Java中AES加密和解密的首选方法

时间:2013-03-26 22:10:51

标签: java aes encryption

我编写了以下两种加密和解密给定令牌的方法:

private static final String ALGORITHM_TYPE = "AES";
private static final String CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static byte[] INITIALIZATION_VECTOR = new byte[] {
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};
public String encrypt(String token) {
    Cipher cipher = null;
    SecretKey key = null;
    String tokenAsHex = null;
    byte[] encryptedToken = null;
    byte[] sksKey = getKeyAsByteArray(KEY); // SecretKeySpec key.

    try {
        key = new SecretKeySpec(sksKey, ALGORITHM_TYPE);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(INITIALIZATION_VECTOR);
        cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        encryptedToken = cipher.doFinal(Base64.encodeBase64(token.getBytes("UTF-8")));
    } catch (Exception e) {
        throw new EncryptionException(e);
    }
    return Base64.encodeBase64String(encryptedToken).toLowerCase();
}

public String decrypt(String token) throws EncryptionException {
    Cipher cipher = null;
    SecretKey key = null;
    byte[] decryptedToken = null;
    byte[] sksKey = getKeyAsByteArray(KEY); // SecretKeySpec key.
    try {
        key = new SecretKeySpec(sksKey, ALGORITHM_TYPE);            
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(INITIALIZATION_VECTOR);
        cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        decryptedToken = cipher.doFinal(Base64.decodeBase64(token));
    } catch(Exception e){
        throw new EncryptionException(e);    
    }
    if (decryptedToken == null) {
         throw new EncryptionException("Unable to decrypt the following token: " + token);
    }
    return Base64.encodeBase64String(decryptedToken);
}

但是,我无法成功解密使用encrypt方法加密的任何字符串。我搜索了类似的问题,找到的最近的是:Encrypt and decrypt with AES and Base64 encoding。即使使用类似的策略,我仍然无法解密加密的字符串。任何帮助都可以帮助您诊断问题所在。

此外,我使用Base64对加密/解密的字节数组进行编码,而不是创建新的String,因为后者会导致不安全的URL字符串。

1 个答案:

答案 0 :(得分:1)

您正在加密base64编码,然后重新对其进行64位编码,并解密base64解码,然后由于某种原因使用base64编码。这没有意义。你应该是:

  1. base64-编码加密,即基本上return Base64.encode(cipher.doFinal(...))
  2. 解密(1)的base64解码,即基本上return cipher.doFinal(Base64.decode(...))