关键词搜索

源码搜索 ×
×

java之RSA和Base64加密帮助类

发布2017-07-24浏览2496次

详情内容

1、RSAUtils.java类

 

  1. package com.sangfor.vpn.client.service.utils;
  2. import java.io.BufferedReader;
  3. import java.io.ByteArrayOutputStream;
  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. import javax.crypto.Cipher;
  21. /**
  22. * Created by wk on 2017https://files.jxasp.com/image/2/14.
  23. */
  24. public class RSAUtils {
  25. private static String RSA = "RSA";
  26. /** *//**
  27. * RSA最大加密明文大小
  28. */
  29. private static final int MAX_ENCRYPT_BLOCK = 117;
  30. /**
  31. * 随机生成RSA密钥对(默认密钥长度为1024)
  32. *
  33. * @return
  34. */
  35. public static KeyPair generateRSAKeyPair()
  36. {
  37. return generateRSAKeyPair(1024);
  38. }
  39. /**
  40. * 随机生成RSA密钥对
  41. *
  42. * @param keyLength
  43. * 密钥长度,范围:512~2048<br>
  44. * 一般1024
  45. * @return
  46. */
  47. public static KeyPair generateRSAKeyPair(int keyLength)
  48. {
  49. try
  50. {
  51. KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
  52. kpg.initialize(keyLength);
  53. return kpg.genKeyPair();
  54. } catch (NoSuchAlgorithmException e)
  55. {
  56. e.printStackTrace();
  57. return null;
  58. }
  59. }
  60. /**
  61. * 用公钥加密 <br>
  62. * 每次加密的字节数,不能超过密钥的长度值减去11
  63. *
  64. * @param data
  65. * 需加密数据的byte数据
  66. * @param publicKey 公钥
  67. * @return 加密后的byte型数据
  68. */
  69. public static byte[] encryptData(byte[] data, PublicKey publicKey)
  70. {
  71. try
  72. {
  73. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  74. // 编码前设定编码方式及密钥
  75. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  76. // 传入编码数据并返回编码结果
  77. int inputLen = data.length;
  78. ByteArrayOutputStream out = new ByteArrayOutputStream();
  79. int offSet = 0;
  80. byte[] cache;
  81. int i = 0;
  82. // 对数据分段加密
  83. while (inputLen - offSet > 0) {
  84. if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
  85. cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
  86. } else {
  87. cache = cipher.doFinal(data, offSet, inputLen - offSet);
  88. }
  89. out.write(cache, 0, cache.length);
  90. i++;
  91. offSet = i * MAX_ENCRYPT_BLOCK;
  92. }
  93. byte[] encryptedData = out.toByteArray();
  94. out.close();
  95. return encryptedData;
  96. } catch (Exception e)
  97. {
  98. e.printStackTrace();
  99. return null;
  100. }
  101. }
  102. /**
  103. * 用私钥解密
  104. *
  105. * @param encryptedData
  106. * 经过encryptedData()加密返回的byte数据
  107. * @param privateKey
  108. * 私钥
  109. * @return
  110. */
  111. public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
  112. {
  113. try
  114. {
  115. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  116. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  117. return cipher.doFinal(encryptedData);
  118. } catch (Exception e)
  119. {
  120. e.printStackTrace();
  121. return null;
  122. }
  123. }
  124. /**
  125. * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
  126. *
  127. * @param keyBytes
  128. * @return
  129. * @throws NoSuchAlgorithmException
  130. * @throws InvalidKeySpecException
  131. */
  132. public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
  133. InvalidKeySpecException
  134. {
  135. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
  136. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  137. PublicKey publicKey = keyFactory.generatePublic(keySpec);
  138. return publicKey;
  139. }
  140. /**
  141. * 通过私钥byte[]将公钥还原,适用于RSA算法
  142. *
  143. * @param keyBytes
  144. * @return
  145. * @throws NoSuchAlgorithmException
  146. * @throws InvalidKeySpecException
  147. */
  148. public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
  149. InvalidKeySpecException
  150. {
  151. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
  152. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  153. PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
  154. return privateKey;
  155. }
  156. /**
  157. * 使用N、e值还原公钥
  158. *
  159. * @param modulus
  160. * @param publicExponent
  161. * @return
  162. * @throws NoSuchAlgorithmException
  163. * @throws InvalidKeySpecException
  164. */
  165. public static PublicKey getPublicKey(String modulus, String publicExponent)
  166. throws NoSuchAlgorithmException, InvalidKeySpecException
  167. {
  168. BigInteger bigIntModulus = new BigInteger(modulus);
  169. BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
  170. RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
  171. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  172. PublicKey publicKey = keyFactory.generatePublic(keySpec);
  173. return publicKey;
  174. }
  175. /**
  176. * 使用N、d值还原私钥
  177. *
  178. * @param modulus
  179. * @param privateExponent
  180. * @return
  181. * @throws NoSuchAlgorithmException
  182. * @throws InvalidKeySpecException
  183. */
  184. public static PrivateKey getPrivateKey(String modulus, String privateExponent)
  185. throws NoSuchAlgorithmException, InvalidKeySpecException
  186. {
  187. BigInteger bigIntModulus = new BigInteger(modulus);
  188. BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
  189. RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
  190. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  191. PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
  192. return privateKey;
  193. }
  194. /**
  195. * 从字符串中加载公钥
  196. *
  197. * @param publicKeyStr
  198. * 公钥数据字符串
  199. * @throws Exception
  200. * 加载公钥时产生的异常
  201. */
  202. public static PublicKey loadPublicKey(String publicKeyStr) throws Exception
  203. {
  204. try
  205. {
  206. byte[] buffer = Base64Utils.decode(publicKeyStr);
  207. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  208. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
  209. return (RSAPublicKey) keyFactory.generatePublic(keySpec);
  210. } catch (NoSuchAlgorithmException e)
  211. {
  212. throw new Exception("无此算法");
  213. } catch (InvalidKeySpecException e)
  214. {
  215. throw new Exception("公钥非法");
  216. } catch (NullPointerException e)
  217. {
  218. throw new Exception("公钥数据为空");
  219. }
  220. }
  221. /**
  222. * 从字符串中加载私钥<br>
  223. * 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
  224. *
  225. * @param privateKeyStr
  226. * @return
  227. * @throws Exception
  228. */
  229. public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception
  230. {
  231. try
  232. {
  233. byte[] buffer = Base64Utils.decode(privateKeyStr);
  234. // X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
  235. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
  236. KeyFactory keyFactory = KeyFactory.getInstance(RSA);
  237. return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
  238. } catch (NoSuchAlgorithmException e)
  239. {
  240. throw new Exception("无此算法");
  241. } catch (InvalidKeySpecException e)
  242. {
  243. throw new Exception("私钥非法");
  244. } catch (NullPointerException e)
  245. {
  246. throw new Exception("私钥数据为空");
  247. }
  248. }
  249. /**
  250. * 从文件中输入流中加载公钥
  251. *
  252. * @param in
  253. * 公钥输入流
  254. * @throws Exception
  255. * 加载公钥时产生的异常
  256. */
  257. public static PublicKey loadPublicKey(InputStream in) throws Exception
  258. {
  259. try
  260. {
  261. return loadPublicKey(readKey(in));
  262. } catch (IOException e)
  263. {
  264. throw new Exception("公钥数据流读取错误");
  265. } catch (NullPointerException e)
  266. {
  267. throw new Exception("公钥输入流为空");
  268. }
  269. }
  270. /**
  271. * 从文件中加载私钥
  272. *
  273. * @param in
  274. * 私钥文件名
  275. * @return 是否成功
  276. * @throws Exception
  277. */
  278. public static PrivateKey loadPrivateKey(InputStream in) throws Exception
  279. {
  280. try
  281. {
  282. return loadPrivateKey(readKey(in));
  283. } catch (IOException e)
  284. {
  285. throw new Exception("私钥数据读取错误");
  286. } catch (NullPointerException e)
  287. {
  288. throw new Exception("私钥输入流为空");
  289. }
  290. }
  291. /**
  292. * 读取密钥信息
  293. *
  294. * @param in
  295. * @return
  296. * @throws IOException
  297. */
  298. private static String readKey(InputStream in) throws IOException
  299. {
  300. BufferedReader br = new BufferedReader(new InputStreamReader(in));
  301. String readLine = null;
  302. StringBuilder sb = new StringBuilder();
  303. while ((readLine = br.readLine()) != null)
  304. {
  305. if (readLine.charAt(0) == '-')
  306. {
  307. continue;
  308. } else
  309. {
  310. sb.append(readLine);
  311. sb.append('\r');
  312. }
  313. }
  314. return sb.toString();
  315. }
  316. /**
  317. * 打印公钥信息
  318. *
  319. * @param publicKey
  320. */
  321. public static void printPublicKeyInfo(PublicKey publicKey)
  322. {
  323. RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
  324. System.out.println("----------RSAPublicKey----------");
  325. System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
  326. System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
  327. System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
  328. System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
  329. }
  330. public static void printPrivateKeyInfo(PrivateKey privateKey)
  331. {
  332. RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
  333. System.out.println("----------RSAPrivateKey ----------");
  334. System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
  335. System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
  336. System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
  337. System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());
  338. }
  339. }

 

 

 

 

 

 

 

