在Java中调用AES的加解密方法很简单,因为系统提供了很好的函数支持;但在C/C++中需要用户自己实现,因此需要学习AES加密的不同实现方式,以便正确的实现。
Java中的代码实现:
public class Aes {
public static String encrypt(String content, String password) throws Exception {
return parseByte2HexStr(encrypt(content.getBytes(),
parseHexStr2Byte(password)));
}
// 解密
public static String decrypt(String content, String password) throws Exception {
return decrypt(parseHexStr2Byte(content), parseHexStr2Byte(password));
}
private static byte[] encrypt(byte[] content, byte[] password) {
try {
byte[] enCodeFormat = new byte[16];
for (int i = 0; i < 16; i++) {
if (i < password.length)
enCodeFormat[i] = password[i];
else
enCodeFormat[i] = 0;
}
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);