标签:取数 编码方式 password bbr secure ringbuf actor tde turn
许久没有写博客了,有些惶恐地打开这个再熟悉不过的编辑器。
场景:要对一个涉及到敏感数据(账号、密码)的接口进行加密后返回
由于之前没有相关的经验,所以先在网上搜罗了一阵,这篇博客不错https://www.cnblogs.com/codeon/p/6123863.html给了我一些思路和启发。
先来介绍两个模糊不清,容易搞混的概念。
加密方式的确定:最后我的接口中的敏感明文信息通过AES进行加密,最后将密文返回给客户端。
网上的一些AES加解密示例中,很多在AES解密步骤时会出现javax.crypto.BadPaddingException: Given final block not properly padded问题,而且很多答案都说的似是而非,经过我的调试和修正后,以下代码可以正常的完成AES/DES的加解密操作。
package com.test.utils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * @Author: LeeChao * @Date: 2018/7/5 * @Describe: 加密工具类 * @Modified By: */ public class EncryptUtil { public static final Logger LOGGER = LogManager.getLogger(EncryptUtil.class); // 此处使用AES-128-CBC加密模式,key需要为16位。 private static final String AES_ENCRYPT_MODE = "AES/CBC/PKCS5Padding"; // 16固定的偏移向量 private static final String IV_PARAMETER = "1234567890abcdef"; private final static String DES_ENCRYPT_MODE = "DES"; /** * AES加密 * * @param aesKey 加密用的Key 可以用26个字母和数字组成, * @param content * @return * @throws Exception */ public static String aesEncrypt(String aesKey, String content) { // 初始化返回结果 String result = null; try { Cipher cipher = Cipher.getInstance(AES_ENCRYPT_MODE); byte[] raw = aesKey.getBytes(); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); // 使用CBC模式,需要一个向量iv,可增加加密算法的强度 IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(content.getBytes("utf-8")); // 此处使用BASE64做转码。 result = new BASE64Encoder().encode(encrypted); // Base64加密后的换行符去掉 result = result.replaceAll("\\r\\n", "").replaceAll("\r", "").replaceAll("\n", ""); } catch (Exception e) { LOGGER.error("AES加密异常" + e); } return result; } /** * AES解密 * * @param aesKey * @param content * @return * @throws Exception */ public static String aesDecrypt(String aesKey, String content) { // 初始化返回结果 String result = null; try { byte[] raw = aesKey.getBytes("ASCII"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance(AES_ENCRYPT_MODE); IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] encrypted1 = new BASE64Decoder().decodeBuffer(content);//先用base64解密 byte[] original = cipher.doFinal(encrypted1); result = new String(original, "utf-8"); } catch (Exception e) { LOGGER.error("AES解密异常" + e); } return result; } /** * MD5散列为16位定长输出 * * @param sourceStr * @return */ public static String MD5(String sourceStr) { String result16 = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(sourceStr.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } // 32位截取为16位 result16 = buf.toString().substring(8, 24); } catch (NoSuchAlgorithmException e) { LOGGER.error(e); } return result16; } /********************DES加密方式***********************/ public static byte[] desEncrypt(byte[] src, byte[] key) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ENCRYPT_MODE); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(DES_ENCRYPT_MODE); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); // 正式执行加密操作 return cipher.doFinal(src); } /** * @param password 密码 * @param key 加密字符串 * @return */ public final static String desEncrypt(String password, String key) { try { return byte2String(desEncrypt(password.getBytes(), key.getBytes())); } catch (Exception e) { } return null; } public static String byte2String(byte[] b) { String hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) { stmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length() == 1) hs = hs + "0" + stmp; else hs = hs + stmp; } return hs.toUpperCase(); } /** * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return * @throws Exception */ public static byte[] desDecrypt(byte[] src, byte[] key) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ENCRYPT_MODE); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance(DES_ENCRYPT_MODE); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // 正式执行解密操作 return cipher.doFinal(src); } public final static String desDecrypt(String data, String key) { try { return new String(desDecrypt(String2byte(data.getBytes()), key.getBytes())); } catch (Exception e) { e.printStackTrace(); } return null; } public static byte[] String2byte(byte[] b) { if ((b.length % 2) != 0) throw new IllegalArgumentException("长度不是偶数"); byte[] b2 = new byte[b.length / 2]; for (int n = 0; n < b.length; n += 2) { String item = new String(b, n, 2); b2[n / 2] = (byte) Integer.parseInt(item, 16); } return b2; } private static String testDecryptAES(String authCode, String cipherText) { System.out.println("=====================AES解密====================="); String key = MD5(authCode); // md5散列出16位固定长度的秘钥 System.out.println("md5-16 :" + key); long encryptTime = System.currentTimeMillis(); String deString = aesDecrypt(key, cipherText); long endTime = System.currentTimeMillis(); System.out.println("解密耗时:" + (endTime - encryptTime) + "毫秒"); System.out.println("解密后的字串是:" + deString); return deString; } public static void main(String[] args) throws Exception { // code String authCode = "8373964002824192"; // config_info String cipherText = "iiK82bTFJLZupt0GuvPZ6vx/OrFdcnHrvVjC4rhPjQz15vFeVzV/TvotNZYi3K6V2NHMLwPdhd4YLQw1e/Wr78Jdemif/yMSvR6CmU5UtnrKs0QgDoOsepRxD5t996tzxW18n/SCsn++h1sokdzs8HvEI0tBP5Z0p5wMQRvi6rq1BadqCySbTGCg3LIpy0yeO/FXufZZw6A5yJ/PruOsGywyxHRwSLABMBR1C3HpsXPpXJkvQl6QlkKt38z2wY4K3Ag3+iI7e03kBVbbR/Omz8nir7s7EQzHgfbGlAZNAbA6iKAh/z6W2gToP4VNHPq2NcwCNdODK8TwR7bK3RD657rqYRJ/C7EBTLi+GpC8mTOOorloW9iEkRPB3pqkDk8r8awlJzi0DZXWxuOn+FNGdosm51qN+OJbuNGa7MiNANki8bhHYNV1Mlbh0sDF4vUsNwFjp1ZBldUu1dNUzbl7b2CWgAsYXhc4y2lsOnX8ddXGqXqXiv2n4JFjkgqBsJ3sapIk5WCTeIH8MjzygnXoHduSpXUNlpMVHsjp3xJLmtJEXYimfqOrL+gnbNwfUCQhu+lqNuSDx+nTqJAeQ7cP+c9YThNUjR8fslZSejnK2PJpIkXupmNjM+3t8D7J7kOYZOyRH5eymcL6h499lNYWf//xAx3RTuFSihvVt7ERjj2AVU/0zPABV5X4llBjVrSoJyDZQIDuYqPH3ChI+hwHjSbxw+RZlTtcorYv4fyXDM9/NepGFP3WWgXmnfwI5s/rfio4tsERLuUXTDza6FR9DA=="; // 解密拿到明文 testDecryptAES(authCode, cipherText); System.out.println("=====================AES加密====================="); String key = MD5("8373964002824192"); // md5散列出16位固定长度的秘钥 System.out.println("md5-16 :" + key); // 需要加密的字串 String cSrc = "123abctest"; // 加密 long lStart = System.currentTimeMillis(); String enString = aesEncrypt(key, cSrc); System.out.println("加密后的字串是:" + enString); long lUseTime = System.currentTimeMillis() - lStart; System.out.println("加密耗时:" + lUseTime + "毫秒"); // 解密 lStart = System.currentTimeMillis(); String DeString = aesDecrypt(key, enString); System.out.println("解密后的字串是:" + DeString); lUseTime = System.currentTimeMillis() - lStart; System.out.println("解密耗时:" + lUseTime + "毫秒"); System.out.println("=====================DES加密====================="); String password = "test中英文杂七烂八混搭@123654{"; String info = "123abctest"; long desStart = System.currentTimeMillis(); String encryptString = desEncrypt(info, password); System.out.println(encryptString); System.out.println("DES加密耗时" + (System.currentTimeMillis() - desStart) + "毫秒"); desStart = System.currentTimeMillis(); String desencryptString = desDecrypt(encryptString, password); System.out.println(desencryptString); System.out.println("DES解密耗时" + (System.currentTimeMillis() - desStart) + "毫秒"); } }
标签:取数 编码方式 password bbr secure ringbuf actor tde turn
原文地址:https://www.cnblogs.com/lingyejun/p/9270127.html