BouncyCastleRSA加解密类C#版兼容JAVAPHP(RSAHelper)C# RSAHelper类 实现兼容JAVA,PHP的RSA加解密类
View Code
1///<summary>
2/// 杨鑫
3/// 2012年10⽉29⽇
4///</summary>
5public class RSAHelper
6 {
7///<summary>
8/// 数据加密处理
9///</summary>
10///<param name="text"></param>
11///<returns></returns>
12public static string EncryptRSA( string text)
13 {
14string value = "";
15// System.out.println("encrypt-start:-----------------------------------------------------");
16try
17 {
18//⾮空验证
19if (! string.IsNullOrEmpty(text))
20 {
21string 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
29int len = 117;
30int m = text.Length / len;
31if (m * len != text.Length)
32 {
33 m = m + 1;
34 }
35
36for ( int i = 0; i < m; i++)
37 {
38string temp = "";
39
40if (i < m - 1)
41 {
42 temp = text.Substring(i * len, len); //(i + 1) * len
43 }
44else
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 }
58catch (Exception e)
59 {
60 MessageBox.Show(e.Message);
61 }
62
63// System.out.println("encrypt-end:-----------------------------------------------------");
64
65return value;
66 }
67
68///<summary>
69/// 数据解密处理
70///</summary>
71///<param name="text"></param>
72///<returns></returns>
73public static string DecryptRSA( string text)
74 {
75string value = "";
76// System.out.println("decrypt-start:-----------------------------------------------------");
77try
78 {
79if (! string.IsNullOrEmpty(text))
80 {
81//密码⽂件名
82string password = "Password.pem";
83//私钥⽂件名
84string privateKey = "PrivateKey.pem";
85
86#region 分段解密 解决加密密⽂过长问题
87int len = 172;
88int m = text.Length / len;
89if (m * len != text.Length)
90 {
91 m = m + 1;
92 }
93
94for ( int i = 0; i < m; i++)
95 {
96string temp = "";
97
98if (i < m - 1)
99 {
100 temp = text.Substring(i * len, len);
101 }
102else
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 }
121catch (Exception e)
122 {
123 MessageBox.Show(e.Message);
124 }
125// System.out.println("decrypt-end:-----------------------------------------------------");
126
127return value;
128 }
129
130///<summary>
131/// RSA加密操作 Encrypt⽅法
132///</summary>
133///<param name="DataToEncrypt"></param>
134///<param name="publicKey"></param>
135///<returns></returns>
136private static byte[] Encrypt( byte[] DataToEncrypt, string publicKey)
137 {
138try
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
150byte[] outBytes = c.DoFinal(DataToEncrypt);
151return outBytes;
152 }
153catch (Exception e)
154 {
155 MessageBox.Show(e.Message);
156 }
157
158return 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>
168private static byte[] Decrypt( byte[] input, string privateKey, string password)
169 {
170try
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
181byte[] outBytes = c.DoFinal(input);
182return outBytes;
183 }
184catch (Exception e)
185 {
186 MessageBox.Show(e.Message);
187 }
188return null;
189 }
190
191///<summary>
192/// 解决PHP Base64编码后回车问题
193///</summary>
194///<param name="text"></param>
195///<returns></returns>
196public static String decode64(String text)
197 {
198 String value = "";
199
200try
201 {
202 text = string.IsNullOrEmpty(text) ? "" : text;
203
204int len = 64;
205int m = text.Length / len;
206if (m * len != text.Length)
207 {
208 m = m + 1;
209 }
210
211for ( int i = 0; i < m; i++)
212 {
213 String temp = "";
214
215if (i < m - 1)
216 {
217 temp = text.Substring(i * len, len); //(i + 1) * len
218 value += temp + "\r\n";
219 }
220else
221 {
222 temp = text.Substring(i * len);
223 value += temp;
224 }
225 }
226 }
227catch (Exception e)
228 {
229 MessageBox.Show(e.Message);国外java php
230 }
231
232return value;
233 }
234 }
235
236///<summary>
237/// BouncyCastle 密钥类
238///</summary>
239public class Password : IPasswordFinder
240 {
241private char[] password;
242
243public Password( char[] word)
244 {
245this.password = ( char[])word.Clone();
246 }
247
248public char[] GetPassword()
249 {
250return ( char[])password.Clone();
251 }
252 }
JAVA下的加解密过程 实例代码:
View Code
1package com.jjlg.webinf;
2
3import java.io.File;
4import java.io.FileReader;
5import java.security.Key;
6import java.security.SecureRandom;
7import java.security.Security;
8
pto.Cipher;
10
11import org.bouncycastle.jce.provider.BouncyCastleProvider;
12import org.bouncycastle.openssl.PEMReader;
13import org.bouncycastle.openssl.PasswordFinder;
14
15import com.jjlg.MyFile;
16import com.jjlg.MyString;
17
18import sun.misc.BASE64Decoder;
19import sun.misc.BASE64Encoder;
20
21/**
22 * RSA算法,实现数据的加密解密。
23 *
24 * @author ShaoJiang
25 *
26*/
27public class PhpRsa
28 {
29
30public static void main(String[] args)
31 {
32try
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 = pt(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+ke3GJpyrBUW
50 System.out.println(PhpRsa.decrypt(p));
51
52// String zi =
53// "⼭西省太原市⼩店区abc⼭西省太原市⼩23店区平阳路与平阳路西⼆efa巷交叉⼝往北⽶新康隆456商城好的789你好";
54// zi = new Bytes(), "utf-8");
55// System.out.println(zi);
56//
57// String t = (new BASE64Encoder()).Bytes("utf-8"));
58// String w = new String((new BASE64Decoder()).decodeBuffer(new
59// Bytes())), "utf-8");
60// String e = t.replace("\r\n", "");//
61//
"5bGx6KW/55yB5aSq5Y6f5biC5bCP5bqX5Yy6YWJj5bGx6KW/55yB5aSq5Y6f5biC5bCPMjPlupfljLrlubPpmLPot6/kuI7lubPpmLPot6/opb/kuoxlZmHlt7fkuqTlj4nlj6PlvoDljJfnsbP 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 Bytes(), "utf-8"));
69
70// 中⽂编码测试
71// String str = "王某某";
72// System.out.println("1:" + new Bytes("utf-8"),
73// "gb2312"));
74
75// System.out.println("1:" + new Bytes("gb2312"),
76// "utf-8"));
77
78// String str2 =
79//
"o0glTLeRAaE1LYj6P/jHPQrzUhKozQWSDHSkyv+HbyluAIE7Ao3KPXGWMG2Rg7SAY+G6yCuOQn4DAmwM4QnbQn+I/CUUVCcz8JTco6S6++3I2luZfTMYee6e+KsC+YHXY2VinJ 80// System.out.println(PhpRsa.decrypt(str2));
81
82 }
83catch (Exception e)
84 {
85 e.printStackTrace();
86 }
87 }
88
89public static String encrypt(String text)
90 {
91 String value = "";
92
93// System.out.println("encrypt-start:-----------------------------------------------------");
94
95try
96 {
97if (text != null && text.length() > 0 && !text.equals(""))
98 {
99 Security.addProvider( new BouncyCastleProvider());
100
101 PhpRsa rsa = new PhpRsa();
102 String path = Class().getResource("").getPath();
103// System.out.println(path + "PublicKey.pem");
104 Key publicKey = translatePublicKey( new File(path + "PublicKey.pem"));
105
106 text = ( new BASE64Encoder()).Bytes("utf-8"));
107 text = place("\r", "");
108 text = place("\n", "");
109// System.out.println(text);
110
111int len = 117;
112int m = text.length() / len;
113if (m * len != text.length())
114 {
115 m = m + 1;
116 }
117
118for ( int i = 0; i < m; i++)
119 {
120 String temp = "";
121
122if (i < m - 1)
123 {
124 temp = text.substring(i * len, (i + 1) * len);
125 }
126else
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()).Bytes(), publicKey));
135 temp = place("\r", "");
136 temp = place("\n", "");
137
138 value += temp;
139 }
140
141// System.out.println("encrypt-text:" + text);
142// System.out.println("encrypt-value:" + value);
143 }
144
145 }
146catch (Exception e)
147 {
148 e.printStackTrace();
149 }
150
151// System.out.println("encrypt-end:-----------------------------------------------------");
152
153return value;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论