使用Java实现JWE规范下的AES-256-GCM算法签名,使用中文注释
时间: 2024-05-02 11:18:43 浏览: 294
以下是使用Java实现JWE规范下的AES-256-GCM算法签名的示例代码:
```java
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class JWE_AES_256_GCM {
public static void main(String[] args) throws Exception {
// 生成随机密钥
Key key = generateKey();
System.out.println("随机密钥:" + Base64.getUrlEncoder().withoutPadding().encodeToString(key.getEncoded()));
// 加密明文数据
String plaintext = "Hello world!";
String cipherText = encrypt(plaintext, key);
System.out.println("加密后的数据:" + cipherText);
// 解密密文数据
String decryptedText = decrypt(cipherText, key);
System.out.println("解密后的数据:" + decryptedText);
}
/**
* 生成随机密钥
*/
public static Key generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256, new SecureRandom());
return keyGenerator.generateKey();
}
/**
* 加密明文数据
*/
public static String encrypt(String plaintext, Key key) throws Exception {
byte[] plaintextBytes = plaintext.getBytes("UTF-8");
// 生成随机IV
byte[] iv = generateIv();
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, parameterSpec);
byte[] ciphertextBytes = cipher.doFinal(plaintextBytes);
// 将IV和密文拼接成JWE字符串
String ivString = Base64.getUrlEncoder().withoutPadding().encodeToString(iv);
String ciphertextString = Base64.getUrlEncoder().withoutPadding().encodeToString(ciphertextBytes);
return ivString + "." + ciphertextString;
}
/**
* 解密密文数据
*/
public static String decrypt(String jwe, Key key) throws Exception {
// 解析JWE字符串,获取IV和密文
String[] parts = jwe.split("\\.");
byte[] iv = Base64.getUrlDecoder().decode(parts[0]);
byte[] ciphertextBytes = Base64.getUrlDecoder().decode(parts[1]);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.DECRYPT_MODE, keySpec, parameterSpec);
byte[] plaintextBytes = cipher.doFinal(ciphertextBytes);
return new String(plaintextBytes, "UTF-8");
}
/**
* 生成随机IV
*/
public static byte[] generateIv() {
byte[] iv = new byte[12];
new SecureRandom().nextBytes(iv);
return iv;
}
}
```
阅读全文