Spring Security Crypto-BadPaddingException:给定最终块未正确填充。如果在解密过程中使用了错误的密钥,则会出现此类问题

时间:2019-01-09 03:41:10

标签: java spring-security

工作代码可以第一次运行,但是不能第二次运行。

BadPaddingException丢掉

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;
    }
}

呼叫代码:

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

问题:我不想向任何人公开demouser密码,也不想再调用generatedEncryptedPwd方法,但得到了NullPointerException

0 个答案:

没有答案