RSA加密解密

今天药忘吃喽~ 2022-08-02 07:30 289阅读 0赞

package com.isoftstone.cms.common.utils;

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Random;

import javax.crypto.Cipher;
import javax.servlet.http.HttpSession;

public class RSAUtils {
/**
* 生成公钥和私钥
* @throws NoSuchAlgorithmException
*
*/
public static HashMap getKeys() throws NoSuchAlgorithmException{
HashMap map = new HashMap();
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(“RSA”, new org.bouncycastle.jce.provider.BouncyCastleProvider());
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
map.put(“public”, publicKey);
map.put(“private”, privateKey);
return map;
}
/**
* 使用模和指数生成RSA公钥
*
*
* @param modulus
* 模
* @param exponent
* 指数
* @return
*/
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
try {
BigInteger b1 = new BigInteger(modulus);
BigInteger b2 = new BigInteger(exponent);
KeyFactory keyFactory = KeyFactory.getInstance(“RSA”, new org.bouncycastle.jce.provider.BouncyCastleProvider());
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

  1. /\*\*
  2. \* 使用模和指数生成RSA私钥
  3. \* /None/NoPadding
  4. \*
  5. \* @param modulus
  6. \*
  7. \* @param exponent
  8. \* 指数
  9. \* @return
  10. \*/
  11. public static RSAPrivateKey getPrivateKey(String modulus, String exponent) \{
  12. try \{
  13. BigInteger b1 = new BigInteger(modulus);
  14. BigInteger b2 = new BigInteger(exponent);
  15. KeyFactory keyFactory = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
  16. RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
  17. return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
  18. \} catch (Exception e) \{
  19. e.printStackTrace();
  20. return null;
  21. \}
  22. \}
  23. /\*\*
  24. \* 公钥加密
  25. \*
  26. \* @param data
  27. \* @param publicKey
  28. \* @return
  29. \* @throws Exception
  30. \*/
  31. public static String encryptByPublicKey(String data, RSAPublicKey publicKey)
  32. throws Exception \{
  33. Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
  34. cipher.init(Cipher.ENCRYPT\_MODE, publicKey);
  35. // 模长
  36. int key\_len = publicKey.getModulus().bitLength() / 8;
  37. // 加密数据长度 <= 模长-11
  38. String\[\] datas = splitString(data, key\_len - 11);
  39. String mi = "";
  40. //如果明文长度大于模长-11则要分组加密
  41. for (String s : datas) \{
  42. mi += bcd2Str(cipher.doFinal(s.getBytes()));
  43. \}
  44. return mi;
  45. \}
  46. /\*\*
  47. \* 私钥解密
  48. \*
  49. \* @param data
  50. \* @param privateKey
  51. \* @return
  52. \* @throws Exception
  53. \*/
  54. public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
  55. throws Exception \{
  56. Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
  57. cipher.init(Cipher.DECRYPT\_MODE, privateKey);
  58. //模长
  59. int key\_len = privateKey.getModulus().bitLength() / 8;
  60. byte\[\] bytes = data.getBytes();
  61. byte\[\] bcd = ASCII\_To\_BCD(bytes, bytes.length);
  62. //System.err.println(bcd.length);
  63. //如果密文长度大于模长则要分组解密
  64. String ming = "";
  65. byte\[\]\[\] arrays = splitArray(bcd, key\_len);
  66. for(byte\[\] arr : arrays)\{
  67. ming += new String(cipher.doFinal(arr));
  68. \}
  69. return ming;
  70. \}
  71. /\*\*
  72. \* 私钥加密
  73. \*
  74. \* @param data
  75. \* @param publicKey
  76. \* @return
  77. \* @throws Exception
  78. \*/
  79. public static String encryptByPrivateKey(String data, RSAPrivateKey privateKey)
  80. throws Exception \{
  81. Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
  82. cipher.init(Cipher.ENCRYPT\_MODE, privateKey);
  83. // 模长
  84. int key\_len = privateKey.getModulus().bitLength() / 8;
  85. // 加密数据长度 <= 模长-11
  86. String\[\] datas = splitString(data, key\_len - 11);
  87. String mi = "";
  88. //如果明文长度大于模长-11则要分组加密
  89. for (String s : datas) \{
  90. mi += bcd2Str(cipher.doFinal(s.getBytes()));
  91. \}
  92. return mi;
  93. \}
  94. /\*\*
  95. \* 公钥解密
  96. \*
  97. \* @param data
  98. \* @param privateKey
  99. \* @return
  100. \* @throws Exception
  101. \*/
  102. public static String decryptByPublicKey(String data, RSAPublicKey publicKey)
  103. throws Exception \{
  104. Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
  105. cipher.init(Cipher.DECRYPT\_MODE, publicKey);
  106. //模长
  107. int key\_len = publicKey.getModulus().bitLength() / 8;
  108. byte\[\] bytes = data.getBytes();
  109. byte\[\] bcd = ASCII\_To\_BCD(bytes, bytes.length);
  110. //System.err.println(bcd.length);
  111. //如果密文长度大于模长则要分组解密
  112. String ming = "";
  113. byte\[\]\[\] arrays = splitArray(bcd, key\_len);
  114. for(byte\[\] arr : arrays)\{
  115. ming += new String(cipher.doFinal(arr));
  116. \}
  117. return ming;
  118. \}
  119. /\*\*
  120. \* ASCII码转BCD
  121. \*
  122. \*/
  123. public static byte\[\] ASCII\_To\_BCD(byte\[\] ascii, int asc\_len) \{
  124. byte\[\] bcd = new byte\[asc\_len / 2\];
  125. int j = 0;
  126. for (int i = 0; i < (asc\_len + 1) / 2; i++) \{
  127. bcd\[i\] = asc\_to\_bcd(ascii\[j++\]);
  128. bcd\[i\] = (byte) (((j >= asc\_len) ? 0x00 : asc\_to\_bcd(ascii\[j++\])) + (bcd\[i\] << 4));
  129. \}
  130. return bcd;
  131. \}
  132. public static byte asc\_to\_bcd(byte asc) \{
  133. byte bcd;
  134. if ((asc >= '0') && (asc <= '9'))
  135. bcd = (byte) (asc - '0');
  136. else if ((asc >= 'A') && (asc <= 'F'))
  137. bcd = (byte) (asc - 'A' + 10);
  138. else if ((asc >= 'a') && (asc <= 'f'))
  139. bcd = (byte) (asc - 'a' + 10);
  140. else
  141. bcd = (byte) (asc - 48);
  142. return bcd;
  143. \}
  144. /\*\*
  145. \* BCD转字符串
  146. \*/
  147. public static String bcd2Str(byte\[\] bytes) \{
  148. char temp\[\] = new char\[bytes.length \* 2\], val;
  149. for (int i = 0; i < bytes.length; i++) \{
  150. val = (char) (((bytes\[i\] & 0xf0) >> 4) & 0x0f);
  151. temp\[i \* 2\] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
  152. val = (char) (bytes\[i\] & 0x0f);
  153. temp\[i \* 2 + 1\] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
  154. \}
  155. return new String(temp);
  156. \}
  157. /\*\*
  158. \* 拆分字符串
  159. \*/
  160. public static String\[\] splitString(String string, int len) \{
  161. int x = string.length() / len;
  162. int y = string.length() % len;
  163. int z = 0;
  164. if (y != 0) \{
  165. z = 1;
  166. \}
  167. String\[\] strings = new String\[x + z\];
  168. String str = "";
  169. for (int i=0; i<x+z; i++) \{
  170. if (i==x+z-1 && y!=0) \{
  171. str = string.substring(i\*len, i\*len+y);
  172. \}else\{
  173. str = string.substring(i\*len, i\*len+len);
  174. \}
  175. strings\[i\] = str;
  176. \}
  177. return strings;
  178. \}
  179. /\*\*
  180. \*拆分数组
  181. \*/
  182. public static byte\[\]\[\] splitArray(byte\[\] data,int len)\{
  183. int x = data.length / len;
  184. int y = data.length % len;
  185. int z = 0;
  186. if(y!=0)\{
  187. z = 1;
  188. \}
  189. byte\[\]\[\] arrays = new byte\[x+z\]\[\];
  190. byte\[\] arr;
  191. for(int i=0; i<x+z; i++)\{
  192. arr = new byte\[len\];
  193. if(i==x+z-1 && y!=0)\{
  194. System.arraycopy(data, i\*len, arr, 0, y);
  195. \}else\{
  196. System.arraycopy(data, i\*len, arr, 0, len);
  197. \}
  198. arrays\[i\] = arr;
  199. \}
  200. return arrays;
  201. \}
  202. public static void main(String\[\] args) throws Exception\{
  203. HashMap<String, Object> map = getKeys();
  204. //生成公钥和私钥
  205. RSAPublicKey publicKey = (RSAPublicKey) map.get("public");
  206. RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");
  207. //模
  208. String modulus = publicKey.getModulus().toString();
  209. System.out.println("pubkey modulus="+modulus);
  210. //公钥指数
  211. String public\_exponent = publicKey.getPublicExponent().toString();
  212. System.out.println("pubkey exponent="+public\_exponent);
  213. //私钥指数
  214. String private\_exponent = privateKey.getPrivateExponent().toString();
  215. System.out.println("private exponent="+private\_exponent);
  216. System.out.println("private modulus="+privateKey.getModulus().toString());
  217. //明文
  218. String ming = "111";
  219. //使用模和指数生成公钥和私钥
  220. RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public\_exponent);
  221. RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private\_exponent);
  222. //加密后的密文
  223. String mi = RSAUtils.encryptByPublicKey(ming, pubKey);
  224. System.err.println("公钥加密:mi="+mi);
  225. //解密后的明文
  226. String ming2 = RSAUtils.decryptByPrivateKey(mi, priKey);
  227. System.err.println("私钥解密:ming2="+ming2);
  228. //私钥加密
  229. mi = RSAUtils.encryptByPrivateKey(ming, priKey);
  230. System.err.println("私钥加密:mi="+mi);
  231. //公钥解密
  232. ming2 = RSAUtils.decryptByPublicKey(mi, pubKey);
  233. System.err.println("公钥解密:ming2="+ming2);
  234. \}

