RSA加密算法互通-java、.net、golang

其他都是废话,直接上代码,我们不生产代码,我们只是代码的搬运工。

java版本RSA算法:

  1 package cn.com.gome.utils;
  2 
  3 import java.io.FileReader;
  4 import java.io.FileWriter;
  5 import java.io.IOException;
  6 import java.io.Reader;
  7 import java.io.Writer;
  8 import java.math.BigInteger;
  9 import java.security.NoSuchAlgorithmException;
 10 import java.security.SecureRandom;
 11 import java.util.HashMap;
 12 import java.util.Map;
 13 
 14 import org.bouncycastle.asn1.ASN1Object;
 15 import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
 16 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
 17 import org.bouncycastle.crypto.AsymmetricBlockCipher;
 18 import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
 19 import org.bouncycastle.crypto.InvalidCipherTextException;
 20 import org.bouncycastle.crypto.encodings.PKCS1Encoding;
 21 import org.bouncycastle.crypto.engines.RSAEngine;
 22 import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
 23 import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
 24 import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
 25 import org.bouncycastle.crypto.params.RSAKeyParameters;
 26 import org.bouncycastle.crypto.util.PrivateKeyFactory;
 27 import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
 28 import org.bouncycastle.crypto.util.PublicKeyFactory;
 29 import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
 30 import org.bouncycastle.util.encoders.Base64;
 31 import org.bouncycastle.util.io.pem.PemObject;
 32 import org.bouncycastle.util.io.pem.PemReader;
 33 import org.bouncycastle.util.io.pem.PemWriter;
 34 
 35 import sun.misc.BASE64Encoder;
 36 
 37 /**
 38  * sra加密
 39  * @author
 40  *
 41  */
 42 public class RSAUtils {
 43 
 44     /**
 45      * 生成公钥和私钥
 46      * @throws NoSuchAlgorithmException 
 47      *
 48      */
 49     public static Map<String,String> getKeys(Boolean isGenerateFile) throws NoSuchAlgorithmException{
 50         Map<String,String> map = new HashMap<String,String>();
 51         //生成参数配置
 52         RSAKeyPairGenerator rsaKeyPairGenerator = new RSAKeyPairGenerator();
 53         //设置秘钥生成参数
 54         SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
 55         //secureRandom.setSeed(seed);
 56         RSAKeyGenerationParameters rsaKeyGenerationParameters = new RSAKeyGenerationParameters(BigInteger.valueOf(65537), secureRandom, 1024, 16);
 57         rsaKeyPairGenerator.init(rsaKeyGenerationParameters);
 58         
 59         //生成秘钥
 60         AsymmetricCipherKeyPair keyPair = rsaKeyPairGenerator.generateKeyPair();
 61         RSAKeyParameters publicKey = (RSAKeyParameters) keyPair.getPublic();//公钥  
 62         RSAKeyParameters privateKey = (RSAKeyParameters) keyPair.getPrivate();//私钥 
 63         
 64         //使用x509证书进行处理
 65         SubjectPublicKeyInfo subjectPublicKeyInfo;
 66         PrivateKeyInfo privateKeyInfo;
 67         try {
 68             subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);
 69             privateKeyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(privateKey);
 70         
 71             //pem格式处理
 72             ASN1Object asn1ObjectPublic = subjectPublicKeyInfo.toASN1Primitive();
 73             byte[] publicInfoByte = asn1ObjectPublic.getEncoded("DER");
 74 
 75             ASN1Object asn1ObjectPrivate = privateKeyInfo.toASN1Primitive();
 76             byte[] privateInfoByte = asn1ObjectPrivate.getEncoded("DER");
 77             
 78             //写入map中
 79             map.put("public", new String((new BASE64Encoder()).encode(publicInfoByte)));
 80             map.put("private", new String((new BASE64Encoder()).encode(privateInfoByte)));
 81 //            map.put("public", new String(Base64.decode(publicInfoByte)));
 82 //            map.put("private", new String(Base64.decode(privateInfoByte)));
 83             
 84             //生成文件
 85             if(isGenerateFile){
 86                 //写入文件private
 87                 Writer r = new FileWriter("private.pem");
 88                 PemWriter pemWriter = new PemWriter(r);
 89                 pemWriter.writeObject(new PemObject("PRIVATE KEY",Base64.encode(privateInfoByte)));
 90                 //写入硬盘
 91                 pemWriter.flush();
 92                 pemWriter.close();
 93                 //public
 94                 Writer rp = new FileWriter("public.pem");
 95                 PemWriter pemWriterp = new PemWriter(rp);
 96                 pemWriterp.writeObject(new PemObject("PUBLIC KEY",Base64.encode(publicInfoByte)));
 97                 //写入硬盘
 98                 pemWriterp.flush();
 99                 pemWriterp.close();
100             }
101         } catch (IOException e) {
102             // TODO Auto-generated catch block
103             e.printStackTrace();
104         }
105         return map;
106     }
107     
108     /**
109      * 获取pem格式
110      * @return
111      * @throws NoSuchAlgorithmException
112      */
113     public static Map<String,String> getKeysPem(Map<String,String> map) throws NoSuchAlgorithmException{
114         
115         if (map==null){
116             map = getKeys(false);
117         }
118         
119         StringBuffer str_Public_Key = new StringBuffer();
120         str_Public_Key.append("-----BEGIN PUBLIC KEY-----");
121         str_Public_Key.append("\n");
122         str_Public_Key.append(map.get("public"));
123         str_Public_Key.append("\n");
124         str_Public_Key.append("-----END PUBLIC KEY-----");
125         map.put("public", str_Public_Key.toString());
126         
127         StringBuffer str_Private_Key = new StringBuffer();
128         str_Private_Key.append("-----BEGIN PRIVATE KEY-----");
129         str_Private_Key.append("\n");
130         str_Private_Key.append(map.get("private"));
131         str_Private_Key.append("\n");
132         str_Private_Key.append("-----END PRIVATE KEY-----");
133         map.put("private", str_Private_Key.toString());
134         
135         return map;
136     }
137 
138     
139     /**
140      * 解密
141      * @return
142      */
143     public static byte[] decryptPrivateKey(String privateKey,byte[] data){
144         
145         //获取原始数据并进行64为解码
146         byte[] bytes = new byte[0];
147         
148         AsymmetricBlockCipher engine = new PKCS1Encoding(new RSAEngine());
149         Reader r = null;
150         try {
151             if(privateKey==null ||privateKey==""){
152                 r = new FileReader("private.pem");
153                 //获取秘钥
154                 PemReader pemReader = new PemReader(r);     //载入私钥
155                 PemObject readObject = pemReader.readPemObject();
156                 //生成key
157                 AsymmetricKeyParameter priKey = PrivateKeyFactory.createKey(Base64.decode(readObject.getContent()));
158                 engine.init(false, priKey);
159                 //进行
160                 pemReader.close();
161             }else{
162                 //生成key
163                 AsymmetricKeyParameter priKey = PrivateKeyFactory.createKey(Base64.decode(privateKey.getBytes()));
164                 engine.init(false, priKey);
165             }
166             //解密
167             bytes = engine.processBlock(data, 0, data.length);
168 
169         } catch (InvalidCipherTextException | IOException e) {
170             e.printStackTrace();
171         }finally{
172             if(r!=null){
173                 try {
174                     r.close();
175                 } catch (IOException e) {
176                     e.printStackTrace();
177                 }
178             }
179         }
180         return bytes;
181     }
182     
183     /**
184      * 加密
185      * @param publicKey
186      * @param data
187      * @return
188      */
189     public static byte[] encryptByPublicKey(String publicKey,byte[] data){
190         //获取原始数据并进行64为解码
191         byte[] bytes = new byte[0];
192         
193         AsymmetricBlockCipher engine = new PKCS1Encoding(new RSAEngine());
194         Reader r = null;
195         try {
196             if(publicKey==null || publicKey==""){
197                 r = new FileReader("public.pem");
198                 //获取秘钥
199                 PemReader pemReader = new PemReader(r);     //载入私钥
200                 PemObject readObject = pemReader.readPemObject();
201                 AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(Base64.decode(readObject.getContent()));
202                 engine.init(true, pubKey);
203                 
204                 //关闭pem读取流
205                 pemReader.close();
206             }else{
207                 AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(Base64.decode(publicKey.getBytes()));
208                 engine.init(true, pubKey);
209             }
210             //解密
211             bytes = engine.processBlock(data, 0, data.length);
212             
213         } catch (InvalidCipherTextException | IOException e) {
214             e.printStackTrace();
215         }finally{
216             if(r!=null){
217                 try {
218                     r.close();
219                 } catch (IOException e) {
220                     // TODO Auto-generated catch block
221                     e.printStackTrace();
222                 }
223             }
224         }
225         return bytes;
226     }
227     
228 }
View Code

