0

我正在尝试使用 AES/ECB/PKCS7Padding 创建加密和解密函数。

private static byte[] INITIALIZATION_VECTOR = new byte[] { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
public static String encrypt(String token) {
    Cipher cipher = null;
    SecretKey key = null;
    String tokenAsHex = null;
    byte[] encryptedToken = null;
    byte[] sksKey = "6iOmT2V6mnd0".getBytes(); // SecretKeySpec key.

    try {
        key = new SecretKeySpec(sksKey, "AES");
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(INITIALIZATION_VECTOR);
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        encryptedToken = cipher.doFinal(token.getBytes("UTF-8"));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Base64.encodeBase64String(encryptedToken);
}

public static String decrypt(String token) {
    Cipher cipher = null;
    SecretKey key = null;
    byte[] decryptedToken = null;
    byte[] sksKey = "6iOmT2V6mnd0".getBytes(); // SecretKeySpec key.
    try {
        key = new SecretKeySpec(sksKey, "AES");            
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(INITIALIZATION_VECTOR);
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
        cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        decryptedToken = cipher.doFinal(Base64.decodeBase64(token));
    } catch(Exception e){
        e.printStackTrace();    
    }
    if (decryptedToken == null) {
         System.out.println("Unable to decrypt the following token: " + token);
    }
    return new String(decryptedToken);
}

我已经编辑了我的程序。

现在 dycryption 似乎有效,但它只适用于 PKCS5Padding ,当我尝试使用 PKCS7Padding 时,它说它找不到提供者,怎么可能?

4

1 回答 1

2

你有几个错误:

  1. 不要将密文转换为字符串 - 这可能是有损转换。相反,将其保留为字节数组或将其转换为十六进制或 base64。

  2. 您需要存储 IV 以供解密期间使用。目前你只是把它扔掉(在你的enc方法中)。一种常见的技术是在密文前面加上你的 IV(可能用分隔符分隔)。

  3. 当您从解密的字节创建字符串时,您应该指定一个字符集。

这可能不是一个详尽的列表,但肯定足以给您带来重大问题。修复这些问题,然后让我们知道您是否仍然看到错误(并在您的问题中发布错误)。

此外,返回一个字符串"error"也是糟糕的设计。在 Java 中,使用异常表示出现问题。

于 2013-06-27T09:42:31.523 回答