public static String getPwd(String encrypedPwd, HttpSession session) throws Exception {
System.out.println(“从请求中获得密文:”+encrypedPwd);
String public_modulus=(String)session.getAttribute(“public_modulus”);
String private_exponent=(String)session.getAttribute(“private_exponent”);
RSAPrivateKey priKey = RSAUtils.getPrivateKey(public_modulus, private_exponent);
String pwd=RSAUtils.decryptByPrivateKey(encrypedPwd, priKey);
pwd= java.net.URLDecoder.decode(pwd,”UTF-8”);
System.out.println(“解密后结果:”+pwd);
return pwd;
}

public static String getRandomString(int length) { //length表示生成字符串的长度
String base = “abcdefghijklmnopqrstuvwxyz0123456789_“;
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}

// public static void setPubkeyAndModulus(HttpServletRequest request,
// Model model) throws NoSuchAlgorithmException {
// RSAModel rsa = getPrivateKeyFromRedis();
// request.getSession().setAttribute(“public_modulus”, rsa.getPublic_modulus());
// request.getSession().setAttribute(“private_exponent”, rsa.getPrivate_exponent());
// model.addAttribute(“publicKeyExponent”, rsa.getPublicKeyExponent());
// model.addAttribute(“publicKeyModulus”, rsa.getPublicKeyModulus());
// }

