BouncyCastle RSA加解密类 C#版 兼容JAVA PHP(RSAHelper)

C# RSAHelper类 实现兼容JAVA,PHP的RSA加解密类

View Code
  1 /// <summary>
  2     /// 杨鑫
  3     /// 2012年10月29日
  4     /// </summary>
  5     public class RSAHelper
  6     {
  7         /// <summary>
  8         /// 数据加密处理
  9         /// </summary>
 10         /// <param name="text"></param>
 11         /// <returns></returns>
 12         public static string EncryptRSA(string text)
 13         {
 14             string value = "";
 15             // System.out.println("encrypt-start:-----------------------------------------------------");
 16             try
 17             {
 18                 //非空验证
 19                 if (!string.IsNullOrEmpty(text))
 20                 {
 21                     string publicKey = "PublicKey.pem";
 22 
 23                     #region 分段加密 解决加密明文过长问题
 24 
 25                     //将字符串转为UTF8编码
 26                     text = Convert.ToBase64String(Encoding.GetEncoding("utf-8").GetBytes(text));
 27                     text = text.Replace("\r""").Replace("\n""");
 28 
 29                     int len = 117;
 30                     int m = text.Length / len;
 31                     if (m * len != text.Length)
 32                     {
 33                         m = m + 1;
 34                     }
 35 
 36                     for (int i = 0; i < m; i++)
 37                     {
 38                         string temp = "";
 39 
 40                         if (i < m - 1)
 41                         {
 42                             temp = text.Substring(i * len, len);//(i + 1) * len
 43                         }
 44                         else
 45                         {
 46                             temp = text.Substring(i * len);
 47                         }
 48 
 49                         temp = Convert.ToBase64String(Encrypt(Encoding.GetEncoding("utf-8").GetBytes(temp), publicKey));
 50                         temp = temp.Replace("\r""").Replace("\n""");
 51 
 52                         value += temp;
 53                     }
 54 
 55                     #endregion
 56                 }
 57             }
 58             catch (Exception e)
 59             {
 60                 MessageBox.Show(e.Message);
 61             }
 62 
 63             // System.out.println("encrypt-end:-----------------------------------------------------");
 64 
 65             return value;
 66         }
 67 
 68         /// <summary>
 69         /// 数据解密处理
 70         /// </summary>
 71         /// <param name="text"></param>
 72         /// <returns></returns>
 73         public static string DecryptRSA(string text)
 74         {
 75             string value = "";
 76             // System.out.println("decrypt-start:-----------------------------------------------------");
 77             try
 78             {
 79                 if (!string.IsNullOrEmpty(text))
 80                 {
 81                     //密码文件名
 82                     string password = "Password.pem";
 83                     //私钥文件名
 84                     string privateKey = "PrivateKey.pem";
 85 
 86                     #region 分段解密 解决加密密文过长问题
 87                     int len = 172;
 88                     int m = text.Length / len;
 89                     if (m * len != text.Length)
 90                     {
 91                         m = m + 1;
 92                     }
 93 
 94                     for (int i = 0; i < m; i++)
 95                     {
 96                         string temp = "";
 97 
 98                         if (i < m - 1)
 99                         {
100                             temp = text.Substring(i * len, len);
101                         }
102                         else
103                         {
104                             temp = text.Substring(i * len);
105                         }
106 
107                         //解决PHP中文问题
108                         temp = decode64(temp);
109 
110                         temp = Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(temp), privateKey, password));
111                         value += temp;
112 
113                     }
114                     #endregion
115 
116                     //解决PHP中文问题
117                     value = decode64(value);
118                     value = Encoding.UTF8.GetString(Convert.FromBase64String(value));
119                 }
120             }
121             catch (Exception e)
122             {
123                 MessageBox.Show(e.Message);
124             }
125             // System.out.println("decrypt-end:-----------------------------------------------------");
126 
127             return value;
128         }
129 
130         /// <summary>
131         /// RSA加密操作 Encrypt方法
132         /// </summary>
133         /// <param name="DataToEncrypt"></param>
134         /// <param name="publicKey"></param>
135         /// <returns></returns>
136         private static byte[] Encrypt(byte[] DataToEncrypt, string publicKey)
137         {
138             try
139             {
140                 PemReader r = new PemReader(new StreamReader(publicKey));//载入公钥文件
141                 Object readObject = r.ReadObject();
142                 //实例化参数实例
143                 AsymmetricKeyParameter pubKey = (AsymmetricKeyParameter)readObject;
144                 IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与JAVA中解密的参数一致
145                 c.Init(true, pubKey);
146 
147                 //int blockSize = c.GetBlockSize();
148                 //c.ProcessBytes(DataToEncrypt);
149 
150                 byte[] outBytes = c.DoFinal(DataToEncrypt);
151                 return outBytes;
152             }
153             catch (Exception e)
154             {
155                 MessageBox.Show(e.Message);
156             }
157 
158             return null;
159         }
160 
161         /// <summary>
162         /// RSA解密操作 Decrypt方法
163         /// </summary>
164         /// <param name="input"></param>
165         /// <param name="privateKey"></param>
166         /// <param name="password"></param>
167         /// <returns></returns>
168         private static byte[] Decrypt(byte[] input, string privateKey, string password)
169         {
170             try
171             {
172                 PemReader r = new PemReader(new StreamReader(privateKey), new Password(new StreamReader(password).ReadToEnd().ToCharArray()));     //载入私钥
173                 Object readObject = r.ReadObject();
174                 AsymmetricKeyParameter priKey = (AsymmetricKeyParameter)readObject;
175                 IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
176                 c.Init(false, priKey);
177 
178                 //int blockSize = c.GetBlockSize();
179                 //c.ProcessBytes(input);
180 
181                 byte[] outBytes = c.DoFinal(input);
182                 return outBytes;
183             }
184             catch (Exception e)
185             {
186                 MessageBox.Show(e.Message);
187             }
188             return null;
189         }
190 
191         /// <summary>
192         /// 解决PHP Base64编码后回车问题 
193         /// </summary>
194         /// <param name="text"></param>
195         /// <returns></returns>
196         public static String decode64(String text)
197         {
198             String value = "";
199 
200             try
201             {
202                 text = string.IsNullOrEmpty(text) ? "" : text;
203 
204                 int len = 64;
205                 int m = text.Length / len;
206                 if (m * len != text.Length)
207                 {
208                     m = m + 1;
209                 }
210 
211                 for (int i = 0; i < m; i++)
212                 {
213                     String temp = "";
214 
215                     if (i < m - 1)
216                     {
217                         temp = text.Substring(i * len, len);//(i + 1) * len
218                         value += temp + "\r\n";
219                     }
220                     else
221                     {
222                         temp = text.Substring(i * len);
223                         value += temp;
224                     }
225                 }
226             }
227             catch (Exception e)
228             {
229                 MessageBox.Show(e.Message);
230             }
231 
232             return value;
233         }
234     }
235 
236     /// <summary>
237     /// BouncyCastle 密钥类
238     /// </summary>
239     public class Password : IPasswordFinder
240     {
241         private char[] password;
242 
243         public Password(char[] word)
244         {
245             this.password = (char[])word.Clone();
246         }
247 
248         public char[] GetPassword()
249         {
250             return (char[])password.Clone();
251         }
252     }

