概述

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、我们可以在代码里随机生成密钥对

  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. }

2、下载开源RSA密钥生成工具openssl(通常Linux系统都自带该程序),解压缩至独立的文件夹,进入其中的bin目录,执行以下命令:

  1. openssl genrsa -out rsa_private_key.pem
  2. openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out private_key.pem
  3. openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

第一条命令生成原始 RSA私钥文件 rsa_private_key.pem,第二条命令将原始 RSA私钥转换为 pkcs8格式,第三条生成RSA公钥 rsa_public_key.pem
从上面看出通过私钥能生成对应的公钥,因此我们将私钥private_key.pem用在服务器端,公钥发放给android跟ios等前端

代码中的使用

首先我们需要封装写个RSA的工具类,方便加密解密的操作。

  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();
  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. X509EncodedKeySpec keySpec = 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. PKCS8EncodedKeySpec keySpec = 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. BigInteger bigIntModulus = new BigInteger(modulus);
  158. BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
  159. RSAPublicKeySpec keySpec = 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. BigInteger bigIntModulus = new BigInteger(modulus);
  178. BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
  179. RSAPublicKeySpec keySpec = 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. X509EncodedKeySpec keySpec = 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. PKCS8EncodedKeySpec keySpec = 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. BufferedReader br = new BufferedReader(new InputStreamReader(in));
  296. String readLine = null;
  297. StringBuilder sb = new StringBuilder();
  298. while ((readLine = br.readLine()) != null)
  299. {
  300. if (readLine.charAt() == '-')
  301. {
  302. continue;
  303. } else
  304. {
  305. sb.append(readLine);
  306. sb.append('\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. System.out.println("----------RSAPublicKey----------");
  322. System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
  323. System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
  324. System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
  325. System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
  326. }
  327.  
  328. public static void printPrivateKeyInfo(PrivateKey privateKey)
  329. {
  330. RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
  331. System.out.println("----------RSAPrivateKey ----------");
  332. System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
  333. System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
  334. System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
  335. System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
  336.  
  337. }
  338.  
  339. }

上面需要注意的就是加密是有长度限制的,过长的话会抛异常!!!

代码中有些需要使用Base64再转换的,而java中不自带,Android中自带,所以自己写出一个来,方便Java后台使用

  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', '', '', '', '', '', '',
  15. '', '', '', '', '+', '/' };
  16. private static byte[] base64DecodeChars = new byte[]
  17. { -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -,
  18. -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, -, , -, -, -, , , ,
  19. , , , , , , , , -, -, -, -, -, -, -, , , , , , , , , , , , ,
  20. , , , , , , , , , , , , , , -, -, -, -, -, -, , , , ,
  21. , , , , , , , , , , , , , , , , , , , , , , -, -,
  22. -, -, - };
  23.  
  24. /**
  25. * 加密
  26. *
  27. * @param data
  28. * @return
  29. */
  30. public static String encode(byte[] data)
  31. {
  32. StringBuffer sb = new StringBuffer();
  33. int len = data.length;
  34. int i = ;
  35. int b1, b2, b3;
  36. while (i < len)
  37. {
  38. b1 = data[i++] & 0xff;
  39. if (i == len)
  40. {
  41. sb.append(base64EncodeChars[b1 >>> ]);
  42. sb.append(base64EncodeChars[(b1 & 0x3) << ]);
  43. sb.append("==");
  44. break;
  45. }
  46. b2 = data[i++] & 0xff;
  47. if (i == len)
  48. {
  49. sb.append(base64EncodeChars[b1 >>> ]);
  50. sb.append(base64EncodeChars[((b1 & 0x03) << ) | ((b2 & 0xf0) >>> )]);
  51. sb.append(base64EncodeChars[(b2 & 0x0f) << ]);
  52. sb.append("=");
  53. break;
  54. }
  55. b3 = data[i++] & 0xff;
  56. sb.append(base64EncodeChars[b1 >>> ]);
  57. sb.append(base64EncodeChars[((b1 & 0x03) << ) | ((b2 & 0xf0) >>> )]);
  58. sb.append(base64EncodeChars[((b2 & 0x0f) << ) | ((b3 & 0xc0) >>> )]);
  59. sb.append(base64EncodeChars[b3 & 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. StringBuffer sb = new StringBuffer();
  86. byte[] data = null;
  87. data = str.getBytes("US-ASCII");
  88. int len = data.length;
  89. int i = ;
  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 == -);
  98. if (b1 == -)
  99. break;
  100.  
  101. do
  102. {
  103. b2 = base64DecodeChars[data[i++]];
  104. } while (i < len && b2 == -);
  105. if (b2 == -)
  106. break;
  107. sb.append((char) ((b1 << ) | ((b2 & 0x30) >>> )));
  108.  
  109. do
  110. {
  111. b3 = data[i++];
  112. if (b3 == )
  113. return sb.toString().getBytes("iso8859-1");
  114. b3 = base64DecodeChars[b3];
  115. } while (i < len && b3 == -);
  116. if (b3 == -)
  117. break;
  118. sb.append((char) (((b2 & 0x0f) << ) | ((b3 & 0x3c) >>> )));
  119.  
  120. do
  121. {
  122. b4 = data[i++];
  123. if (b4 == )
  124. return sb.toString().getBytes("iso8859-1");
  125. b4 = base64DecodeChars[b4];
  126. } while (i < len && b4 == -);
  127. if (b4 == -)
  128. break;
  129. sb.append((char) (((b3 & 0x03) << ) | b4));
  130. }
  131. return sb.toString().getBytes("iso8859-1");
  132. }
  133.  
  134. }

