AES加密的gcm模式java实现代码
时间: 2023-05-11 08:06:33 浏览: 317
JS实现AES-GCM加密,java实现AES-GCM解密。.md
以下是AES加密的gcm模式java实现代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
public class AESGCMEncryptor {
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_LENGTH = 16;
private static final String ALGORITHM = "AES/GCM/NoPadding";
public static byte[] encrypt(byte[] plaintext, byte[] key) throws Exception {
SecureRandom random = new SecureRandom();
byte[] iv = new byte[GCM_IV_LENGTH];
random.nextBytes(iv);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
byte[] ciphertext = cipher.doFinal(plaintext);
byte[] result = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(ciphertext, 0, result, iv.length, ciphertext.length);
return result;
}
}
```
希望这个代码能够帮到你!
阅读全文