2、Base64Utils.java类

 

  1. package com.sangfor.vpn.client.service.utils;
  2. import java.io.UnsupportedEncodingException;
  3. /**
  4. * Created by wk on 2017https://files.jxasp.com/image/2/14.
  5. */
  6. public class Base64Utils {
  7. private static char[] base64EncodeChars = new char[]
  8. { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
  9. 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
  10. 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
  11. '6', '7', '8', '9', '+', '/' };
  12. private static byte[] base64DecodeChars = new byte[]
  13. { -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,
  14. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
  15. 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,
  16. 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
  17. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
  18. -1, -1, -1 };
  19. /**
  20. * 加密
  21. *
  22. * @param data
  23. * @return
  24. */
  25. public static String encode(byte[] data)
  26. {
  27. StringBuffer sb = new StringBuffer();
  28. int len = data.length;
  29. int i = 0;
  30. int b1, b2, b3;
  31. while (i < len)
  32. {
  33. b1 = data[i++] & 0xff;
  34. if (i == len)
  35. {
  36. sb.append(base64EncodeChars[b1 >>> 2]);
  37. sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
  38. sb.append("==");
  39. break;
  40. }
  41. b2 = data[i++] & 0xff;
  42. if (i == len)
  43. {
  44. sb.append(base64EncodeChars[b1 >>> 2]);
  45. sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
  46. sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
  47. sb.append("=");
  48. break;
  49. }
  50. b3 = data[i++] & 0xff;
  51. sb.append(base64EncodeChars[b1 >>> 2]);
  52. sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
  53. sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
  54. sb.append(base64EncodeChars[b3 & 0x3f]);
  55. }
  56. return sb.toString();
  57. }
  58. /**
  59. * 解密
  60. *
  61. * @param str
  62. * @return
  63. */
  64. public static byte[] decode(String str)
  65. {
  66. try
  67. {
  68. return decodePrivate(str);
  69. } catch (UnsupportedEncodingException e)
  70. {
  71. e.printStackTrace();
  72. }
  73. return new byte[]
  74. {};
  75. }
  76. private static byte[] decodePrivate(String str) throws UnsupportedEncodingException
  77. {
  78. StringBuffer sb = new StringBuffer();
  79. byte[] data = null;
  80. data = str.getBytes("US-ASCII");
  81. int len = data.length;
  82. int i = 0;
  83. int b1, b2, b3, b4;
  84. while (i < len)
  85. {
  86. do
  87. {
  88. b1 = base64DecodeChars[data[i++]];
  89. } while (i < len && b1 == -1);
  90. if (b1 == -1)
  91. break;
  92. do
  93. {
  94. b2 = base64DecodeChars[data[i++]];
  95. } while (i < len && b2 == -1);
  96. if (b2 == -1)
  97. break;
  98. sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
  99. do
  100. {
  101. b3 = data[i++];
  102. if (b3 == 61)
  103. return sb.toString().getBytes("iso8859-1");
  104. b3 = base64DecodeChars[b3];
  105. } while (i < len && b3 == -1);
  106. if (b3 == -1)
  107. break;
  108. sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
  109. do
  110. {
  111. b4 = data[i++];
  112. if (b4 == 61)
  113. return sb.toString().getBytes("iso8859-1");
  114. b4 = base64DecodeChars[b4];
  115. } while (i < len && b4 == -1);
  116. if (b4 == -1)
  117. break;
  118. sb.append((char) (((b3 & 0x03) << 6) | b4));
  119. }
  120. return sb.toString().getBytes("iso8859-1");
  121. }
  122. }

 

 

 

 

