任何一个安全的系统里,密码都是不允许明文传输的,一般传输到后台的密码都是经过加密,再由后台解密进行校验的,传统的加密方式就是通过RSA加密

RSA算法概述

我们看看加密算法的历史

对称加密算法

在1976年以前,所有的加密方法都是同一种模式 对称加密算法(Symmetric-key algorithm)
其特点就是如果甲传了一串密文给乙,那么乙必须要知道甲的加密规则才能解密。否则无法解密,这样就导致了加密算法的泄露,影响了系统安全性。

非对称加密算法

1976年,两位美国计算机学家Whitfield Diffie 和 Martin Hellman,提出了一种崭新构思,可以在不直接传递密钥的情况下,完成解密。这被称为“Diffie-Hellman密钥交换算法”

  • (1)甲要传密信给乙,乙先根据某种算法得出本次与甲通信的公钥与私钥
  • (2)乙将公钥传给甲(公钥可以让任何人知道,即使泄露也没有任何关系)
  • (3)甲使用乙传给的公钥加密要发送的信息原文m,发送给乙加密后的密文c
  • (4)乙使用自己的私钥解密密文c,得到信息原文m

如果公钥加密的信息只有私钥解得开,那么只要私钥不泄漏,通信就是安全的。
简而言之,就是接收方只需要发布公钥,以及特定的算法,就可以实现数据安全。

RSA算法

1977年,三位数学家Rivest、Shamir 和 Adleman 设计了一种算法,可以实现非对称加密。这种算法用他们三个人的名字命名,叫做RSA算法
这种算法非常可靠,密钥越长,它就越难破解。根据已经披露的文献,目前被破解的最长RSA密钥是768个二进制位。也就是说,长度超过768位的密钥,还无法破解(至少没人公开宣布)。因此可以认为,1024位的RSA密钥基本安全,2048位的密钥极其安全。