golang版本 RSA算法:

1、生成钥匙

  1 package rsahelper
  2 
  3 import (
  4     "crypto/rand"
  5     "crypto/rsa"
  6     "crypto/x509"
  7     "encoding/asn1"
  8     "encoding/pem"
  9     "flag"
 10     "log"
 11     "os"
 12     "sync"
 13 )
 14 
 15 //当前类的指针
 16 var rsaGkey *rsaGenerateKey
 17 
 18 //同步锁
 19 var rsaGenerateKeyonce sync.Once
 20 
 21 //实现单例
 22 type rsaGenerateKey struct {
 23 }
 24 
 25 //生成密钥
 26 func RSAGenerateKeys() *rsaGenerateKey {
 27     rsaGenerateKeyonce.Do(func() {
 28         rsaGkey = new(rsaGenerateKey)
 29     })
 30     return rsaGkey
 31 }
 32 
 33 //生成文件
 34 func (r *rsaGenerateKey) GenerateKey() {
 35     var bits int
 36     flag.IntVar(&bits, "b", 1024, "密钥长度,默认为1024位")
 37     if err := r.GenRsaKey(bits); err != nil {
 38         log.Fatal("密钥文件生成失败!")
 39     }
 40 }
 41 
 42 //生成公私私钥--return(私钥,公私,错误)
 43 func (r *rsaGenerateKey) Generate() ([]byte, []byte, error) {
 44     //定义变量并赋值
 45     var bits int
 46     bits = 1024 //密钥长度,默认为128位"
 47     //主线程中只用定义一次
 48     //flag.IntVar(&bits, "bint", 512, "密钥长度,默认为128位")
 49     // 生成私钥文件
 50     privateKey, err := rsa.GenerateMultiPrimeKey(rand.Reader, 3, bits)
 51     if err != nil {
 52         return nil, nil, err
 53     }
 54     //生成私钥
 55     derStream := MarshalPKCS8PrivateKey(privateKey)
 56     blockpri := &pem.Block{
 57         Type:  "PRIVATE KEY",
 58         Bytes: derStream,
 59     }
 60     // 生成公钥文件
 61     publicKey := &privateKey.PublicKey
 62     derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
 63     if err != nil {
 64         return nil, nil, err
 65     }
 66     blockpub := &pem.Block{
 67         Type:  "PUBLIC KEY",
 68         Bytes: derPkix,
 69     }
 70 
 71     return pem.EncodeToMemory(blockpri), pem.EncodeToMemory(blockpub), nil
 72 }
 73 
 74 //转化成pkcs8
 75 func MarshalPKCS8PrivateKey(key *rsa.PrivateKey) []byte {
 76     info := struct {
 77         Version             int
 78         PrivateKeyAlgorithm []asn1.ObjectIdentifier
 79         PrivateKey          []byte
 80     }{}
 81     info.Version = 0
 82     info.PrivateKeyAlgorithm = make([]asn1.ObjectIdentifier, 1)
 83     info.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
 84     info.PrivateKey = x509.MarshalPKCS1PrivateKey(key)
 85 
 86     k, err := asn1.Marshal(info)
 87     if err != nil {
 88         log.Panic(err.Error())
 89     }
 90     return k
 91 }
 92 
 93 //生成文件
 94 func (r *rsaGenerateKey) GenRsaKey(bits int) error {
 95     // 生成私钥文件
 96     privateKey, err := rsa.GenerateKey(rand.Reader, bits)
 97     if err != nil {
 98         return err
 99     }
100     derStream := x509.MarshalPKCS1PrivateKey(privateKey)
101     block := &pem.Block{
102         Type:  "RSA PRIVATE KEY",
103         Bytes: derStream,
104     }
105     file, err := os.Create("private.pem")
106     if err != nil {
107         return err
108     }
109     err = pem.Encode(file, block)
110     if err != nil {
111         return err
112     }
113     // 生成公钥文件
114     publicKey := &privateKey.PublicKey
115     derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
116     if err != nil {
117         return err
118     }
119     block = &pem.Block{
120         Type:  "PUBLIC KEY",
121         Bytes: derPkix,
122     }
123     file, err = os.Create("public.pem")
124     if err != nil {
125         return err
126     }
127     err = pem.Encode(file, block)
128     if err != nil {
129         return err
130     }
131     return nil
132 }
View Code