最后就是真正使用它们了:

  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. btn1.setOnClickListener(this);
  53. btn2.setOnClickListener(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. InputStream inPublic = getResources().getAssets().open("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. InputStream inPrivate = getResources().getAssets().open("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. String decryptStr = 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资源文件夹里了,也可以直接使用字符串得到,上面注释掉了。

后记:后来发现,android的rsa机制和php,java的默认机制有点不同

也就是说android系统的RSA实现是"RSA/None/NoPadding",而标准JDK实现是"RSA/ECB/PKCS1Padding"

具体解决方法http://stackoverflow.com/questions/13556295/rsa-encryption-in-android

稍微作修改一下这里:Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");就行了

修改后的RSAUtils类

  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. private static String RSA1 = "RSA/ECB/PKCS1Padding";
  31. /**
  32. * 随机生成RSA密钥对(默认密钥长度为1024)
  33. *
  34. * @return
  35. */
  36. public static KeyPair generateRSAKeyPair()
  37. {
  38. return generateRSAKeyPair();
  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(RSA1);
  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(RSA1);
  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. X509EncodedKeySpec keySpec = 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. PKCS8EncodedKeySpec keySpec = 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. BigInteger bigIntModulus = new BigInteger(modulus);
  158. BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
  159. RSAPublicKeySpec keySpec = 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. BigInteger bigIntModulus = new BigInteger(modulus);
  178. BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
  179. RSAPublicKeySpec keySpec = 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. X509EncodedKeySpec keySpec = 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. PKCS8EncodedKeySpec keySpec = 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. BufferedReader br = new BufferedReader(new InputStreamReader(in));
  296. String readLine = null;
  297. StringBuilder sb = new StringBuilder();
  298. while ((readLine = br.readLine()) != null)
  299. {
  300. if (readLine.charAt() == '-')
  301. {
  302. continue;
  303. } else
  304. {
  305. sb.append(readLine);
  306. sb.append('\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. System.out.println("----------RSAPublicKey----------");
  322. System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
  323. System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
  324. System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
  325. System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
  326. }
  327.  
  328. public static void printPrivateKeyInfo(PrivateKey privateKey)
  329. {
  330. RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
  331. System.out.println("----------RSAPrivateKey ----------");
  332. System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
  333. System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
  334. System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
  335. System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
  336.  
  337. }
  338.  
  339. }

Android RSA加密解密的更多相关文章

  1. android -------- RSA加密解密算法

    RSA加密算法是一种非对称加密算法.在公开密钥加密和电子商业中RSA被广泛使用 RSA公开密钥密码体制.所谓的公开密钥密码体制就是使用不同的加密密钥与解密密钥,是一种“由已知加密密钥推导出解密密钥在计 ...

  2. 兼容javascript和C#的RSA加密解密算法,对web提交的数据进行加密传输

    Web应用中往往涉及到敏感的数据,由于HTTP协议以明文的形式与服务器进行交互,因此可以通过截获请求的数据包进行分析来盗取有用的信息.虽然https可以对传输的数据进行加密,但是必须要申请证书(一般都 ...

  3. iOS使用Security.framework进行RSA 加密解密签名和验证签名

    iOS 上 Security.framework为我们提供了安全方面相关的api: Security框架提供的RSA在iOS上使用的一些小结 支持的RSA keySize 大小有:512,768,10 ...

  4. openssl evp RSA 加密解密

    openssl evp RSA 加密解密 可以直接使用RSA.h 提供的接口 如下测试使用EVP提供的RSA接口 1. EVP提供的RSA 加密解密 主要接口: int EVP_PKEY_encryp ...

  5. C# 与JAVA 的RSA 加密解密交互,互通,C#使用BouncyCastle来实现私钥加密,公钥解密的方法

    因为C#的RSA加密解密只有公钥加密,私钥解密,没有私钥加密,公钥解密.在网上查了很久也没有很好的实现.BouncyCastle的文档少之又少.很多人可能会说,C#也是可以的,通过Biginteger ...

  6. Cryptopp iOS 使用 RSA加密解密和签名验证签名

    Cryptopp 是一个c++写的功能完善的密码学工具,类似于openssl 官网:https://www.cryptopp.com 以下主要演示Cryptopp 在iOS上的RSA加密解密签名与验证 ...

  7. C# Java间进行RSA加密解密交互

    原文:C# Java间进行RSA加密解密交互 这里,讲一下RSA算法加解密在C#和Java之间交互的问题,这两天纠结了很久,也看了很多其他人写的文章,颇受裨益,但没能解决我的实际问题,终于,还是被我捣 ...

  8. C# Java间进行RSA加密解密交互(二)

    原文:C# Java间进行RSA加密解密交互(二) 接着前面一篇文章C# Java间进行RSA加密解密交互,继续探讨这个问题. 在前面,虽然已经实现了C# Java间进行RSA加密解密交互,但是还是与 ...

  9. C# Java间进行RSA加密解密交互(三)

    原文:C# Java间进行RSA加密解密交互(三) 接着前面一篇C# Java间进行RSA加密解密交互(二)说吧,在上篇中为了实现 /** * RSA加密 * @param text--待加密的明文 ...

随机推荐

  1. BZOJ4568 : [Scoi2016]幸运数字

    树的点分治,每次求出重心后,求出重心到每个点路径上的数的线性基. 对于每个询问,只需要暴力合并两个线性基即可. 时间复杂度$O(60n\log n+60^2q)$. #include<cstdi ...

  2. VR教育旋风来袭,各大公司争先进军虚拟现实教育

    根据国内一份最新的报告显示,VR技术对于提高学生的学习成绩有非常积极的作用,并且通过测试结果来看,无论是对知识的认知还是成绩测试,VR都起到了非常有效的效果. 2016成为VR元年,虚拟现实技术除了在 ...

  3. Android 应用内存优化 之 onLowMemory & onTrimMemory

    OnLowMemory: 是Android提供的API,在系统内存不足,所有后台程序(优先级为background的进程,不是指后台运行的进程)都被杀死时,系统会调用OnLowMemory.OnTri ...

  4. CDOJ 1431 不是图论 Label:Tarjan || Kosarajn

    Time Limit:1000MS     Memory Limit:65535KB     64bit IO Format:%lld & %llu Description 给出一个nn个点, ...

  5. 【BZOJ】3670: [Noi2014]动物园

    http://www.lydsy.com/JudgeOnline/problem.php?id=3670 题意:太水了= = #include <bits/stdc++.h> using ...

  6. 【Eclipse】几个最重要的快捷键

    1几个最重要的快捷键    代码助手:Ctrl+Space(简体中文操作系统是Alt+/) 快速修正:Ctrl+1 单词补全:Alt+/ 打开外部Java文档:Shift+F2   显示搜索对话框:C ...

  7. 获取jQuery对象的第N个DOM元素 && table常用css样式

    获取jQuery对象的第N个DOM元素 1.$(selector).get(N-1) 2.$(selector)[N-1] 注意:.index()方法返回的是一个数,相当于C#中的IndexOf() ...

  8. iOS9 tableVIewCell的分割线不显示,只有在滑动的时候才显示?

    1.如果用6plus模拟器的话,电脑分辨率达不到那么高,因此就看不到分割线. 2.把模拟器换成6s 或 5s,就没问题了.

  9. Cloudera Manager 5和CDH5离线安装

    CDH (Cloudera’s Distribution, including Apache Hadoop),是Hadoop众多分支中的一种,由Cloudera维护,基于稳定版本的Apache Had ...

  10. Windows 下安装使用docker swarm machine docker toolbox

    下载docker 集成安装环境 http://get.daocloud.io/#install-toolbox 这个网站很不错,下载 这个集成了 docker docker-machine ,还有gi ...