java RSA算法实现

  1. import org.apache.commons.codec.binary.Base64;
  2. import javax.crypto.BadPaddingException;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.IllegalBlockSizeException;
  5. import java.io.ByteArrayOutputStream;
  6. import java.io.IOException;
  7. import java.security.*;
  8. import java.security.interfaces.RSAPrivateKey;
  9. import java.security.interfaces.RSAPublicKey;
  10. import java.security.spec.PKCS8EncodedKeySpec;
  11. import java.security.spec.X509EncodedKeySpec;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. /**
  15. *
  16. * @date 2019/7/31 13:48
  17. */
  18. public class RSAUtils {
  19. /**
  20. * 加密算法RSA
  21. */
  22. public static final String KEY_ALGORITHM = "RSA";
  23. /**
  24. * 签名算法
  25. */
  26. public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
  27. /**
  28. * 获取公钥的key
  29. */
  30. private static final String PUBLIC_KEY = "RSAPublicKey";
  31. /**
  32. * 获取私钥的key
  33. */
  34. private static final String PRIVATE_KEY = "RSAPrivateKey";
  35. /**
  36. * RSA最大加密明文大小
  37. */
  38. private static final int MAX_ENCRYPT_BLOCK = 117;
  39. /**
  40. * RSA最大解密密文大小
  41. */
  42. private static final int MAX_DECRYPT_BLOCK = 128;
  43. /**
  44. * RSA 位数 如果采用2048 上面最大加密和最大解密则须填写: 245 256
  45. */
  46. private static final int INITIALIZE_LENGTH = 1024;
  47. /**
  48. * 私钥
  49. */
  50. private static final String privateKey = "";
  51. /**
  52. * 生成密钥对(公钥和私钥)
  53. *
  54. * @return
  55. * @throws Exception
  56. */
  57. public static Map<String, Object> genKeyPair() throws Exception {
  58. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
  59. keyPairGen.initialize(INITIALIZE_LENGTH);
  60. KeyPair keyPair = keyPairGen.generateKeyPair();
  61. RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  62. RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
  63. Map<String, Object> keyMap = new HashMap<String, Object>(2);
  64. keyMap.put(PUBLIC_KEY, publicKey);
  65. keyMap.put(PRIVATE_KEY, privateKey);
  66. return keyMap;
  67. }
  68. /** */
  69. /**
  70. * 用私钥对信息生成数字签名
  71. *
  72. * @param data 已加密数据
  73. * @return
  74. * @throws Exception
  75. */
  76. public static String sign(byte[] data) throws Exception {
  77. byte[] keyBytes = Base64.decodeBase64(privateKey);
  78. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  79. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  80. PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
  81. Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  82. signature.initSign(privateK);
  83. signature.update(data);
  84. return Base64.encodeBase64String(signature.sign());
  85. }
  86. /**
  87. * 校验数字签名
  88. *
  89. * @param data 已加密数据
  90. * @param publicKey 公钥(BASE64编码)
  91. * @param sign 数字签名
  92. * @return
  93. * @throws Exception
  94. */
  95. public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
  96. byte[] keyBytes = Base64.decodeBase64(publicKey);
  97. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
  98. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  99. PublicKey publicK = keyFactory.generatePublic(keySpec);
  100. Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  101. signature.initVerify(publicK);
  102. signature.update(data);
  103. return signature.verify(Base64.decodeBase64(sign));
  104. }
  105. /**
  106. * <p>
  107. * 私钥解密
  108. *
  109. * @param encryptedData 已加密数据
  110. * @return
  111. * @throws Exception
  112. */
  113. private static byte[] decryptByPrivateKey(byte[] encryptedData) throws Exception {
  114. byte[] keyBytes = Base64.decodeBase64(privateKey);
  115. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  116. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  117. Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
  118. Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
  119. return getBytes(encryptedData, privateK, cipher, Cipher.DECRYPT_MODE, MAX_DECRYPT_BLOCK);
  120. }
  121. /**
  122. * 公钥解密
  123. *
  124. * @param encryptedData 已加密数据
  125. * @param publicKey 公钥(BASE64编码)
  126. * @return
  127. * @throws Exception
  128. */
  129. public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
  130. byte[] keyBytes = Base64.decodeBase64(publicKey);
  131. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
  132. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  133. Key publicK = keyFactory.generatePublic(x509KeySpec);
  134. Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
  135. return getBytes(encryptedData, publicK, cipher, Cipher.DECRYPT_MODE, MAX_DECRYPT_BLOCK);
  136. }
  137. /**
  138. * 公钥加密
  139. *
  140. * @param data 源数据
  141. * @param publicKey 公钥(BASE64编码)
  142. * @return
  143. * @throws Exception
  144. */
  145. private static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
  146. byte[] keyBytes = Base64.decodeBase64(publicKey);
  147. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
  148. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  149. Key publicK = keyFactory.generatePublic(x509KeySpec);
  150. // 对数据加密
  151. Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
  152. return getBytes(data, publicK, cipher, Cipher.ENCRYPT_MODE, MAX_ENCRYPT_BLOCK);
  153. }
  154. /**
  155. * 私钥加密
  156. *
  157. * @param data 源数据
  158. * @return
  159. * @throws Exception
  160. */
  161. public static byte[] encryptByPrivateKey(byte[] data) throws Exception {
  162. byte[] keyBytes = Base64.decodeBase64(privateKey);
  163. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  164. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  165. Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
  166. Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
  167. return getBytes(data, privateK, cipher, Cipher.ENCRYPT_MODE, MAX_ENCRYPT_BLOCK);
  168. }
  169. private static byte[] getBytes(byte[] data, Key privateK, Cipher cipher, int encryptMode, int maxEncryptBlock)
  170. throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
  171. cipher.init(encryptMode, privateK);
  172. int inputLen = data.length;
  173. ByteArrayOutputStream out = new ByteArrayOutputStream();
  174. int offSet = 0;
  175. byte[] cache;
  176. int i = 0;
  177. // 对数据分段加密
  178. while (inputLen - offSet > 0) {
  179. if (inputLen - offSet > maxEncryptBlock) {
  180. cache = cipher.doFinal(data, offSet, maxEncryptBlock);
  181. } else {
  182. cache = cipher.doFinal(data, offSet, inputLen - offSet);
  183. }
  184. out.write(cache, 0, cache.length);
  185. i++;
  186. offSet = i * maxEncryptBlock;
  187. }
  188. byte[] encryptedData = out.toByteArray();
  189. out.close();
  190. return encryptedData;
  191. }
  192. /**
  193. * 获取私钥
  194. *
  195. * @param keyMap 密钥对
  196. * @return
  197. * @throws Exception
  198. */
  199. public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
  200. Key key = (Key) keyMap.get(PRIVATE_KEY);
  201. return Base64.encodeBase64String(key.getEncoded());
  202. }
  203. /**
  204. * 获取公钥
  205. *
  206. * @param keyMap 密钥对
  207. * @return
  208. * @throws Exception
  209. */
  210. public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
  211. Key key = (Key) keyMap.get(PUBLIC_KEY);
  212. return Base64.encodeBase64String(key.getEncoded());
  213. }
  214. /**
  215. * java端公钥加密
  216. */
  217. public static String encryptedDataOnJava(String data, String publicKey) {
  218. try {
  219. data = Base64.encodeBase64String(encryptByPublicKey(data.getBytes(), publicKey));
  220. } catch (Exception e) {
  221. e.printStackTrace();
  222. }
  223. return data;
  224. }
  225. /**
  226. * java端私钥解密
  227. */
  228. public static String decryptDataOnJava(String data){
  229. String temp = "";
  230. byte[] rs = Base64.decodeBase64(data);
  231. try {
  232. temp = new String(decryptByPrivateKey(rs), "UTF-8");
  233. } catch (Exception e) {
  234. return null;
  235. }
  236. return temp;
  237. }
  238. }
  1. 服务器通过 genKeyPair() 方法获得公钥、私钥。
  2. 将公钥发布给通信者(例如前端界面)
  3. 通信者获取公钥用同样的RSA算法加密数据。
  4. 服务器通过私钥进行数据解密

JavaScript RSA算法

  1. 可以通过引入外部RSA算法JS,来实现公钥加密 ```html

```

  1. 如果怕有外网限制,则使用本地文件jsencrypt.min.js 用法是一样的。