'Cipher AES/CBC/PKCS5Padding cant decrypt after application reinitialization

I'm trying to encrypt and decrypt some texts using Cipher with the "AES/CBC/PKCS5Padding" algorithm but if I restart the application the text that was encrypt can't be decrypted. I'm encrypting the text, transforming the encrypted bytes in base64 text, storing it and retrieving it when necessary, so transforming the base64 text in bytes and trying to decrypt to take the original text.

The code I'm using is:

private static SecretKey getKeyFromPassword(String password, String salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(UTF_8),
            65536, 256);
    SecretKey secret = new SecretKeySpec(factory.generateSecret(spec)
            .getEncoded(), "AES");
    return secret;
}


private static IvParameterSpec generateIv() {
    byte[] iv = new byte[16];
    new SecureRandom().nextBytes(iv);
    return new IvParameterSpec(iv);
}

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        // string for test
        String teste = "teste teste teste teste";

        //getting start with Cipher
        SecretKey secretKey = getKeyFromPassword("pass", "salt");
        IvParameterSpec ivParameterSpec = generateIv();
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        //encrypting
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        byte[] cipherText = new byte[0];
        cipherText = cipher.doFinal(teste.getBytes(UTF_8));

        // encrypt to base64 text
        String criptado = Base64.getEncoder().encodeToString(cipherText);
        

        //decripting
        byte[] plainText = new byte[0];
        byte[] rawText = Base64.getDecoder().decode(criptado);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        plainText = cipher.doFinal(rawText);
        String decriptado = new String(plainText);

The problem is something with the size of the bit key? Like in this topic: java AES/CBC/PKCS5PADDING in php (AES-256-CBC) resulting different result

I took this guide to the code: baeldung.com/java-aes-encryption-decryption



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source