AES-GCM Example in Java
bindon
2019-11-28
Security Guide
Implementation
package io.github.bindon;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesGcmExample {
public static final int AES_KEY_SIZE = 256;
public static final int GCM_IV_LENGTH = 12;
public static final int GCM_TAG_LENGTH = 16;
public static void main(String[] args) throws Exception {
// Generate SecretKey
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(AES_KEY_SIZE);
SecretKey secretKey = keyGenerator.generateKey();
// Generate IV
byte[] iv = new byte[GCM_IV_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
// Initialize
String plaintext = "bindon";
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
// Encrypt
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
// Decrypt
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
byte[] decryptedText = cipher.doFinal(ciphertext);
// Print
System.out.println("Original Text : " + plaintext);
System.out.println("Encrypted Text : " + Base64.getUrlEncoder().encodeToString(ciphertext));
System.out.println("Decrypted Text : " + new String(decryptedText, StandardCharsets.UTF_8));
}
}
Result
Original Text : bindon
Encrypted Text : Exxq04kFmtfgFf5Rvp4kp0th7cDwkg==
Decrypted Text : bindon
Security Guide Post List
TITLE | DATE | File Upload | 2020-02-26 | API Security | 2020-02-26 | HTTP Security Headers | 2020-02-21 | CSRF(Cross Site Request Forgery) Prevention | 2020-02-20 | XSS(Cross-Site Scripting) Prevention | 2020-02-17 | AES-GCM Example in Java | 2019-11-28 | ECDH Example in Java | 2019-11-25 |
---|