Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 基于密码的加密解密中最后一个块不完整_Java_Password Encryption - Fatal编程技术网

Java 基于密码的加密解密中最后一个块不完整

Java 基于密码的加密解密中最后一个块不完整,java,password-encryption,Java,Password Encryption,我在使用PBEWITHSA256和256BITAES CBC BC算法进行基于密码的加密/解密时遇到问题。当我进入cipher.doFinal时,我得到:javax.crypto.IllegalBlockSizeException:解密中的最后一个块未完成 public static String encrypt(String salt, String password, byte[] object) throws GeneralSecurityException { PBEParame

我在使用PBEWITHSA256和256BITAES 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);

我错过什么了吗?当其他人遇到此异常时,他们没有使用相同的salt进行加密和解密,或者他们没有解码来自Base64的加密文本。这些都不能解决我的问题

加密和解密的输出应该是字节[],而不是字符串

PBEWITHSA256和256BITAES CBC BC应仅用于密钥生成过程,而不用于加密/解密过程本身

您只应继续,例如:

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