簡體   English   中英

嘗試加密字符串時為什么會出現BadPaddingException?

[英]Why do I get BadPaddingException when trying to encrypt a string?

通過此鏈接 ,我創建了一個Encryption類來Encryption /解密Android項目中的二進制數據。

package com.my.package;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

// TODO Incomplete class
public class Encryption {

    private static final byte[] salt = { (byte) 0xA4, (byte) 0x0B, (byte) 0xC8,
            (byte) 0x34, (byte) 0xD6, (byte) 0x95, (byte) 0xF3, (byte) 0x13 };

    private static int BLOCKS = 128;

    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    private static byte[] decrypt(byte[] raw, byte[] encrypted)
            throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    private static byte[] getKey() throws Exception {
        byte[] keyStart = "this is a key".getBytes();
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(keyStart);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();
        byte[] key = skey.getEncoded();
        return key;
    }

    public static void test() {
        String test = "My Name Is Dragon Warrior";

        byte[] e = null;
        try {
            e = encrypt(getKey(), test.getBytes());
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        byte[] d = null;
        try {
            d = decrypt(getKey(), e);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println(new String(d));
    }
}

然后在主要活動中運行代碼:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // ...
    Encryption.test();
    // ...
}

然后在test()執行以下代碼時,我得到BadPaddingException

try {
    d = decrypt(getKey(), e);
} catch (Exception e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

有趣的是,我創建了一個Java項目而不是Android項目。 而且代碼運行正常,沒有任何異常。

我的代碼有什么問題?

“ SHA1PRNG” 不是關鍵的派生功能,並且在提供程序之間的實現可能有所不同。 請使用正確的KDF(例如PBKDF2)作為密碼。 “這是鍵” 不是鍵,是字符串。

暫無
暫無

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

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