Java加密解密快速入门下篇【包括MD5、BASE64、DES、RSA等算法】

素颜马尾好姑娘i 2021-06-10 20:42 437阅读 0赞

在上一篇博客中已经简要的介绍了MD5、BASE64、DES、RSA等算法在Java中的具体应用。现在可以考虑对这些代码封装成一个工具类EncryptUtil吻,然后再补充一下Commons Codec对BASE64的扩展支持!微笑

<一>. EncryptUtil工具类:

  1. 使用commons-logging记录异常日志。

  2. 提取常量字段、公共字段。

  3. 提取公共方法:

Java代码

  1. //创建密钥
  2. createSecretKey(String key):Key
  3. //加密解密
  4. processCipher(byte[] processData, Key key, int opsMode, String algorithm):byte[]

    1. EncryptUtil类的完整代码:大笑

Java代码

  1. /*
  2. * Copyright (c) 2014, Nick Xu, All rights reserved.
  3. */
  4. package com.excelsoft.common.crypto;
  5. import java.io.IOException;
  6. import java.security.Key;
  7. import java.security.KeyPair;
  8. import java.security.KeyPairGenerator;
  9. import java.security.MessageDigest;
  10. import java.security.NoSuchAlgorithmException;
  11. import java.security.PrivateKey;
  12. import java.security.PublicKey;
  13. import java.security.SecureRandom;
  14. import java.security.Signature;
  15. import javax.crypto.Cipher;
  16. import javax.crypto.SecretKey;
  17. import javax.crypto.SecretKeyFactory;
  18. import javax.crypto.spec.DESKeySpec;
  19. import org.apache.commons.logging.Log;
  20. import org.apache.commons.logging.LogFactory;
  21. import sun.misc.BASE64Decoder;
  22. import sun.misc.BASE64Encoder;
  23. /**
  24. * 功能简述: 加密解密工具类,对MD5/BASE64/DES/RSA等算法提供了包装.
  25. * @author Nick Xu
  26. * @version 1.0
  27. */
  28. public class EncryptUtil {
  29. private static Log logger = LogFactory.getLog(EncryptUtil.class);
  30. private static final int KEY_SIZE = 1024;
  31. private static final String MD5_ALGORITHM= “md5”;
  32. private static final String DES_ALGORITHM= “des”;
  33. private static final String RSA_ALGORITHM= “rsa”;
  34. private static final String SIGNATURE_ALGORITHM= “MD5withRSA”;
  35. private static MessageDigest md5;
  36. private static BASE64Encoder encoder;
  37. private static BASE64Decoder decoder;
  38. private static SecureRandom random;
  39. private static KeyPair keyPair;
  40. private EncryptUtil() {
  41. }
  42. static {
  43. try {
  44. md5 = MessageDigest.getInstance(MD5_ALGORITHM);
  45. KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
  46. keyPairGenerator.initialize(KEY_SIZE);
  47. keyPair = keyPairGenerator.generateKeyPair();
  48. }
  49. catch (NoSuchAlgorithmException e) {
  50. // Exception handler
  51. logger.error(e);
  52. }
  53. encoder = new BASE64Encoder();
  54. decoder = new BASE64Decoder();
  55. random = new SecureRandom();
  56. }
  57. /**
  58. * 功能简述: 使用md5进行单向加密.
  59. */
  60. public static String encryptMD5(String plainText) {
  61. byte[] cipherData = md5.digest(plainText.getBytes());
  62. StringBuilder builder = new StringBuilder();
  63. for(byte cipher : cipherData) {
  64. String toHexStr = Integer.toHexString(cipher & 0xff);
  65. builder.append(toHexStr.length() == 1 ? “0” + toHexStr : toHexStr);
  66. }
  67. return builder.toString();
  68. }
  69. /**
  70. * 功能简述: 使用BASE64进行加密.
  71. * @param plainData 明文数据
  72. * @return 加密之后的文本内容
  73. */
  74. public static String encryptBASE64(byte[] plainData) {
  75. return encoder.encode(plainData);
  76. }
  77. /**
  78. * 功能简述: 使用BASE64进行解密.
  79. * @param cipherText 密文文本
  80. * @return 解密之后的数据
  81. */
  82. public static byte[] decryptBASE64(String cipherText) {
  83. byte[] plainData = null;
  84. try {
  85. plainData = decoder.decodeBuffer(cipherText);
  86. }
  87. catch (IOException e) {
  88. // Exception handler
  89. logger.error(e);
  90. }
  91. return plainData;
  92. }
  93. /**
  94. * 功能简述: 使用DES算法进行加密.
  95. * @param plainData 明文数据
  96. * @param key 加密密钥
  97. * @return
  98. */
  99. public static byte[] encryptDES(byte[] plainData, String key) {
  100. return processCipher(plainData, createSecretKey(key), Cipher.ENCRYPT_MODE, DES_ALGORITHM);
  101. }
  102. /**
  103. * 功能简述: 使用DES算法进行解密.
  104. * @param cipherData 密文数据
  105. * @param key 解密密钥
  106. * @return
  107. */
  108. public static byte[] decryptDES(byte[] cipherData, String key) {
  109. return processCipher(cipherData, createSecretKey(key), Cipher.DECRYPT_MODE, DES_ALGORITHM);
  110. }
  111. /**
  112. * 功能简述: 根据key创建密钥SecretKey.
  113. * @param key
  114. * @return
  115. */
  116. private static SecretKey createSecretKey(String key) {
  117. SecretKey secretKey = null;
  118. try {
  119. DESKeySpec keySpec = new DESKeySpec(key.getBytes());
  120. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
  121. secretKey = keyFactory.generateSecret(keySpec);
  122. }
  123. catch (Exception e) {
  124. // Exception handler
  125. logger.error(e);
  126. }
  127. return secretKey;
  128. }
  129. /**
  130. * 功能简述: 加密/解密处理流程.
  131. * @param processData 待处理的数据
  132. * @param key 提供的密钥
  133. * @param opsMode 工作模式
  134. * @param algorithm 使用的算法
  135. * @return
  136. */
  137. private static byte[] processCipher(byte[] processData, Key key, int opsMode, String algorithm) {
  138. try{
  139. Cipher cipher = Cipher.getInstance(algorithm);
  140. cipher.init(opsMode, key, random);
  141. return cipher.doFinal(processData);
  142. }
  143. catch (Exception e) {
  144. // Exception handler
  145. logger.error(e);
  146. }
  147. return null;
  148. }
  149. /**
  150. * 功能简述: 创建私钥,用于RSA非对称加密.
  151. * @return
  152. */
  153. public static PrivateKey createPrivateKey() {
  154. return keyPair.getPrivate();
  155. }
  156. /**
  157. * 功能简述: 创建公钥,用于RSA非对称加密.
  158. * @return
  159. */
  160. public static PublicKey createPublicKey() {
  161. return keyPair.getPublic();
  162. }
  163. /**
  164. * 功能简述: 使用RSA算法加密.
  165. * @param plainData 明文数据
  166. * @param key 密钥
  167. * @return
  168. */
  169. public static byte[] encryptRSA(byte[] plainData, Key key) {
  170. return processCipher(plainData, key, Cipher.ENCRYPT_MODE, RSA_ALGORITHM);
  171. }
  172. /**
  173. * 功能简述: 使用RSA算法解密.
  174. * @param cipherData 密文数据
  175. * @param key 密钥
  176. * @return
  177. */
  178. public static byte[] decryptRSA(byte[] cipherData, Key key) {
  179. return processCipher(cipherData, key, Cipher.DECRYPT_MODE, RSA_ALGORITHM);
  180. }
  181. /**
  182. * 功能简述: 使用私钥对加密数据创建数字签名.
  183. * @param cipherData 已经加密过的数据
  184. * @param privateKey 私钥
  185. * @return
  186. */
  187. public static byte[] createSignature(byte[] cipherData, PrivateKey privateKey) {
  188. try {
  189. Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  190. signature.initSign(privateKey);
  191. signature.update(cipherData);
  192. return signature.sign();
  193. }
  194. catch (Exception e) {
  195. // Exception handler
  196. logger.error(e);
  197. }
  198. return null;
  199. }
  200. /**
  201. * 功能简述: 使用公钥对数字签名进行验证.
  202. * @param signData 数字签名
  203. * @param publicKey 公钥
  204. * @return
  205. */
  206. public static boolean verifySignature(byte[] cipherData, byte[] signData, PublicKey publicKey) {
  207. try {
  208. Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
  209. signature.initVerify(publicKey);
  210. signature.update(cipherData);
  211. return signature.verify(signData);
  212. }
  213. catch (Exception e) {
  214. // Exception handler
  215. logger.error(e);
  216. }
  217. return false;
  218. }
  219. }

<二>. Commons Codec对BASE64的扩展支持:

  1. JDK提供了对BASE64的标准支持,每隔76个字符进行换行\\r\\n,并且包含+、=、/等特殊字符不适合作为url参数传递。因此通常都会使用Commons Codec来进行BASE64的加密和解密。下载commons-codec-1.8.jar并添加到lib下面,注意选择高版本,低版本有些方法不支持。![天真][smiley-innocent.gif]
  1. 是否换行:

Java代码

  1. byte[] cipherData = Base64.encodeBase64(plainText.getBytes()); //默认不换行
  2. byte[] cipherData = Base64.encodeBase64(plainText.getBytes(), false); //取消换行
  3. byte[] cipherData = Base64.encodeBase64Chunked(plainText.getBytes()); //进行换行
  4. String cipherText = Base64.encodeBase64String(plainText.getBytes()); //转为字符串

    1. 安全的url:转换+为-、/为_、将多余的=去掉

Java代码

  1. byte[] cipherData = Base64.encodeBase64(plainText.getBytes(), false, true);
  2. byte[] cipherData = Base64.encodeBase64URLSafe(plainText.getBytes());
  3. String cipherText = Base64.encodeBase64URLSafeString(plainText.getBytes());

发表评论

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

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

相关阅读