3、SecurityUtils类

 

  1. package com.sangfor.vpn.client.service.utils;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.InputStream;
  5. import java.security.PrivateKey;
  6. import java.security.PublicKey;
  7. public class SecurityUtils {
  8. /**
  9. * 解密
  10. * @param cipherText 密文
  11. * @return 返回解密后的字符串
  12. * @throws Exception
  13. */
  14. public static String decrypt(String cipherText) throws Exception{
  15. // 从文件中得到私钥
  16. FileInputStream inPrivate = new FileInputStream(
  17. SecurityUtils.class.getClassLoader().getResource("").getPath() + "/pkcs8_private_key.pem");
  18. PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
  19. byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(cipherText), privateKey);
  20. String decryptStr = new String(decryptByte,"utf-8");
  21. return decryptStr;
  22. }
  23. /**
  24. * 加密
  25. * @param plainTest 明文
  26. * @return 返回加密后的密文
  27. * @throws Exception
  28. */
  29. public static String encrypt(String plainTest) throws Exception{
  30. PublicKey publicKey = RSAUtils.loadPublicKey(plainTest);
  31. // 加密
  32. byte[] encryptByte = RSAUtils.encryptData(plainTest.getBytes(), publicKey);
  33. String afterencrypt = Base64Utils.encode(encryptByte);
  34. return afterencrypt;
  35. }
  36. /**
  37. * 加密
  38. * @param plainTest 明文
  39. * @return 返回加密后的密文
  40. * @throws Exception
  41. */
  42. public static String encrypt(String plainTest, String key) throws Exception{
  43. PublicKey publicKey = RSAUtils.loadPublicKey(key);
  44. // 加密
  45. byte[] encryptByte = RSAUtils.encryptData(plainTest.getBytes(), publicKey);
  46. String afterencrypt = Base64Utils.encode(encryptByte);
  47. return afterencrypt;
  48. }
  49. }

 

 

 

 

 

 

 

 

 

 

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载