[英]AES/CFB/NOPADDING Encrypt to Decrypt not working
can anyone guide me where this is going wrong?谁能指导我哪里出了问题? The encryption to decryption doesn't work in this scenario.
在这种情况下,加密解密不起作用。
public static byte[] encrypt(String value)
throws GeneralSecurityException {
KeyGenerator generator1 = KeyGenerator.getInstance("AES");
generator1.init(128);
Cipher cipher = Cipher.getInstance("AES/CFB/NOPADDING");
cipher.init(Cipher.ENCRYPT_MODE, generator1.generateKey(),
new IvParameterSpec(new byte[16]));
return cipher.doFinal(value.getBytes(Charset.forName("UTF-8")));
} }
public static String decrypt(byte[] encrypted) throws GeneralSecurityException {公共 static 字符串解密(字节 [] 加密)抛出 GeneralSecurityException {
KeyGenerator generator1 = KeyGenerator.getInstance("AES");
generator1.init(128);
Cipher cipher = Cipher.getInstance("AES/CFB/NOPADDING");
cipher.init(Cipher.DECRYPT_MODE, generator1.generateKey(),
new IvParameterSpec(new byte[16]));
byte[] original = cipher.doFinal(encrypted);
return new String(original, Charset.forName("UTF-8"));
} }
You are basically generating a new symmetric key for each operation (encryption/decryption).您基本上是为每个操作(加密/解密)生成一个新的对称密钥。 But symmetric encryption algorithms require the same key for encryption as for decryption of the same value.
但是对称加密算法需要相同的密钥来加密和解密相同的值。 So you can instead try:
因此,您可以尝试:
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class Main {
private static byte[] encrypt(final SecretKey key,
final IvParameterSpec iv,
final byte[] value) throws GeneralSecurityException {
final Cipher cipher = Cipher.getInstance("AES/CFB/NOPADDING");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(value);
}
private static byte[] decrypt(final SecretKey key,
final IvParameterSpec iv,
final byte[] encrypted) throws GeneralSecurityException {
final Cipher cipher = Cipher.getInstance("AES/CFB/NOPADDING");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(encrypted);
}
public static void main(final String[] args) throws GeneralSecurityException {
//Generate the secret symmetric key once:
final KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128);
final SecretKey k = generator.generateKey();
//Generate the same IV once:
final IvParameterSpec iv = new IvParameterSpec(new byte[16]);
//Generate a random plain text to be tested:
final byte[] value = new byte[32];
new Random().nextBytes(value);
System.out.println(Arrays.equals(value, decrypt(k, iv, encrypt(k, iv, value))));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.