Spring Security Crypto - BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption

Viewed 427

The working code can run for first time but cannot run for second time.

BadPaddingException throw out

IllegalStateException: Unable to invoke Cipher due to bad padding

Spring Security Crypto 5.1.3

public class Cryptographer {

    private TextEncryptor encryptor;
    private static Cryptographer crypto;
    private Cryptographer() {
    }
    public static Cryptographer getInstance() {
        if (crypto == null) {
            Security.setProperty("crypto.policy", "unlimited");
            crypto = new Cryptographer();
        }

        return crypto;
    }
    public synchronized void generateEncryptedPwd(final String encryptPwd, String filePath) {
        try {
            final String salt = KeyGenerators.string().generateKey();
            encryptor = Encryptors.text(encryptPwd, salt);

            File encryptedFile = new File(filePath);
            Files.write(encryptor.encrypt(encryptPwd).getBytes(), encryptedFile);
        } catch (IOException ex) {
            MyLogManager.logger.log(Level.INFO, "Exception: " + ex.getMessage());
        }
    }
    public synchronized String decryptPwd(String filePath) {
        String decryptedStr="";
        try {
            File fr = new File(filePath);
            Scanner sc = new Scanner(fr);
            decryptedStr = sc.nextLine();
            decryptedStr = encryptor.decrypt(decryptedStr);

        } catch (IOException ex) {
            MyLogManager.logger.log(Level.INFO, "Exception: " + ex.getMessage());
        }

        return decryptedStr;
    }
}

Calling code:

crypt.generateEncryptedPwd("demouser", ".\\credential\\phptravels_demo.txt");

Questions: I don't want to expose demouser password to anyone and I don't want to call the generatedEncryptedPwd method anymore but got NullPointerException.

0 Answers
Related