如何在Java中获得IV解密?

0 java encryption cryptography aes java-ee

我需要加密/解密用户名字段,我打算使用下面的代码:

public class Decrypter {
    Cipher dcipher;

    byte[] salt = new String("12345678").getBytes();
    int iterationCount = 1024;
    int keyStrength = 256;
    SecretKey key;
    byte[] iv;

    Decrypter(String passPhrase) throws Exception {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keyStrength);
        SecretKey tmp = factory.generateSecret(spec);
        key = new SecretKeySpec(tmp.getEncoded(), "AES");
        dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    }

    public String encrypt(String data) throws Exception {
        dcipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters params = dcipher.getParameters();
        iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        byte[] utf8EncryptedData = dcipher.doFinal(data.getBytes());
        String base64EncryptedData = new sun.misc.BASE64Encoder().encodeBuffer(utf8EncryptedData);

        System.out.println("IV " + new sun.misc.BASE64Encoder().encodeBuffer(iv));
        System.out.println("Encrypted Data " + base64EncryptedData);
        return base64EncryptedData;
    }

    public String decrypt(String base64EncryptedData) throws Exception {
        dcipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
        byte[] decryptedData = new sun.misc.BASE64Decoder().decodeBuffer(base64EncryptedData);
        byte[] utf8 = dcipher.doFinal(decryptedData);
        return new String(utf8, "UTF8");
    }

    public static void main(String args[]) throws Exception {
        Decrypter decrypter = new Decrypter("ABCDEFGHIJKL");
        String encrypted = decrypter.encrypt("StringToBeEncrypted");
        String decrypted = decrypter.decrypt(encrypted);
        System.out.println(decrypted);
    }
} 
Run Code Online (Sandbox Code Playgroud)

我从其他网站上获取了这段代码.上面的代码在独立运行时工作正常.但我面临的问题是如何在用户名已加密时解密该值?

我将从不同的类调用加密和解密函数,所以如果字符串已加密并存储在数据库中,那么当用户登录网站时,当我调用解密方法时,如何将IV作为CBC模式传递解密需要一个IV参数,而我在加密期间没有存储iv?

任何帮助深表感谢!!

注意:这与密码保护无关.如前所述,需要加密userid而不是密码!为了保护密码,我只使用哈希.

SLa*_*aks 8

在加密或解密数据时,您需要提供 IV .

就像哈希的盐一样,IV确保相同的明文永远不会产生压缩的密文.

当您加密每个明文并将其与密文一起存储时,您需要生成(安全)随机IV.

  • 你是否建议我在数据库中保存IV并将其传递给解密? (2认同)