JAVA下的加解密过程 实例代码:

 

View Code
  1 package com.jjlg.webinf;
  2 
  3 import java.io.File;
  4 import java.io.FileReader;
  5 import java.security.Key;
  6 import java.security.SecureRandom;
  7 import java.security.Security;
  8 
  9 import javax.crypto.Cipher;
 10 
 11 import org.bouncycastle.jce.provider.BouncyCastleProvider;
 12 import org.bouncycastle.openssl.PEMReader;
 13 import org.bouncycastle.openssl.PasswordFinder;
 14 
 15 import com.jjlg.MyFile;
 16 import com.jjlg.MyString;
 17 
 18 import sun.misc.BASE64Decoder;
 19 import sun.misc.BASE64Encoder;
 20 
 21 /**
 22  * RSA算法,实现数据的加密解密。
 23  * 
 24  * @author ShaoJiang
 25  * 
 26  */
 27 public class PhpRsa
 28 {
 29 
 30     public static void main(String[] args)
 31     {
 32         try
 33         {
 34 
 35             // 字符串截取测试
 36             // String str = "1234567890";
 37             // System.out.println(str.substring(0, 5));
 38             // System.out.println(str.substring(5, 10));
 39 
 40             // 加密解密测试
 41             String text = "一二三四五六七八九十1234567890一二三四五六七八九十1234567890一二三四五六七八九十1234567890一二三四五六七八九十1234567890一二三四五六七八九十1234567890";
 42             String encodeString = PhpRsa.encrypt(text);
 43             String decodeString = PhpRsa.decrypt(encodeString);
 44 
 45             System.out.println("text=" + text);
 46             System.out.println("encodeString=" + encodeString);
 47             System.out.println("decodeString=" + decodeString);
 48 
 49             String p = "gO9NZbjwx7bf+MfWPKYP2WkZI72jUwz/EC031V+WkWLEigo04vbvsRyPxv0wJYYVuJ3xQk7OgonTWYfDa3EGXVN45j64SMhxhOdN5242h+ke3GJpyrBUWi/waVc/conAL46sNe6tCtGW7iU/EOl415XoUTX6ns7LdHDRPsxj3d8=";
 50             System.out.println(PhpRsa.decrypt(p));
 51 
 52             // String zi =
 53             // "山西省太原市小店区abc山西省太原市小23店区平阳路与平阳路西二efa巷交叉口往北米新康隆456商城好的789你好";
 54             // zi = new String(zi.getBytes(), "utf-8");
 55             // System.out.println(zi);
 56             //
 57             // String t = (new BASE64Encoder()).encode(zi.getBytes("utf-8"));
 58             // String w = new String((new BASE64Decoder()).decodeBuffer(new
 59             // String(t.getBytes())), "utf-8");
 60             // String e = t.replace("\r\n", "");//
 61             // "5bGx6KW/55yB5aSq5Y6f5biC5bCP5bqX5Yy6YWJj5bGx6KW/55yB5aSq5Y6f5biC5bCPMjPlupfljLrlubPpmLPot6/kuI7lubPpmLPot6/opb/kuoxlZmHlt7fkuqTlj4nlj6PlvoDljJfnsbPmlrDlurfpmoY0NTbllYbln47lpb3nmoQ3ODnkvaDlpb0=";
 62             // e = new String((new BASE64Decoder()).decodeBuffer(e));
 63             // t = t.replace("\r\n", "");
 64             // System.out.println(t);
 65             // System.out.println(t.length());
 66             // System.out.println(w);
 67             // System.out.println(w.length());
 68             // System.out.println(new String(e.getBytes(), "utf-8"));
 69 
 70             // 中文编码测试
 71             // String str = "王某某";
 72             // System.out.println("1:" + new String(str.getBytes("utf-8"),
 73             // "gb2312"));
 74 
 75             // System.out.println("1:" + new String(str.getBytes("gb2312"),
 76             // "utf-8"));
 77 
 78             // String str2 =
 79             // "o0glTLeRAaE1LYj6P/jHPQrzUhKozQWSDHSkyv+HbyluAIE7Ao3KPXGWMG2Rg7SAY+G6yCuOQn4DAmwM4QnbQn+I/CUUVCcz8JTco6S6++3I2luZfTMYee6e+KsC+YHXY2VinJ7ubN6hCtKWLckbC68oXBXtKEHfPQ48vZnmcWk=";
 80             // System.out.println(PhpRsa.decrypt(str2));
 81 
 82         }
 83         catch (Exception e)
 84         {
 85             e.printStackTrace();
 86         }
 87     }
 88 
 89     public static String encrypt(String text)
 90     {
 91         String value = "";
 92 
 93         // System.out.println("encrypt-start:-----------------------------------------------------");
 94 
 95         try
 96         {
 97             if (text != null && text.length() > 0 && !text.equals(""))
 98             {
 99                 Security.addProvider(new BouncyCastleProvider());
100 
101                 PhpRsa rsa = new PhpRsa();
102                 String path = rsa.getClass().getResource("").getPath();
103                 // System.out.println(path + "PublicKey.pem");
104                 Key publicKey = translatePublicKey(new File(path + "PublicKey.pem"));
105 
106                 text = (new BASE64Encoder()).encode(text.getBytes("utf-8"));
107                 text = text.replace("\r", "");
108                 text = text.replace("\n", "");
109                 // System.out.println(text);
110 
111                 int len = 117;
112                 int m = text.length() / len;
113                 if (m * len != text.length())
114                 {
115                     m = m + 1;
116                 }
117 
118                 for (int i = 0; i < m; i++)
119                 {
120                     String temp = "";
121 
122                     if (i < m - 1)
123                     {
124                         temp = text.substring(i * len, (i + 1) * len);
125                     }
126                     else
127                     {
128                         temp = text.substring(i * len);
129                     }
130 
131                     // System.out.println(temp);
132                     // System.out.println(temp.length());
133 
134                     temp = (new BASE64Encoder()).encode(PhpRsa.encrypt(temp.getBytes(), publicKey));
135                     temp = temp.replace("\r", "");
136                     temp = temp.replace("\n", "");
137 
138                     value += temp;
139                 }
140 
141                 // System.out.println("encrypt-text:" + text);
142                 // System.out.println("encrypt-value:" + value);
143             }
144 
145         }
146         catch (Exception e)
147         {
148             e.printStackTrace();
149         }
150 
151         // System.out.println("encrypt-end:-----------------------------------------------------");
152 
153         return value;
154     }
155 
156     public static String decrypt(String text)
157     {
158         String value = "";
159 
160         // System.out.println("decrypt-start:-----------------------------------------------------");
161 
162         try
163         {
164             if (text != null && text.length() > 0 && !text.equals(""))
165             {
166                 Security.addProvider(new BouncyCastleProvider());
167 
168                 PhpRsa rsa = new PhpRsa();
169                 String path = rsa.getClass().getResource("").getPath();
170                 String password = MyFile.readTxt(path + "Password.pem", "utf-8").replace("\n", "");
171 
172                 Key privateKey = translatePrivateKey(new File(path + "PrivateKey.pem"), password);
173 
174                 // 分段解密
175                 int len = 172;
176                 int m = text.length() / len;
177                 if (m * len != text.length())
178                 {
179                     m = m + 1;
180                 }
181 
182                 for (int i = 0; i < m; i++)
183                 {
184                     String temp = "";
185 
186                     if (i < m - 1)
187                     {
188                         temp = text.substring(i * len, (i + 1) * len);
189                     }
190                     else
191                     {
192                         temp = text.substring(i * len);
193                     }
194 
195                     // System.out.println(temp);
196                     // System.out.println(temp.length());
197                     temp = PhpRsa.decode64(temp);
198 
199                     // System.out.println(temp);
200                     // System.out.println(temp.length());
201 
202                     temp = new String(PhpRsa.decrypt((new BASE64Decoder()).decodeBuffer(temp), privateKey), "utf-8");
203 
204                     // System.out.println(temp);
205                     // System.out.println(temp.length());
206 
207                     value += temp;
208                 }
209 
210                 value = PhpRsa.decode64(value);
211                 value = new String((new BASE64Decoder()).decodeBuffer(value), "utf-8");
212 
213                 // System.out.println("dencrypt-text:" + text);
214                 // System.out.println("dencrypt-value:" + value);
215             }
216         }
217         catch (Exception e)
218         {
219             e.printStackTrace();
220         }
221 
222         // System.out.println("decrypt-end:-----------------------------------------------------");
223 
224         return value;
225     }
226 
227     public static String decode64(String text)
228     {
229         String value = "";
230 
231         try
232         {
233 
234             text = MyString.format(text);
235 
236             int len = 64;
237             int m = text.length() / len;
238             if (m * len != text.length())
239             {
240                 m = m + 1;
241             }
242 
243             for (int i = 0; i < m; i++)
244             {
245                 String temp = "";
246 
247                 if (i < m - 1)
248                 {
249                     temp = text.substring(i * len, (i + 1) * len);
250                     value += temp + "\r\n";
251                 }
252                 else
253                 {
254                     temp = text.substring(i * len);
255                     value += temp;
256                 }
257             }
258 
259             // System.out.println(value);
260 
261         }
262         catch (Exception e)
263         {
264             e.printStackTrace();
265         }
266 
267         return value;
268     }
269 
270     static public Key translatePublicKey(File pem)
271     {
272         try
273         {
274             PEMReader reader = new PEMReader(new FileReader(pem));
275             Key key = (Key) reader.readObject();
276             reader.close();
277 
278             return key;
279         }
280         catch (Exception e)
281         {
282             e.printStackTrace();
283         }
284 
285         return null;
286     }
287 
288     static public Key translatePrivateKey(File pem, final String password)
289     {
290         try
291         {
292             PEMReader reader = new PEMReader(new FileReader(pem), new PasswordFinder()
293             {
294                 public char[] getPassword()
295                 {
296                     return password.toCharArray();
297                 }
298             });
299             Key key = (Key) reader.readObject();
300             reader.close();
301             return key;
302         }
303         catch (Exception e)
304         {
305             e.printStackTrace();
306         }
307 
308         return null;
309     }
310 
311     public static byte[] encrypt(byte[] input, Key publicKey)
312     {
313         try
314         {
315             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
316             cipher.init(Cipher.ENCRYPT_MODE, publicKey, new SecureRandom());
317             return cipher.doFinal(input);
318         }
319         catch (Exception e)
320         {
321             e.printStackTrace();
322         }
323 
324         return null;
325     }
326 
327     public static byte[] decrypt(byte[] input, Key privateKey)
328     {
329         try
330         {
331             Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
332             cipher.init(Cipher.DECRYPT_MODE, privateKey);
333             return cipher.doFinal(input);
334         }
335         catch (Exception e)
336         {
337             e.printStackTrace();
338         }
339 
340         return null;
341     }
342 }

 

 

posted @ 2012-10-30 13:53  YaSin  阅读(3616)  评论(0编辑  收藏  举报