Java实现代码
private static final byte[] IV = {16, 26, -35, 23, 34, 125, -5, -4, -8, -9, -15, -78, 90, -8, -99, 100};
public static byte[] encrypt(String content, String password) {
try {
SecretKeySpec key = getKey(password);
if(key == null){
return null;
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV));
byte[] result = cipher.doFinal(byteContent);
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String encryptToStr(String content, String password) {
byte[] bytes = encrypt(content, password);
if(bytes == null){
return null;
}
return Base64Util.encode(bytes);
}
public static byte[] decrypt(byte[] content, String password) {
try {
SecretKeySpec key = getKey(password);
if(key == null){
return null;
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String decryptFromStr(String encodeStr, String password) {
byte[] encodeBytes = Base64Util.decodeToBytes(encodeStr);
byte[] bytes = decrypt(encodeBytes, password);
if(bytes == null){
return null;
}
return new String(bytes);
}
private static SecretKeySpec getKey(String password){
try {
byte[] passwdBytes = password.getBytes("utf-8");
if(passwdBytes.length < 16){
return null;
}
byte[] bytes = new byte[16];
for(int i = 0; i < 16; i++){
bytes[i] = passwdBytes[i];
}
return new SecretKeySpec(bytes, "AES");
}catch(Exception e){
e.printStackTrace();
return null;
}
}
AES加密模式和填充方式
算法/模式/填充 | 16字节加密后数据长度 | 不满16字节加密后长度 |
---|
AES/CBC/NoPadding | 16 | 不支持 |
AES/CBC/PKCS5Padding | 32 | 16 |
AES/CBC/ISO10126Padding | 32 | 16 |
AES/CFB/NoPadding | 16 | 原始数据长度 |
AES/CFB/PKCS5Padding | 32 | 16 |
AES/CFB/ISO10126Padding | 32 | 16 |
AES/ECB/NoPadding | 16 | 不支持 |
AES/ECB/PKCS5Padding | 32 | 16 |
AES/ECB/ISO10126Padding | 32 | 16 |
AES/OFB/NoPadding | 16 | 原始数据长度 |
AES/OFB/PKCS5Padding | 32 | 16 |
AES/OFB/ISO10126Padding | 32 | 16 |
AES/PCBC/NoPadding | 16 | 不支持 |
AES/PCBC/PKCS5Padding | 32 | 16 |
AES/PCBC/ISO10126Padding | 32 | 16 |