小编Bea*_*956的帖子

在Java加密和解密中处理IV和salt

所以我想在一个方法来解密消息,但它不工作,因为我需要做cipher.init(Cipher.ENCRYPT_MODE, secret)之前,我尝试添加new IvParameterSpec(iv)cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));.否则,它只返回一个NullPointerException我想知道是否可以在方法中执行此操作而不是一直写入它.我真的不能想到一个解决方案,这就是为什么我在这里.加密工作正常但不解密.

项目运行: JRE 7

加密代码:

public static String encrypt(String str) {
    try {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(str.toCharArray(), salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret); //<--- Need to do this before writing IvPerameterSpec,
        // But I think that it's not possible if …
Run Code Online (Sandbox Code Playgroud)

java encryption nullpointerexception

2
推荐指数
1
解决办法
6021
查看次数

标签 统计

encryption ×1

java ×1

nullpointerexception ×1