java GCM 加密 设置 gcm 256 模式 java 实现
时间: 2024-05-11 20:16:59 浏览: 10
您好!感谢您的问题。关于Java实现GCM 256模式的加密,您可以使用Java Cryptography Extension (JCE)提供的API。以下是一个简单的Java程序示例:
```
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.security.SecureRandom;
public class Main {
public static void main(String[] args) throws Exception {
// 生成一个256位的AES密钥
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
SecretKey key = keyGen.generateKey();
// 原始数据
byte[] plaintext = "hello world".getBytes();
// 随机生成96位的IV向量
SecureRandom random = new SecureRandom();
byte[] iv = new byte[12];
random.nextBytes(iv);
// 创建GCM Cipher对象
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
// 初始化Cipher对象
GCMParameterSpec spec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
// 加密数据
byte[] ciphertext = cipher.doFinal(plaintext);
System.out.println("密文:" + new String(ciphertext));
// 解密数据
cipher.init(Cipher.DECRYPT_MODE, key, spec);
byte[] decrypted = cipher.doFinal(ciphertext);
System.out.println("明文:" + new String(decrypted));
}
}
```
这个程序生成一个256位的AES密钥,使用GCM模式进行加密和解密。加密时,生成一个96位的IV向量,使用Cipher对象进行加密。解密时,同样使用Cipher对象进行解密,需要指定相同的密钥和IV向量。