当前位置:   article > 正文

RSA加密实现之JAVA方式_java rsa加密

java rsa加密
  1. package com.xxxx.tax.util;
  2. import com.xxxxx.tax.util.ExceptionUtil;
  3. import lombok.extern.log4j.Log4j;
  4. import java.io.ByteArrayOutputStream;
  5. import java.security.Key;
  6. import java.security.KeyFactory;
  7. import java.security.KeyPair;
  8. import java.security.KeyPairGenerator;
  9. import java.security.PrivateKey;
  10. import java.security.PublicKey;
  11. import java.security.Signature;
  12. import java.security.interfaces.RSAPrivateKey;
  13. import java.security.interfaces.RSAPublicKey;
  14. import java.security.spec.PKCS8EncodedKeySpec;
  15. import java.security.spec.X509EncodedKeySpec;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18. import org.apache.commons.codec.binary.Base64;
  19. import javax.crypto.Cipher;
  20. @Log4j
  21. public class RSAUtils {
  22. /** *//**
  23. * 加密算法RSA
  24. */
  25. public static final String KEY_ALGORITHM = "RSA";
  26. /** *//**
  27. * 签名算法
  28. */
  29. public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
  30. /** *//**
  31. * 获取公钥的key
  32. */
  33. private static final String PUBLIC_KEY = "RSAPublicKey";
  34. /** *//**
  35. * 获取私钥的key
  36. */
  37. private static final String PRIVATE_KEY = "RSAPrivateKey";
  38. /** *//**
  39. * RSA最大加密明文大小
  40. */
  41. private static final int MAX_ENCRYPT_BLOCK = 117;
  42. /** *//**
  43. * RSA最大解密密文大小
  44. */
  45. private static final int MAX_DECRYPT_BLOCK = 128;
  46. /** *//**
  47. * <p>
  48. * 生成密钥对(公钥和私钥)
  49. * </p>
  50. *
  51. * @return
  52. * @throws Exception
  53. */
  54. public static Map<String, Object> genKeyPair() throws Exception {
  55. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
  56. keyPairGen.initialize(1024);
  57. KeyPair keyPair = keyPairGen.generateKeyPair();
  58. RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  59. RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
  60. Map<String, Object> keyMap = new HashMap<String, Object>(2);
  61. String publicKeyString = new String(Base64Util.encode(publicKey.getEncoded()));
  62. // 得到私钥字符串
  63. String privateKeyString = new String(Base64Util.encode((privateKey.getEncoded())));
  64. System.out.println(publicKeyString);
  65. System.out.println(privateKeyString);
  66. keyMap.put(PUBLIC_KEY, publicKey);
  67. keyMap.put(PRIVATE_KEY, privateKey);
  68. return keyMap;
  69. }
  70. /** *//**
  71. * <p>
  72. * 用私钥对信息生成数字签名
  73. * </p>
  74. *
  75. * @param data 已加密数据
  76. * @param privateKey 私钥(BASE64编码)
  77. *
  78. * @return
  79. * @throws Exception
  80. */
  81. public static String sign(byte[] data, String privateKey) throws Exception {
  82. byte[] keyBytes = Base64Util.decode(privateKey);
  83. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  84. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  85. PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
  86. Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  87. signature.initSign(privateK);
  88. signature.update(data);
  89. return Base64Util.encode(signature.sign());
  90. }
  91. /** *//**
  92. * <p>
  93. * 校验数字签名
  94. * </p>
  95. *
  96. * @param data 已加密数据
  97. * @param publicKey 公钥(BASE64编码)
  98. * @param sign 数字签名
  99. *
  100. * @return
  101. * @throws Exception
  102. *
  103. */
  104. public static boolean verify(byte[] data, String publicKey, String sign)
  105. throws Exception {
  106. byte[] keyBytes = Base64Util.decode(publicKey);
  107. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
  108. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  109. PublicKey publicK = keyFactory.generatePublic(keySpec);
  110. Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  111. signature.initVerify(publicK);
  112. signature.update(data);
  113. return signature.verify(Base64Util.decode(sign));
  114. }
  115. /** *//**
  116. * <P>
  117. * 私钥解密
  118. * </p>
  119. *
  120. * @param encryptedData 已加密数据
  121. * @param privateKey 私钥(BASE64编码)
  122. * @return
  123. * @throws Exception
  124. */
  125. public static String decryptByPrivateKey(byte[] encryptedData, String privateKey)
  126. throws Exception {
  127. byte[] keyBytes = Base64Util.decode(privateKey);
  128. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  129. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  130. Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
  131. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  132. cipher.init(Cipher.DECRYPT_MODE, privateK);
  133. int inputLen = encryptedData.length;
  134. ByteArrayOutputStream out = new ByteArrayOutputStream();
  135. int offSet = 0;
  136. byte[] cache;
  137. int i = 0;
  138. // 对数据分段解密
  139. while (inputLen - offSet > 0) {
  140. if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
  141. cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
  142. } else {
  143. cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
  144. }
  145. out.write(cache, 0, cache.length);
  146. i++;
  147. offSet = i * MAX_DECRYPT_BLOCK;
  148. }
  149. byte[] decryptedData = out.toByteArray();
  150. out.close();
  151. return Base64Util.encode(decryptedData);
  152. }
  153. /**
  154. * 公钥解密
  155. *
  156. * @param publicKeyText
  157. * @param text
  158. * @return
  159. * @throws Exception
  160. */
  161. public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {
  162. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
  163. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  164. PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
  165. Cipher cipher = Cipher.getInstance("RSA");
  166. cipher.init(Cipher.DECRYPT_MODE, publicKey);
  167. byte[] result = cipher.doFinal(Base64.decodeBase64(text));
  168. return new String(result);
  169. }
  170. /** *//**
  171. * <p>
  172. * 公钥解密
  173. * </p>
  174. *
  175. * @param encryptedData 已加密数据
  176. * @param publicKey 公钥(BASE64编码)
  177. * @return
  178. * @throws Exception
  179. */
  180. public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
  181. throws Exception {
  182. byte[] keyBytes = Base64Util.decode(publicKey);
  183. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
  184. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  185. Key publicK = keyFactory.generatePublic(x509KeySpec);
  186. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  187. cipher.init(Cipher.DECRYPT_MODE, publicK);
  188. int inputLen = encryptedData.length;
  189. ByteArrayOutputStream out = new ByteArrayOutputStream();
  190. int offSet = 0;
  191. byte[] cache;
  192. int i = 0;
  193. // 对数据分段解密
  194. while (inputLen - offSet > 0) {
  195. if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
  196. cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
  197. } else {
  198. cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
  199. }
  200. out.write(cache, 0, cache.length);
  201. i++;
  202. offSet = i * MAX_DECRYPT_BLOCK;
  203. }
  204. byte[] decryptedData = out.toByteArray();
  205. out.close();
  206. return decryptedData;
  207. }
  208. /** *//**
  209. * <p>
  210. * 公钥加密
  211. * </p>
  212. *
  213. * @param data 源数据
  214. * @param publicKey 公钥(BASE64编码)
  215. * @return
  216. * @throws Exception
  217. */
  218. public static String encryptByPublicKey(byte[] data, String publicKey)
  219. throws Exception {
  220. byte[] keyBytes = Base64Util.decode(publicKey);
  221. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
  222. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  223. Key publicK = keyFactory.generatePublic(x509KeySpec);
  224. // 对数据加密
  225. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  226. cipher.init(Cipher.ENCRYPT_MODE, publicK);
  227. int inputLen = data.length;
  228. ByteArrayOutputStream out = new ByteArrayOutputStream();
  229. int offSet = 0;
  230. byte[] cache;
  231. int i = 0;
  232. // 对数据分段加密
  233. while (inputLen - offSet > 0) {
  234. if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
  235. cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
  236. } else {
  237. cache = cipher.doFinal(data, offSet, inputLen - offSet);
  238. }
  239. out.write(cache, 0, cache.length);
  240. i++;
  241. offSet = i * MAX_ENCRYPT_BLOCK;
  242. }
  243. byte[] encryptedData = out.toByteArray();
  244. out.close();
  245. //return Base64Util.encode(encryptedData);
  246. return bytesToHexString(encryptedData);
  247. }
  248. /** *//**
  249. * <p>
  250. * 公钥加密
  251. * </p>
  252. *
  253. * @param data 源数据
  254. * @param publicKey 公钥(BASE64编码)
  255. * @return
  256. * @throws Exception
  257. */
  258. public static String encryptByPublicKeyByBase(byte[] data, String publicKey)
  259. throws Exception {
  260. byte[] keyBytes = Base64Util.decode(publicKey);
  261. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
  262. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  263. Key publicK = keyFactory.generatePublic(x509KeySpec);
  264. // 对数据加密
  265. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  266. cipher.init(Cipher.ENCRYPT_MODE, publicK);
  267. int inputLen = data.length;
  268. ByteArrayOutputStream out = new ByteArrayOutputStream();
  269. int offSet = 0;
  270. byte[] cache;
  271. int i = 0;
  272. // 对数据分段加密
  273. while (inputLen - offSet > 0) {
  274. if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
  275. cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
  276. } else {
  277. cache = cipher.doFinal(data, offSet, inputLen - offSet);
  278. }
  279. out.write(cache, 0, cache.length);
  280. i++;
  281. offSet = i * MAX_ENCRYPT_BLOCK;
  282. }
  283. byte[] encryptedData = out.toByteArray();
  284. out.close();
  285. return Base64Util.encode(encryptedData);
  286. // return bytesToHexString(encryptedData);
  287. }
  288. /**
  289. * 将字节数组转换成16进制字符串
  290. * @param bytes 即将转换的数据
  291. * @return 16进制字符串
  292. */
  293. public static String bytesToHexString(byte[] bytes) {
  294. StringBuffer sb = new StringBuffer(bytes.length);
  295. String temp = null;
  296. for (int i = 0; i < bytes.length; i++) {
  297. temp = Integer.toHexString(0xFF & bytes[i]);
  298. if (temp.length() < 2) {
  299. sb.append(0);
  300. }
  301. sb.append(temp);
  302. }
  303. return sb.toString();
  304. }
  305. /** *//**
  306. * <p>
  307. * 私钥加密
  308. * </p>
  309. *
  310. * @param data 源数据
  311. * @param privateKey 私钥(BASE64编码)
  312. * @return
  313. * @throws Exception
  314. */
  315. public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
  316. throws Exception {
  317. byte[] keyBytes = Base64Util.decode(privateKey);
  318. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
  319. KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
  320. Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
  321. Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
  322. cipher.init(Cipher.ENCRYPT_MODE, privateK);
  323. int inputLen = data.length;
  324. ByteArrayOutputStream out = new ByteArrayOutputStream();
  325. int offSet = 0;
  326. byte[] cache;
  327. int i = 0;
  328. // 对数据分段加密
  329. while (inputLen - offSet > 0) {
  330. if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
  331. cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
  332. } else {
  333. cache = cipher.doFinal(data, offSet, inputLen - offSet);
  334. }
  335. out.write(cache, 0, cache.length);
  336. i++;
  337. offSet = i * MAX_ENCRYPT_BLOCK;
  338. }
  339. byte[] encryptedData = out.toByteArray();
  340. out.close();
  341. return encryptedData;
  342. }
  343. /** *//**
  344. * <p>
  345. * 获取私钥
  346. * </p>
  347. *
  348. * @param keyMap 密钥对
  349. * @return
  350. * @throws Exception
  351. */
  352. public static String getPrivateKey(Map<String, Object> keyMap)
  353. throws Exception {
  354. Key key = (Key) keyMap.get(PRIVATE_KEY);
  355. return Base64Util.encode(key.getEncoded());
  356. }
  357. /** *//**
  358. * <p>
  359. * 获取公钥
  360. * </p>
  361. *
  362. * @param keyMap 密钥对
  363. * @return
  364. * @throws Exception
  365. */
  366. public static String getPublicKey(Map<String, Object> keyMap)
  367. throws Exception {
  368. Key key = (Key) keyMap.get(PUBLIC_KEY);
  369. return Base64Util.encode(key.getEncoded());
  370. }
  371. public static void main(String[] args){
  372. try {
  373. //RSAUtils.genKeyPair();
  374. String IMAGE_PRIVATEKEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALwNwRLuWJo7gzOIJDQSa2tnsu52bEESmI1yC+/pPEQ4tqXiuyhAqctwFXY97qLakUBdoGs/4CcjU9yTVjFMBE5kyaQncF83TwIoDyZlS5VoYL8gcNXt9RTemlURVYXpu1WxoOD60X6T24uUrko4AiEpu5E2HtmNypELxlJUPWqrAgMBAAECgYA3Mv5adTXyx8dCSBMAaeu4Ei9WidJK44997V0NpfO3vsH2PXBcZ2avvY2/MHystuVt9E2TTaOZOWhzVZg2Ti7w5j/L3P9WpgSB4M4Rpy2WaI31cLLu9cmRgfuQCNHJKwevlp9h144F65XJpHJjkCyP/rW5QvPRtoA/d0ujA4C10QJBAPY+HW5wl139ALfRVJx/GHdxMNLsJskJPwLAT/+vJu5eVerF3d/nQgpuDyEmNN0GvNhrZ/liP1i9IWBsy26TlJMCQQDDgV75r2TEt8wp4mqKP9ufm4tkmidsPlAAsx8G8/ETffekROv9ksWjSdTxvcQ5Z7AFfVq4NFKiXMOG86pwqniJAkAgvMda7HsjUsSqq5jtKXSORK0yDZVmeuU2r2yzWIz7ee1ARkgmQW+lRVabmKHElOW8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VWv5nrTllK//PQ6wI2od0cVsJ96vXZC1nXlKZZWfQaaceOKf4Wcm6qWIUzG0qy35bZyR1CxWwzMUve1e2dgzeuT23XOsJvCyPMf4JTpkm+Xhr7gpqoRBRsVLi8mU1ObIYCtWbGs87L6FdFrhRljXw9BPOXJXczqXupQFFujlb4vnte8/3JT0v56qh/JKv6R0Fj4MsDieIqE9RKZrLt85ulVwoWTWuhTF1VdtBx0062tcI7/HG539S2X30YGTKpPLWAL/zsmSYoFR6uZm0nM+gwHA8kR+EYK+XAVvPNcb/ULKkhUq0ZaaT3Rbsz04UMmXiVFanOtmDIAsAsnq8fAuuInpzn/vhqEXofGADtrgg5SlMAg5Czw3koycIR1YxuQBxnNjGRpJA9pJR3BMy3/Fyus8GD4mGIwnIwfHKvyuWuYTx2LzvKQRQa/qf3u2w0Wl3mC6is9hubvPg/njv/PiB7mJbz/Ec3+r1nfPXBwAvFM7gj59KEhvJuFo04HwjEaSl7XZGMh3YKlsTZnmRrArBNZzhBGxt3mRUZ0sZ93Yev2QUaw=";
  377. String res = new String(Base64Util.decode(RSAUtils.decryptByPrivateKey(Base64Util.decode(str), IMAGE_PRIVATEKEY)));
  378. System.out.println(res);
  379. String ss = RSAUtils.encryptByPublicKey("abcdef".getBytes(), IMAGE_PUBLICKEY);
  380. System.out.println(ss);
  381. } catch (Exception e) {
  382. log.error(ExceptionUtil.getMessage(e));
  383. }
  384. }
  385. }

如有问题,请私信。

xObP8s/gudi/zrPMoaJKU7K5u7e+s7/Os8yhokpBVkHP4LnYv86zzMjn0OjSqtKyv8nS1MGqz7VRUaGjDQoNCtf31d8gUVEgNDA0NTQwMjI5

题,请私信

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/601135
推荐阅读
相关标签
  

闽ICP备14008679号