Last active
April 5, 2017 15:11
-
-
Save kevinherron/7bfa0ca7954dc369b70e7df708ab0bb8 to your computer and use it in GitHub Desktop.
Aes256GcmTest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.eclipse.milo.opcua.stack; | |
import java.security.SecureRandom; | |
import java.util.Arrays; | |
import javax.crypto.Cipher; | |
import javax.crypto.spec.GCMParameterSpec; | |
import javax.crypto.spec.SecretKeySpec; | |
import org.eclipse.milo.opcua.stack.core.util.CryptoRestrictions; | |
import org.testng.annotations.Test; | |
import static org.testng.Assert.assertTrue; | |
public class Aes256GcmTest { | |
static { | |
// Needed for 256-bit key length. | |
// Could install unlimited strength crypto policies instead. | |
CryptoRestrictions.remove(); | |
} | |
private static final String TRANSFORMATION = "AES/GCM/NoPadding"; | |
private static final byte[] KEY = new byte[32]; | |
private static final byte[] NONCE = new byte[12]; | |
@Test | |
public void testAesGcm() throws Exception { | |
SecureRandom secureRandom = SecureRandom.getInstanceStrong(); | |
secureRandom.nextBytes(KEY); | |
secureRandom.nextBytes(NONCE); | |
byte[] plainText = new byte[]{1, 2, 3, 4}; | |
byte[] cipherText = encrypt(plainText); | |
System.out.println("plainText: " + Arrays.toString(plainText)); | |
System.out.println("cipherText: " + Arrays.toString(cipherText)); | |
byte[] plainTextPrime = decrypt(cipherText); | |
System.out.println("plainTextPrime: " + Arrays.toString(plainTextPrime)); | |
assertTrue(Arrays.equals(plainText, plainTextPrime)); | |
} | |
private byte[] encrypt(byte[] plainText) throws Exception { | |
SecretKeySpec keySpec = new SecretKeySpec(KEY, "AES"); | |
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, NONCE); | |
Cipher cipher = Cipher.getInstance(TRANSFORMATION); | |
cipher.init(Cipher.ENCRYPT_MODE, keySpec, parameterSpec); | |
return cipher.doFinal(plainText); | |
} | |
private byte[] decrypt(byte[] cipherText) throws Exception { | |
SecretKeySpec keySpec = new SecretKeySpec(KEY, "AES"); | |
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, NONCE); | |
Cipher cipher = Cipher.getInstance(TRANSFORMATION); | |
cipher.init(Cipher.DECRYPT_MODE, keySpec, parameterSpec); | |
return cipher.doFinal(cipherText); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment