簡體   English   中英

使用AES PKCS7Padding進行加密和解密失敗

[英]Encryption and decryption with AES PKCS7Padding Fails

我正在嘗試使用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它說它找不到提供商,它怎么可能?

你有幾個錯誤:

  1. 不要將密文轉換為字符串 - 這可能是有損轉換。 相反,將其保留為字節數組或將其轉換為十六進制或base64。

  2. 您需要存儲IV以便在解密期間使用。 目前你只是扔掉它(在你的enc方法中)。 一種常見的技術是在密文前加上你的IV(可能用分隔符分隔)。

  3. 從解密的字節創建字符串時,應指定字符集。

這可能不是一個詳盡的清單,但它肯定足以引起您的主要問題。 修復這些,然后告訴我們您是否仍然看到錯誤(並在您的問題中發布錯誤 )。

另外,返回帶有"error"的字符串是糟糕的設計。 在Java中,使用異常來指示出錯的地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM