AES/CFB/NOPADDING 加密到解密不工作

AES/CFB/NOPADDING Encrypt to Decrypt not working

谁能指导我哪里出了问题?加密解密在这种情况下不起作用。

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 静态字符串解密(字节 [] 加密) 抛出 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"));

}

您基本上是为每个操作生成一个新的对称密钥 (encryption/decryption)。但是对称加密算法需要相同的密钥来加密和解密相同的值。所以你可以试试:

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