Example usage for javax.crypto.spec GCMParameterSpec GCMParameterSpec

List of usage examples for javax.crypto.spec GCMParameterSpec GCMParameterSpec

Introduction

In this page you can find the example usage for javax.crypto.spec GCMParameterSpec GCMParameterSpec.

Prototype

public GCMParameterSpec(int tLen, byte[] src, int offset, int len) 

Source Link

Document

Constructs a GCMParameterSpec object using the specified authentication tag bit-length and a subset of the specified buffer as the IV.

Usage

From source file:com.demandware.appsec.csrf.StatelessCSRFTokenManager.java

/**
 * encrypts or decrypts using AES/GCM and the given values
 *
 * @param key the key to use with *crypting
 * @param iv the iv to use when *crypting
 * @param textBytes the encrypted value to be decrypted OR the plaintext to be encrypted
 * @param mode either {@link Cipher#ENCRYPT_MODE} or {@link Cipher#DECRYPT_MODE}
 * @return the encrypted or decrypted value, depending on the given mode
 * @throws NoSuchAlgorithmException if the underlying code throws this exception
 * @throws NoSuchPaddingException if the underlying code throws this exception
 * @throws InvalidKeyException if the underlying code throws this exception
 * @throws InvalidAlgorithmParameterException if the underlying code throws this exception
 * @throws IllegalBlockSizeException if the underlying code throws this exception
 * @throws BadPaddingException if the underlying code throws this exception
 * @throws UnsupportedEncodingException if the underlying code throws this exception
 *//*from  w  w  w . j a  v a 2  s .  c o m*/
private byte[] crypt(byte[] key, byte[] iv, byte[] textBytes, int mode) throws NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    byte[] cryptedValue = null;
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    SecretKeySpec keyspec = new SecretKeySpec(key, 0, KEY_SIZE, "AES");
    GCMParameterSpec gcmspec = new GCMParameterSpec(GCM_TAG_BITS, iv, 0, PARAMETER_SPEC_SIZE);
    cipher.init(mode, keyspec, gcmspec);
    cryptedValue = cipher.doFinal(textBytes);
    return cryptedValue;
}