AES/CBC/PKCS5Padding加密
阿新 • • 發佈:2018-12-16
package io.swagger.util; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; public class AES { // public static void main(String[] args) throws Exception { // String content = "admin"; // String key = "12345a78g2345678"; // String encryptResult = encrypt(content, key); // String decryptResult = decrypt(encryptResult, key); // System.out.println("加密後:" + encryptResult); // System.out.println("解密後:" + new String(decryptResult)); // } public static String decrypt(String data, String password) throws Exception { byte[] content = parseHexStr2Byte(data); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); KeyGenerator kgen = KeyGenerator.getInstance("AES"); // KeyGenerator提供(對稱)金鑰生成器的功能。使用getInstance 類方法構造金鑰生成器。 kgen.init(128, new SecureRandom(password.getBytes("UTF-8")));// 使用使用者提供的隨機源初始化此金鑰生成器,使其具有確定的金鑰大小。 SecretKey secretKey = kgen.generateKey(); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(password.getBytes("UTF-8")));// 使用解密模式初始化 金鑰 byte[] decrypt = cipher.doFinal(content); return new String(decrypt, "UTF-8"); // 加密 } public static String encrypt(String content, String password) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes("UTF-8"))); SecretKey secretKey = kgen.generateKey(); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(password.getBytes("UTF-8")));// 使用加密模式初始化 金鑰 byte[] encrypt = cipher.doFinal(content.getBytes("UTF-8")); // 按單部分操作加密或解密資料,或者結束一個多部分操作。 return parseByte2HexStr(encrypt); } /** * 將二進位制轉換成16進位制 * * @param buf * @return */ public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 將16進位制轉換為二進位制 * * @param hexStr * @return */ public static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) return null; byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } }