一、byte和hex的相互转换:
byte->String :Hex.encodeHexString(byte[]);
String->byte[]:Hex.decodeHex(str.toCharArray());
二、实例代码:
package com.szy.project.test;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.codec.binary.Hex;
/**对称加解密
* @author sunzy
*/
public class AES {
/**秘钥*/
private static String KEY = "wszsdaaa";
/**初始化向量参数*/
private static String IV = "reshengdeyixjhoa";
public static void main(String[] args) {
String content="我喜欢美女";
try {
System.out.println("加密前:"+content);
String encrypt = encrypt(content);
System.out.println("加密后:"+encrypt);
System.out.println("解密后:"+decrypt(encrypt));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 加密
* @param content 加密信息
* @return
* @throws Exception
*/
public static String encrypt(String content) throws Exception{
KeyGenerator keyGenerator=KeyGenerator.getInstance("AES");
keyGenerator.init(128, new SecureRandom(KEY.getBytes()));
SecretKey key=keyGenerator.generateKey();
Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));
return Hex.encodeHexString(cipher.doFinal(content.getBytes()));
}
/**
* 解密
* @param content 解密信息
* @return
* @throws Exception
*/
public static String decrypt(String content) throws Exception{
KeyGenerator keyGenerator=KeyGenerator.getInstance("AES");
keyGenerator.init(128, new SecureRandom(KEY.getBytes()));
SecretKey key=keyGenerator.generateKey();
Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));
return new String(cipher.doFinal(Hex.decodeHex(content.toCharArray())));
}
}