AES加密解密代码实现时间:2021-11-13 07:54:23package com.lengyu.djmusic.domain;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;/** * @author lengyu * * AES加密解密实现 */public class AES {private final static String algorithm = "AES";private static String asHex(byte buf[]) {StringBuffer strbuf = new StringBuffer(buf.length * 2);int i;for (i = 0; i < buf.length; i++) {if (((int) buf[i] & 0xff) < 0x10)strbuf.append("0");strbuf.append(Long.toString((int) buf[i] & 0xff, 16));}return strbuf.toString();}private static byte[] asBin(String src) {if (src.length() < 1)return null;byte[] encrypted = new byte[src.length() / 2];for (int i = 0; i < src.length() / 2; i++) {int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);encrypted[i] = (byte) (high * 16 + low);}return encrypted;}public static String getRawKey() {try {// Get the KeyGeneratorKeyGenerator kgen = KeyGenerator.getInstance(algorithm);kgen.init(128); // 192 and 256 bits may not be available// Generate the secret key specs.SecretKey skey = kgen.generateKey();byte[] raw = skey.getEncoded();return asHex(raw);} catch (Exception e) {// App.log.info("AES", "获取密钥出错," + e.getMessage());return "";}}/** * 加密 * * @param message * @param rawKey * @return */public static String getEncrypt(String message, String rawKey) {byte[] key = asBin(rawKey);try {SecretKeySpec skeySpec = new SecretKeySpec(key, algorithm);Cipher cipher = Cipher.getInstance(algorithm);cipher.init(Cipher.ENCRYPT_MODE, skeySpec);byte[] encrypted = cipher.doFinal(message.getBytes());return asHex(encrypted);} catch (Exception e) {// App.log.info("AES", "获取加密串出错," + e.getMessage());return "";}}/** * 解密 * * @param encrypted * @param rawKey * @return */public static String getDecrypt(String encrypted, String rawKey) {byte[] tmp = asBin(encrypted);byte[] key = asBin(rawKey);try {SecretKeySpec skeySpec = new SecretKeySpec(key, algorithm);Cipher cipher = Cipher.getInstance(algorithm);cipher.init(Cipher.DECRYPT_MODE, skeySpec);byte[] decrypted = cipher.doFinal(tmp);return new String(decrypted);} catch (Exception e) {// App.log.info("AES", "获取解密串出错," + e.getMessage());return "";}}public static void main(String[] args) throws Exception {String message = "需要被加密的字符串";// 需要被加密的字符串String rawKey = getRawKey(); // 得到钥匙System.out.println("Key = " + rawKey);String encrypted = getEncrypt(message, rawKey);System.out.println("org text = " + message);// 原数据System.out.println("encrypted = " + encrypted);// 加密以后String decrypted = getDecrypt(encrypted, rawKey);// 解密串System.out.println("解密串 = " + decrypted);}}