2、加密解密

 1 package rsahelper
 2 
 3 import (
 4     "crypto/rand"
 5     "crypto/rsa"
 6     "crypto/x509"
 7     "encoding/pem"
 8     "errors"
 9     "io/ioutil"
10     "os"
11     "sync"
12 )
13 
14 //rsa
15 type rsaUtils struct {
16     PrivateKey []byte
17     PublicKey  []byte
18 }
19 
20 //当前类的指针
21 var rasUtilsClass *rsaUtils
22 
23 //同步锁
24 var rasUtilsClassonce sync.Once
25 
26 //rsa工具
27 func RSAUtils() *rsaUtils {
28     rasUtilsClassonce.Do(func() {
29         rasUtilsClass = new(rsaUtils)
30     })
31     //返回处理对象
32     return rasUtilsClass
33 }
34 
35 func (r *rsaUtils) init() bool {
36     //读取文件
37     pubkey, err := r.readFile("public.pem")
38     if err != nil {
39         return false
40     }
41     r.PublicKey = pubkey
42 
43     //获取私钥
44     prikey, err := r.readFile("private.pem")
45     if err != nil {
46         return false
47     }
48     r.PrivateKey = prikey
49     return true
50 }
51 
52 func (r *rsaUtils) readFile(filePth string) ([]byte, error) {
53     f, err := os.Open(filePth)
54     if err != nil {
55         return nil, err
56     }
57     return ioutil.ReadAll(f)
58 }
59 
60 // 加密
61 func (r *rsaUtils) RsaEncrypt(origData []byte, publicKey []byte) ([]byte, error) {
62     block, _ := pem.Decode(publicKey)
63     if block == nil {
64         return nil, errors.New("public key error")
65     }
66     pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
67     if err != nil {
68         return nil, err
69     }
70     pub := pubInterface.(*rsa.PublicKey)
71     return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
72 }
73 
74 // 解密
75 func (r *rsaUtils) RsaDecrypt(ciphertext []byte, privateKey []byte) ([]byte, error) {
76     block, _ := pem.Decode(privateKey)
77     if block == nil {
78         return nil, errors.New("private key error!")
79     }
80     priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
81     if err != nil {
82         return nil, err
83     }
84     priKey := priv.(*rsa.PrivateKey)
85     return rsa.DecryptPKCS1v15(rand.Reader, priKey, ciphertext)
86 }
View Code

