概述
RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式分解却极其困 难,因此可以将乘积公开作为加密密钥,即公钥,而两个大素数组合成私钥。公钥是可发布的供任何人使用,私钥则为自己所有,供解密之用。关于RSA其它需要了解的知识,参考维基百科:http://zh.wikipedia.org/zh-cn/RSA%E5%8A%A0%E5%AF%86%E6%BC%94%E7%AE%97%E6%B3%95
在项目开发中对于一些比较敏感的信息需要对其进行加密处理,我们就可以使用RSA这种非对称加密算法来对数据进行加密处理。
使用
秘钥对的生成
1、我们可以在代码里随机生成密钥对
[java] view plain copy
1. /**
2. * 随机生成RSA密钥对
3. *
4. * @param keyLength
5. * 密钥长度,范围:512~2048<br>
6. * 一般1024
7. * @return
8. */
9. public static KeyPair generateRSAKeyPair(int keyLength)
10. {
11. try
12. {
13. KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
14. kpg.initialize(keyLength);
15. return kpg.genKeyPair();
16. catch (NoSuchAlgorithmException e)
17. {
18. e.printStackTrace();
19. return null;
20. }
21. }
通过这方法我们得到KeyPair后就可以调用 keyPair.getPrivate() 和 pair.getPublic()得到 私钥 和 公钥了。不过实际我们一般是使用2的方法把生成的密钥对保存起来,密钥自己保存,比如服务端,把公钥给客户端(Android)用于加密需要发送的数据,最后服务端根据私钥吧客户端加密的信息解密再处理。
2、通过OpenSSl工具生成密钥对
OpenSSl工具下载:OpenSSl工具 (64位的也可使用)使用OpenSSl工具生成密钥对的过程如下:
首先双击打开bin文件夹下的openssl.exe,打开之后是一个命令行窗口:
然后通过如下命令生成私钥:
[plain] view plain copy
1. genrsa -out rsa_private_key.pem 1024
这条命令是让openssl随机生成了一份私钥,加密长度是1024位, 密钥长度,范围:512~2048。执行完命令后就可在bin文件夹下看到rsa_private_key.pem文件了。
用文本类工具打开可看到里面的内容:
[plain] view plain copy
1. -----BEGIN RSA PRIVATE KEY-----
2. MIICXQIBAAKBgQCfRTdcPIH10gT9f31rQuIInLwe7fl2dtEJ93gTmjE9c2H+kLVE
3. NWgECiJVQ5sonQNfwToMKdO0b3Olf4pgBKeLThraz/L3nYJYlbqjHC3jTjUnZc0l
4. uumpXGsox62+PuSGBlfb8zJO6hix4GV/vhyQVCpG9aYqgE7zyTRZYX9byQIDAQAB
5. AoGAO9+sYRtKC9xJDfcocfMxv+UT/1ic6EDgcqu6Uzwq+Jvwod9KlXqyQJqCr6T7
6. pjfodc3RAZOTx4gCZJverBvz053RH5GawCdocEgaqbXAAWJOhA+9IEU0NUud7ckF
7. yDko0QXLoGP9tanrMEt5zMqt8QxDyl6Xcij3mk8rivOgBJECQQDNTO6dZX8xCozc
8. Ne0gzC53Gv/KQXANBBHMr7WkKUb2i5+tXkEJ5z3abx2ppEQXDr4AgJH8Gtbm6K7t
9. EHV4ov4FAkEAxppD/iiT1/SVQq20be8CsiHpsjTPiestWQWdm1Qn/Y2nAkGkpCFp
10. yEdUvVDPtQhRN9EqNggNAnwg5kMvsuwN9QJAfHBhQe4/hk5Kyz+0l+irUW6AFOxN
11. KtaIo3TtuK98X/yJsOAstAACMeCgLi9vRjqdWFiWJCVwlU38mZ0cVx8UsQJBALzt
12. M5Er+LiPKw5rQCD0JZRfPnkQU/3XgyQUe4Gv5PsHLcCvwXeBcafcc3hEz9JfPyPi
13. Dk2oCvg6LPHfKBkFBaECQQCODcKX6DBWiyVxmPaJOOcF63KpCYDPkjeovIUHro1x
14. ElR2GrQCC/9Q4C4vruOhBQ+vX8NMPnO6NBy5TLGDwMyc
15. -----END RSA PRIVATE KEY-----
这里面的内容是标准的ASCII字符,中间的一大串字符就是私钥数据了。
然后通过如下命令生成公钥:
[plain] view plain copy
1. rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout
打开文件看下里面的内容:
[plain] view plain copy
可以看到是跟私钥的文件类似的。
1. -----BEGIN PUBLIC KEY-----
2. MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfRTdcPIH10gT9f31rQuIInLwe
3. 7fl2dtEJ93gTmjE9c2H+kLVENWgECiJVQ5sonQNfwToMKdO0b3Olf4pgBKeLThra
4. z/L3nYJYlbqjHC3jTjUnZc0luumpXGsox62+PuSGBlfb8zJO6hix4GV/vhyQVCpG
5. 9aYqgE7zyTRZYX9byQIDAQAB
6. -----END PUBLIC KEY-----
PKCS#8编码,命令如下:
[plain] view plain copy
- pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt
这条命令的结果依然是在bin文件夹生成了pkcs8_rsa_private_key.pem文件,打开内容如下:
[plain] view plain copy
1. -----BEGIN PRIVATE KEY-----
2. MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9FN1w8gfXSBP1/
3. fWtC4gicvB7t+XZ20Qn3eBOaMT1zYf6QtUQ1aAQKIlVDmyidA1/BOgwp07Rvc6V/
4. imAEp4tOGtrP8vedgliVuqMcLeNONSdlzSW66alcayjHrb4+5IYGV9vzMk7qGLHg
5. ZX++HJBUKkb1piqATvPJNFlhf1vJAgMBAAECgYA736xhG0oL3EkN9yhx8zG/5RP/
6. WJzoQOByq7pTPCr4m/Ch30qVerJAmoKvpPumN+h1zdEBk5PHiAJkm96sG/PTndEf
7. kZrAJ2hwSBqptcABYk6ED70gRTQ1S53tyQXIOSjRBcugY/21qeswS3nMyq3xDEPK
8. XpdyKPeaTyuK86AEkQJBAM1M7p1lfzEKjNw17SDMLnca/8pBcA0EEcyvtaQpRvaL
9. n61eQQnnPdpvHamkRBcOvgCAkfwa1uboru0QdXii/gUCQQDGmkP+KJPX9JVCrbRt
10. 7wKyIemyNM+J6y1ZBZ2bVCf9jacCQaSkIWnIR1S9UM+1CFE30So2CA0CfCDmQy+y
11. 7A31AkB8cGFB7j+GTkrLP7SX6KtRboAU7E0q1oijdO24r3xf/Imw4Cy0AAIx4KAu
12. L29GOp1YWJYkJXCVTfyZnRxXHxSxAkEAvO0zkSv4uI8rDmtAIPQllF8+eRBT/deD
13. JBR7ga/k+wctwK/Bd4Fxp9xzeETP0l8/I+IOTagK+Dos8d8oGQUFoQJBAI4Nwpfo
14. MFaLJXGY9ok45wXrcqkJgM+SN6i8hQeujXESVHYatAIL/1DgLi+u46EFD69fw0w+
15. c7o0HLlMsYPAzJw=
16. -----END PRIVATE KEY-----
可以看到中间的私钥内容有所变化了,这样的私钥我们在代码里就方便使用了。
以上的密钥文件使用时需要注意吧头和尾的字符串去掉,我们只取中间的内容。
代码中的使用
首先我们需要封装写个RSA的工具类,方便加密解密的操作。
[java] view plain copy
1. package com.example.rsa;
2.
3. import java.io.BufferedReader;
4. import java.io.IOException;
5. import java.io.InputStream;
6. import java.io.InputStreamReader;
7. import java.math.BigInteger;
8. import java.security.KeyFactory;
9. import java.security.KeyPair;
10. import java.security.KeyPairGenerator;
11. import java.security.NoSuchAlgorithmException;
12. import java.security.PrivateKey;
13. import java.security.PublicKey;
14. import java.security.interfaces.RSAPrivateKey;
15. import java.security.interfaces.RSAPublicKey;
16. import java.security.spec.InvalidKeySpecException;
17. import java.security.spec.PKCS8EncodedKeySpec;
18. import java.security.spec.RSAPublicKeySpec;
19. import java.security.spec.X509EncodedKeySpec;
20.
21. import javax.crypto.Cipher;
22.
23. /**
24. * @author Mr.Zheng
25. * @date 2014年8月22日 下午1:44:23
26. */
27. public final class RSAUtils
28. {
29. private static String RSA = "RSA";
30.
31. /**
32. * 随机生成RSA密钥对(默认密钥长度为1024)
33. *
34. * @return
35. */
36. public static KeyPair generateRSAKeyPair()
37. {
38. return generateRSAKeyPair(1024);
39. }
40.
41. /**
42. * 随机生成RSA密钥对
43. *
44. * @param keyLength
45. * 密钥长度,范围:512~2048<br>
46. * 一般1024
47. * @return
48. */
49. public static KeyPair generateRSAKeyPair(int keyLength)
50. {
51. try
52. {
53. KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
54. kpg.initialize(keyLength);
55. return kpg.genKeyPair();
56. catch (NoSuchAlgorithmException e)
57. {
58. e.printStackTrace();
59. return null;
60. }
61. }
62.
63. /**
64. * 用公钥加密 <br>
65. * 每次加密的字节数,不能超过密钥的长度值减去11
66. *
67. * @param data
68. * 需加密数据的byte数据
69. * @param pubKey
70. * 公钥
71. * @return 加密后的byte型数据
72. */
73. public static byte[] encryptData(byte[] data, PublicKey publicKey)
74. {
75. try
76. {
77. Cipher cipher = Cipher.getInstance(RSA);
78. // 编码前设定编码方式及密钥
79. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
80. // 传入编码数据并返回编码结果
81. return cipher.doFinal(data);
82. catch (Exception e)
83. {
84. e.printStackTrace();
85. return null;
86. }
87. }
88.
89. /**
90. * 用私钥解密
91. *
92. * @param encryptedData
93. * 经过encryptedData()加密返回的byte数据
94. * @param privateKey
95. * 私钥
96. * @return
97. */
98. public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
99. {
100. try
101. {
102. Cipher cipher = Cipher.getInstance(RSA);
103. cipher.init(Cipher.DECRYPT_MODE, privateKey);
104. return cipher.doFinal(encryptedData);
105. catch (Exception e)
106. {
107. return null;
108. }
109. }
110.
111. /**
112. * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
113. *
114. * @param keyBytes
115. * @return
116. * @throws NoSuchAlgorithmException
117. * @throws InvalidKeySpecException
118. */
119. public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
120. InvalidKeySpecException
121. {
122. new X509EncodedKeySpec(keyBytes);
123. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
124. PublicKey publicKey = keyFactory.generatePublic(keySpec);
125. return publicKey;
126. }
127.
128. /**
129. * 通过私钥byte[]将公钥还原,适用于RSA算法
130. *
131. * @param keyBytes
132. * @return
133. * @throws NoSuchAlgorithmException
134. * @throws InvalidKeySpecException
135. */
136. public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
137. InvalidKeySpecException
138. {
139. new PKCS8EncodedKeySpec(keyBytes);
140. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
141. PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
142. return privateKey;
143. }
144.
145. /**
146. * 使用N、e值还原公钥
147. *
148. * @param modulus
149. * @param publicExponent
150. * @return
151. * @throws NoSuchAlgorithmException
152. * @throws InvalidKeySpecException
153. */
154. public static PublicKey getPublicKey(String modulus, String publicExponent)
155. throws NoSuchAlgorithmException, InvalidKeySpecException
156. {
157. new BigInteger(modulus);
158. new BigInteger(publicExponent);
159. new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
160. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
161. PublicKey publicKey = keyFactory.generatePublic(keySpec);
162. return publicKey;
163. }
164.
165. /**
166. * 使用N、d值还原私钥
167. *
168. * @param modulus
169. * @param privateExponent
170. * @return
171. * @throws NoSuchAlgorithmException
172. * @throws InvalidKeySpecException
173. */
174. public static PrivateKey getPrivateKey(String modulus, String privateExponent)
175. throws NoSuchAlgorithmException, InvalidKeySpecException
176. {
177. new BigInteger(modulus);
178. new BigInteger(privateExponent);
179. new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
180. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
181. PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
182. return privateKey;
183. }
184.
185. /**
186. * 从字符串中加载公钥
187. *
188. * @param publicKeyStr
189. * 公钥数据字符串
190. * @throws Exception
191. * 加载公钥时产生的异常
192. */
193. public static PublicKey loadPublicKey(String publicKeyStr) throws Exception
194. {
195. try
196. {
197. byte[] buffer = Base64Utils.decode(publicKeyStr);
198. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
199. new X509EncodedKeySpec(buffer);
200. return (RSAPublicKey) keyFactory.generatePublic(keySpec);
201. catch (NoSuchAlgorithmException e)
202. {
203. throw new Exception("无此算法");
204. catch (InvalidKeySpecException e)
205. {
206. throw new Exception("公钥非法");
207. catch (NullPointerException e)
208. {
209. throw new Exception("公钥数据为空");
210. }
211. }
212.
213. /**
214. * 从字符串中加载私钥<br>
215. * 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
216. *
217. * @param privateKeyStr
218. * @return
219. * @throws Exception
220. */
221. public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception
222. {
223. try
224. {
225. byte[] buffer = Base64Utils.decode(privateKeyStr);
226. // X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
227. new PKCS8EncodedKeySpec(buffer);
228. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
229. return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
230. catch (NoSuchAlgorithmException e)
231. {
232. throw new Exception("无此算法");
233. catch (InvalidKeySpecException e)
234. {
235. throw new Exception("私钥非法");
236. catch (NullPointerException e)
237. {
238. throw new Exception("私钥数据为空");
239. }
240. }
241.
242. /**
243. * 从文件中输入流中加载公钥
244. *
245. * @param in
246. * 公钥输入流
247. * @throws Exception
248. * 加载公钥时产生的异常
249. */
250. public static PublicKey loadPublicKey(InputStream in) throws Exception
251. {
252. try
253. {
254. return loadPublicKey(readKey(in));
255. catch (IOException e)
256. {
257. throw new Exception("公钥数据流读取错误");
258. catch (NullPointerException e)
259. {
260. throw new Exception("公钥输入流为空");
261. }
262. }
263.
264. /**
265. * 从文件中加载私钥
266. *
267. * @param keyFileName
268. * 私钥文件名
269. * @return 是否成功
270. * @throws Exception
271. */
272. public static PrivateKey loadPrivateKey(InputStream in) throws Exception
273. {
274. try
275. {
276. return loadPrivateKey(readKey(in));
277. catch (IOException e)
278. {
279. throw new Exception("私钥数据读取错误");
280. catch (NullPointerException e)
281. {
282. throw new Exception("私钥输入流为空");
283. }
284. }
285.
286. /**
287. * 读取密钥信息
288. *
289. * @param in
290. * @return
291. * @throws IOException
292. */
293. private static String readKey(InputStream in) throws IOException
294. {
295. new BufferedReader(new InputStreamReader(in));
296. null;
297. new StringBuilder();
298. while ((readLine = br.readLine()) != null)
299. {
300. if (readLine.charAt(0) == '-')
301. {
302. continue;
303. else
304. {
305. sb.append(readLine);
306. '\r');
307. }
308. }
309.
310. return sb.toString();
311. }
312.
313. /**
314. * 打印公钥信息
315. *
316. * @param publicKey
317. */
318. public static void printPublicKeyInfo(PublicKey publicKey)
319. {
320. RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
321. "----------RSAPublicKey----------");
322. "Modulus.length=" + rsaPublicKey.getModulus().bitLength());
323. "Modulus=" + rsaPublicKey.getModulus().toString());
324. "PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
325. "PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
326. }
327.
328. public static void printPrivateKeyInfo(PrivateKey privateKey)
329. {
330. RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
331. "----------RSAPrivateKey ----------");
332. "Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
333. "Modulus=" + rsaPrivateKey.getModulus().toString());
334. "PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
335. "PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
336.
337. }
338.
339. }
上面需要注意的就是加密是有长度限制的,过长的话会抛异常!!!
加密的明文长度不能超过RSA密钥的长度-11,比如1024位的,明文长度不能超过117。
密文的长度总是密钥的长度的一半,比如1024位的,密文长度是64,如果是1032位,密文长度是65位。
代码中有些需要使用Base64再转换的,而java中不自带,Android中自带,所以自己写出一个来,方便Java后台使用
[java] view plain copy
1. package com.example.rsa;
2.
3. import java.io.UnsupportedEncodingException;
4.
5. /**
6. * @author Mr.Zheng
7. * @date 2014年8月22日 下午9:50:28
8. */
9. public class Base64Utils
10. {
11. private static char[] base64EncodeChars = new char[]
12. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
13. 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
14. 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
15. '6', '7', '8', '9', '+', '/' };
16. private static byte[] base64DecodeChars = new byte[]
17. 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
18. 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
19. 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
20. 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
21. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
22. 1, -1, -1 };
23.
24. /**
25. * 加密
26. *
27. * @param data
28. * @return
29. */
30. public static String encode(byte[] data)
31. {
32. new StringBuffer();
33. int len = data.length;
34. int i = 0;
35. int b1, b2, b3;
36. while (i < len)
37. {
38. 0xff;
39. if (i == len)
40. {
41. 2]);
42. 0x3) << 4]);
43. "==");
44. break;
45. }
46. 0xff;
47. if (i == len)
48. {
49. 2]);
50. 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
51. 0x0f) << 2]);
52. "=");
53. break;
54. }
55. 0xff;
56. 2]);
57. 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
58. 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
59. 0x3f]);
60. }
61. return sb.toString();
62. }
63.
64. /**
65. * 解密
66. *
67. * @param str
68. * @return
69. */
70. public static byte[] decode(String str)
71. {
72. try
73. {
74. return decodePrivate(str);
75. catch (UnsupportedEncodingException e)
76. {
77. e.printStackTrace();
78. }
79. return new byte[]
80. {};
81. }
82.
83. private static byte[] decodePrivate(String str) throws UnsupportedEncodingException
84. {
85. new StringBuffer();
86. byte[] data = null;
87. "US-ASCII");
88. int len = data.length;
89. int i = 0;
90. int b1, b2, b3, b4;
91. while (i < len)
92. {
93.
94. do
95. {
96. b1 = base64DecodeChars[data[i++]];
97. while (i < len && b1 == -1);
98. if (b1 == -1)
99. break;
100.
101. do
102. {
103. b2 = base64DecodeChars[data[i++]];
104. while (i < len && b2 == -1);
105. if (b2 == -1)
106. break;
107. char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
108.
109. do
110. {
111. b3 = data[i++];
112. if (b3 == 61)
113. return sb.toString().getBytes("iso8859-1");
114. b3 = base64DecodeChars[b3];
115. while (i < len && b3 == -1);
116. if (b3 == -1)
117. break;
118. char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
119.
120. do
121. {
122. b4 = data[i++];
123. if (b4 == 61)
124. return sb.toString().getBytes("iso8859-1");
125. b4 = base64DecodeChars[b4];
126. while (i < len && b4 == -1);
127. if (b4 == -1)
128. break;
129. char) (((b3 & 0x03) << 6) | b4));
130. }
131. return sb.toString().getBytes("iso8859-1");
132. }
133.
134. }
最后就是真正使用它们了:
[java] view plain copy
1. package com.example.rsa;
2.
3. import java.io.InputStream;
4. import java.security.PrivateKey;
5. import java.security.PublicKey;
6.
7. import android.app.Activity;
8. import android.os.Bundle;
9. import android.util.Base64;
10. import android.view.View;
11. import android.view.View.OnClickListener;
12. import android.widget.Button;
13. import android.widget.EditText;
14.
15. public class MainActivity extends Activity implements OnClickListener
16. {
17. private Button btn1, btn2;// 加密,解密
18. private EditText et1, et2, et3;// 需加密的内容,加密后的内容,解密后的内容
19.
20. /* 密钥内容 base64 code */
21. private static String PUCLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfRTdcPIH10gT9f31rQuIInLwe"
22. "\r" + "7fl2dtEJ93gTmjE9c2H+kLVENWgECiJVQ5sonQNfwToMKdO0b3Olf4pgBKeLThra" + "\r"
23. "z/L3nYJYlbqjHC3jTjUnZc0luumpXGsox62+PuSGBlfb8zJO6hix4GV/vhyQVCpG" + "\r"
24. "9aYqgE7zyTRZYX9byQIDAQAB" + "\r";
25. private static String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9FN1w8gfXSBP1/"
26. "\r" + "fWtC4gicvB7t+XZ20Qn3eBOaMT1zYf6QtUQ1aAQKIlVDmyidA1/BOgwp07Rvc6V/" + "\r"
27. "imAEp4tOGtrP8vedgliVuqMcLeNONSdlzSW66alcayjHrb4+5IYGV9vzMk7qGLHg" + "\r"
28. "ZX++HJBUKkb1piqATvPJNFlhf1vJAgMBAAECgYA736xhG0oL3EkN9yhx8zG/5RP/" + "\r"
29. "WJzoQOByq7pTPCr4m/Ch30qVerJAmoKvpPumN+h1zdEBk5PHiAJkm96sG/PTndEf" + "\r"
30. "kZrAJ2hwSBqptcABYk6ED70gRTQ1S53tyQXIOSjRBcugY/21qeswS3nMyq3xDEPK" + "\r"
31. "XpdyKPeaTyuK86AEkQJBAM1M7p1lfzEKjNw17SDMLnca/8pBcA0EEcyvtaQpRvaL" + "\r"
32. "n61eQQnnPdpvHamkRBcOvgCAkfwa1uboru0QdXii/gUCQQDGmkP+KJPX9JVCrbRt" + "\r"
33. "7wKyIemyNM+J6y1ZBZ2bVCf9jacCQaSkIWnIR1S9UM+1CFE30So2CA0CfCDmQy+y" + "\r"
34. "7A31AkB8cGFB7j+GTkrLP7SX6KtRboAU7E0q1oijdO24r3xf/Imw4Cy0AAIx4KAu" + "\r"
35. "L29GOp1YWJYkJXCVTfyZnRxXHxSxAkEAvO0zkSv4uI8rDmtAIPQllF8+eRBT/deD" + "\r"
36. "JBR7ga/k+wctwK/Bd4Fxp9xzeETP0l8/I+IOTagK+Dos8d8oGQUFoQJBAI4Nwpfo" + "\r"
37. "MFaLJXGY9ok45wXrcqkJgM+SN6i8hQeujXESVHYatAIL/1DgLi+u46EFD69fw0w+" + "\r" + "c7o0HLlMsYPAzJw="
38. "\r";
39.
40. @Override
41. protected void onCreate(Bundle savedInstanceState)
42. {
43. super.onCreate(savedInstanceState);
44. setContentView(R.layout.activity_main);
45. initView();
46. }
47.
48. private void initView()
49. {
50. btn1 = (Button) findViewById(R.id.btn1);
51. btn2 = (Button) findViewById(R.id.btn2);
52. this);
53. this);
54.
55. et1 = (EditText) findViewById(R.id.et1);
56. et2 = (EditText) findViewById(R.id.et2);
57. et3 = (EditText) findViewById(R.id.et3);
58. }
59.
60. @Override
61. public void onClick(View v)
62. {
63. switch (v.getId())
64. {
65. // 加密
66. case R.id.btn1:
67. String source = et1.getText().toString().trim();
68. try
69. {
70. // 从字符串中得到公钥
71. // PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY);
72. // 从文件中得到公钥
73. "rsa_public_key.pem");
74. PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);
75. // 加密
76. byte[] encryptByte = RSAUtils.encryptData(source.getBytes(), publicKey);
77. // 为了方便观察吧加密后的数据用base64加密转一下,要不然看起来是乱码,所以解密是也是要用Base64先转换
78. String afterencrypt = Base64Utils.encode(encryptByte);
79. et2.setText(afterencrypt);
80. catch (Exception e)
81. {
82. e.printStackTrace();
83. }
84. break;
85. // 解密
86. case R.id.btn2:
87. String encryptContent = et2.getText().toString().trim();
88. try
89. {
90. // 从字符串中得到私钥
91. // PrivateKey privateKey = RSAUtils.loadPrivateKey(PRIVATE_KEY);
92. // 从文件中得到私钥
93. "pkcs8_rsa_private_key.pem");
94. PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
95. // 因为RSA加密后的内容经Base64再加密转换了一下,所以先Base64解密回来再给RSA解密
96. byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(encryptContent), privateKey);
97. new String(decryptByte);
98. et3.setText(decryptStr);
99. catch (Exception e)
100. {
101. e.printStackTrace();
102. }
103. break;
104. default:
105. break;
106. }
107. }
108.
109. }
我把密钥放到assest资源文件夹里了,也可以直接使用字符串得到,上面注释掉了。
最后我们来看下效果吧: