我需要加密/解密用户名字段,我打算使用下面的代码:
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);
}
}
我已从另一个站点获取此代码。上面的代码在独立运行时工作正常。但是我面临的问题是如何在用户名已经加密时解密该值?
我将从不同的类调用加密和解密函数,所以如果字符串已经加密并存储在数据库中,那么当用户登录网站时,当我调用解密方法时,如何将 IV 作为 CBC 模式传递解密需要一个 IV 参数,而我在加密期间没有存储 iv ???
任何帮助深表感谢!!
注意:这与密码保护无关。如前所述,需要加密用户 ID 而不是密码!对于密码保护,我只使用哈希。