public static byte[] generateDesKey(int length) throws Exception {
//实例化
KeyGenerator kgen = null;
kgen = KeyGenerator.getInstance("AES");
//设置密钥长度
kgen.init(length);
//生成密钥
SecretKey skey = kgen.generateKey();
//返回密钥的二进制编码
return skey.getEncoded();
}
byte[] aesKey = generateDesKey(256);
AES加密
public static byte[] Aes256Encode(String str, byte[] key) throws Exception {
byte[] result = null;
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); // 生成加密解密需要的Key
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
result = cipher.doFinal(str.getBytes("UTF-8"));
return result;
}
public static final String ALGORITHM = "AES/ECB/PKCS5Padding";