论述
AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据。本文就简单介绍如何通过JAVA实现AES加密。
java实现
加密
/** * 加密 * * @param content * @param encryptKey */ public static String aesEncrypt(String content, String encryptKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { return base64Encode(aesEncryptToBytes(content, encryptKey)); } public static byte[] aesEncryptToBytes(String content, String encryptKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(encryptKey.getBytes())); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES")); return cipher.doFinal(content.getBytes("UTF-8")); } public static String base64Encode(byte[] bytes) { return new BASE64Encoder().encode(bytes); }
解密数据
public static String aesDecrypt(String encryptStr, String decryptKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException { return isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey); } public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(decryptKey.getBytes())); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES")); byte[] decryptBytes = cipher.doFinal(encryptBytes); return new String(decryptBytes, "UTF-8"); } public static byte[] base64Decode(String base64Code) throws IOException { return isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code); }
这里少了一段话是判断为空的方法
/** * 判断是否为空 * * @param str * @return */ public static boolean isEmpty(String str) { if (str == null) { return true; } else if ("".equals(str.trim())) { return true; } else { return false; } }
填写加密数据进行加解密
String content ="{'amt':'" + "0.01" + "'},{'traceNo':'" + "000415" + "'}"; System.out.println("原文:"+content); String encodeContent = aesEncrypt(content,"123456789"); // System.out.println("密文:"+byteToHexString(encodeContent.getBytes())); String decodeContent = aesDecrypt(encodeContent,"123456789"); System.out.println("解密:"+decodeContent);如果加密数据想看十六进制写了转化类
public static String byteToHexString(byte [] byteHex){ String strHex=""; if(byteHex==null) return ""; for(int i=0;i<byteHex.length;i++){ strHex=strHex+String.format("%02X", byteHex[i]); } return strHex; }