基于密码的加密 - 最后一个块在解密时不完整

时间:2015-02-10 11:56:38

标签: java password-encryption

我使用PBEWithSHA256And256BitAES-CBC-BC算法遇到基于密码的加密/解密问题。当我得到cipher.doFinal时,我得到:javax.crypto.IllegalBlockSizeException:解密时最后一个块不完整。

public static String encrypt(String salt, String password, byte[] object) throws GeneralSecurityException {
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt.getBytes(), 1000);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());

        SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        Cipher encryptionCipher = Cipher.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
        encryptionCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

        byte[] encryptedObject = encryptionCipher.doFinal(object);

    return new String(encryptedObject);
}

public static String decrypt(String encryptedObject, String password, String salt) throws GeneralSecurityException{
    PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), 1000);
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());

        SecretKeyFactory keyFactory
                = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
        SecretKey passwordKey = keyFactory.generateSecret(keySpec);

        Cipher cipher = Cipher.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
        cipher.init(Cipher.DECRYPT_MODE, passwordKey, parameterSpec);

        byte[] decryptedObject = cipher.doFinal(encryptedObject.getBytes());

    return new String(decryptedObject);
}

主要:

Security.addProvider(new BouncyCastleProvider());
String text = "plaintext";
String salt = "salt";
String password = "password";
String encrypted = encrypt(salt, password, text.getBytes());
String decrypted = decrypt(encrypted, password, salt);
System.out.println(decrypted);

我错过了什么吗?当其他人得到这个例外时,他们没有使用相同的盐进行加密和解密,或者他们没有从Base64解码加密文本。这些都没有解决我的问题。

2 个答案:

答案 0 :(得分:0)

加密和解密的输出应该是byte []而不是String。

答案 1 :(得分:0)

PBEWithSHA256And256BitAES-CBC-BC仅应用于密钥生成过程,而不应用于加密/解密过程本身。

您应该只使用(例如):

继续
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");