// public static RSAModel getPrivateKeyFromRedis() {
// RSAModel rsa;
// //从JedisConnectionFactory获得Jedis对象
// JedisConnectionFactory jedisConnectionFactory=(JedisConnectionFactory)SpringUtils.getBean(“jedisConnectionFactory”);
// JedisConnection jedisConnection =jedisConnectionFactory.getConnection();
// Jedis jedis=jedisConnection.getNativeConnection();
// //切换数据库到11
// jedis.select(11);
//
// int max=100;
// int min=1;
// Random random = new Random();
// int s = random.nextInt(max)%(max-min+1) + min;
// String key = “privateKey” + s;
//
// rsa = (RSAModel)SerializeUtil.unserialize(jedis.get(key.getBytes()));
String keyValue = rsa.getPrivate_exponent();
System.out.println(key + “ “ + keyValue);
System.out.println(“查看”+key + “的剩余生存时间:”+jedis.ttl(key));
//
//
// return rsa;
// }
}

发表评论

表情:
评论列表 (有 0 条评论,289人围观)

还没有评论,来说两句吧...

相关阅读

    相关 RSA加密解密

    RSA加密与解密 RSA算法的密钥由公钥和私钥组成,公钥用于加密,私钥用于解密。顾名思义,公钥就是可以进行公开的密钥,一般可以公开给你的合作伙伴;私钥就是私有的,也就是只

    相关 JS-RSA加密解密

      在上一篇文章《Java使用RSA加密解密签名及校验》中,用java实现加密解密,但是在实际应用中,如前端页面用户输入的密码传输给后台服务前,需加密,也就是公钥加密,私钥解密