.net版本的RSA算法:

  1 using Org.BouncyCastle.Asn1;
  2 using Org.BouncyCastle.Asn1.Pkcs;
  3 using Org.BouncyCastle.Asn1.X509;
  4 using Org.BouncyCastle.Crypto;
  5 using Org.BouncyCastle.Crypto.Encodings;
  6 using Org.BouncyCastle.Crypto.Engines;
  7 using Org.BouncyCastle.Crypto.Generators;
  8 using Org.BouncyCastle.Crypto.Parameters;
  9 using Org.BouncyCastle.Math;
 10 using Org.BouncyCastle.Pkcs;
 11 using Org.BouncyCastle.Security;
 12 using Org.BouncyCastle.Utilities.IO.Pem;
 13 using Org.BouncyCastle.X509;
 14 using System;
 15 using System.Collections.Generic;
 16 using System.IO;
 17 using System.Linq;
 18 using System.Text;
 19 using System.Threading.Tasks;
 20 
 21 namespace Sys.Common.Helper
 22 {
 23     /// <summary>
 24     /// RSA加密解密
 25     /// </summary>
 26     public class RSAHelper
 27     {
 28         /// <summary>
 29         /// 生成公钥和私钥
 30         /// </summary>
 31         /// <param name="isGenerateFile"></param>
 32         /// <returns></returns>
 33         public static Dictionary<string, string> getKeys(bool isGenerateFile)
 34         {
 35             Dictionary<String, String> dic = new Dictionary<String, String>();
 36             //生成参数配置
 37             RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
 38             //设置秘钥生成参数
 39             SecureRandom secureRandom = SecureRandom.GetInstance("SHA1PRNG");
 40             //secureRandom.setSeed(seed);
 41             RsaKeyGenerationParameters rsaKeyGenerationParameters = new RsaKeyGenerationParameters(BigInteger.ValueOf(65537), secureRandom, 1024, 16);
 42             rsaKeyPairGenerator.Init(rsaKeyGenerationParameters);
 43 
 44             //生成秘钥
 45             AsymmetricCipherKeyPair keyPair = rsaKeyPairGenerator.GenerateKeyPair();
 46             RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public;//公钥  
 47             RsaKeyParameters privateKey = (RsaKeyParameters)keyPair.Private;//私钥 
 48 
 49             //使用x509证书进行处理
 50             SubjectPublicKeyInfo subjectPublicKeyInfo;
 51             PrivateKeyInfo privateKeyInfo;
 52             try
 53             {
 54                 subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
 55                 privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
 56 
 57                 //pem格式处理
 58                 Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
 59                 byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("DER");
 60 
 61                 Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
 62                 byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("DER");
 63 
 64                 //写入map中
 65                 dic.Add("public", Convert.ToBase64String(publicInfoByte));
 66                 dic.Add("private", Convert.ToBase64String(privateInfoByte));
 67 
 68                 //生成文件
 69                 if (isGenerateFile)
 70                 {
 71                     //写入文件private
 72                     TextWriter r = new StreamWriter("private.pem");
 73                     PemWriter pemWriter = new PemWriter(r);
 74                     PemObjectGenerator priPem = new PemObject("PRIVATE KEY", System.Text.Encoding.Default.GetBytes(Convert.ToBase64String(privateInfoByte)));
 75                     pemWriter.WriteObject(priPem);
 76                     //写入硬盘
 77                     pemWriter.Writer.Flush(); //写入文件
 78                     pemWriter.Writer.Dispose(); //手动释放资源
 79                     pemWriter.Writer.Close(); //关闭资源
 80                     //public
 81                     TextWriter rp = new StreamWriter("public.pem");
 82                     PemWriter pemWriterp = new PemWriter(rp);
 83                     PemObjectGenerator pubPem = new PemObject("PUBLIC KEY", System.Text.Encoding.Default.GetBytes(Convert.ToBase64String(publicInfoByte)));
 84                     pemWriterp.WriteObject(pubPem);
 85                     //写入硬盘
 86                     pemWriterp.Writer.Flush(); //写入文件
 87                     pemWriterp.Writer.Dispose(); //手动释放资源
 88                     pemWriterp.Writer.Close(); //关闭资源
 89                 }
 90             }
 91             catch (Exception e)
 92             {
 93                 throw e;
 94             }
 95             return dic;
 96         }
 97 
 98         /// <summary>
 99         /// 生成公钥和私钥
100         /// </summary>
101         /// <param name="map"></param>
102         /// <returns></returns>
103         public static Dictionary<String, String> getKeysPem(Dictionary<String, String> dic)
104         {
105 
106             if (dic == null)
107             {
108                 dic = getKeys(false);
109             }
110 
111             StringBuilder str_Public_Key = new StringBuilder();
112             str_Public_Key.Append("-----BEGIN PUBLIC KEY-----");
113             str_Public_Key.Append("\n");
114             string pubKey = string.Empty;
115             dic.TryGetValue("public", out pubKey);
116             str_Public_Key.Append(pubKey);
117             str_Public_Key.Append("\n");
118             str_Public_Key.Append("-----END PUBLIC KEY-----");
119             dic.Add("public", str_Public_Key.ToString());
120 
121             StringBuilder str_Private_Key = new StringBuilder();
122             str_Private_Key.Append("-----BEGIN PRIVATE KEY-----");
123             str_Private_Key.Append("\n");
124             string priKey = string.Empty;
125             dic.TryGetValue("private", out priKey);
126             str_Private_Key.Append(priKey);
127             str_Private_Key.Append("\n");
128             str_Private_Key.Append("-----END PRIVATE KEY-----");
129             dic.Add("private", str_Private_Key.ToString());
130 
131             return dic;
132         }
133 
134 
135         /// <summary>
136         /// 解密
137         /// </summary>
138         /// <param name="privateKey">不是pem格式</param>
139         /// <param name="data"></param>
140         /// <returns></returns>
141         public static byte[] decryptPrivateKey(String privateKey, byte[] data)
142         {
143 
144             //获取原始数据并进行64为解码
145             byte[] bytes = new byte[0];
146 
147             IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
148             TextReader r = null;
149             try
150             {
151                 if (privateKey == null || privateKey == "")
152                 {
153                     r = new StreamReader("private.pem");
154                     //获取秘钥
155                     PemReader pemReader = new PemReader(r);     //载入私钥
156                     PemObject readObject = pemReader.ReadPemObject();
157                     //生成key
158                     AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(System.Text.Encoding.Default.GetString(readObject.Content)));
159                     engine.Init(false, priKey);
160                     //进行
161                     pemReader.Reader.Dispose();
162                     pemReader.Reader.Close();
163                 }
164                 else
165                 {
166                     //生成key
167                     AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
168                     engine.Init(false, priKey);
169                 }
170                 //解密
171                 bytes = engine.ProcessBlock(data, 0, data.Length);
172 
173             }
174             catch (Exception e)
175             {
176                 throw e;
177             }
178             finally
179             {
180                 if (r != null)
181                 {
182                     r.Dispose(); //手动释放资源
183                     r.Close();
184                 }
185             }
186             return bytes;
187         }
188 
189         /// <summary>
190         /// 加密
191         /// </summary>
192         /// <param name="publicKey">不是pem格式</param>
193         /// <param name="data"></param>
194         /// <returns></returns>
195         public static byte[] encryptByPublicKey(String publicKey, byte[] data)
196         {
197             //获取原始数据并进行64为解码
198             byte[] bytes = new byte[0];
199 
200             IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
201             TextReader r = null;
202             try
203             {
204                 if (publicKey == null || publicKey == "")
205                 {
206                     r = new StreamReader("public.pem");
207                     //获取秘钥
208                     PemReader pemReader = new PemReader(r);     //载入私钥
209                     PemObject readObject = pemReader.ReadPemObject();
210                     AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(Convert.FromBase64String(System.Text.Encoding.Default.GetString(readObject.Content)));
211                     engine.Init(true, pubKey);
212 
213                     //关闭pem读取流
214                     pemReader.Reader.Dispose();
215                     pemReader.Reader.Close();
216                 }
217                 else
218                 {
219                     AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
220                     engine.Init(true, pubKey);
221                 }
222                 //解密
223                 bytes = engine.ProcessBlock(data, 0, data.Length);
224 
225             }
226             catch (Exception e)
227             {
228                 throw e;
229             }
230             finally
231             {
232                 r.Dispose();
233                 r.Close();
234             }
235             return bytes;
236         }
237     }
238 }
View Code

搬完收工,希望可以帮助到需要帮助的同学。

posted @ 2017-04-14 15:26  linuxone  阅读(2215)  评论(0编辑  收藏  举报
kaochuan