0

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

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 对加密/解密字节数组进行编码,而不是创建一个新字符串,因为后者会导致不安全的 URL 字符串。

4

1 回答 1

1

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

  1. base64-encoding加密,即本质上return Base64.encode(cipher.doFinal(...))
  2. 解密(1)的base64解码,即本质上return cipher.doFinal(Base64.decode(...))
于 2013-03-26T22:16:56.853 回答