Example usage for org.bouncycastle.crypto.modes GCMBlockCipher getOutputSize

List of usage examples for org.bouncycastle.crypto.modes GCMBlockCipher getOutputSize

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.modes GCMBlockCipher getOutputSize.

Prototype

public int getOutputSize(int len) 

Source Link

Usage

From source file:dbn.crypto.Crypto.java

public static byte[] aesGCMEncrypt(byte[] plaintext, byte[] key) {
    try {/*from   w  ww .  j  a  v a2 s.  c  o  m*/
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        GCMBlockCipher aes = new GCMBlockCipher(new AESEngine());
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:dbn.crypto.Crypto.java

public static byte[] aesGCMDecrypt(byte[] ivCiphertext, byte[] key) {
    try {//from  w  w  w . jav  a2  s .c o m
        if (ivCiphertext.length < 16) {
            throw new InvalidCipherTextException("invalid ivCiphertext length");
        }
        byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length);
        GCMBlockCipher aes = new GCMBlockCipher(new AESEngine());
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(false, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(ciphertext.length)];
        int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0);
        plaintextLength += aes.doFinal(output, plaintextLength);
        byte[] result = new byte[plaintextLength];
        System.arraycopy(output, 0, result, 0, result.length);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:dorkbox.util.crypto.CryptoAES.java

License:Apache License

/**
 * AES encrypts data with a specified key.
 *
 * @param logger//  www.jav a 2s.c o m
 *                 may be null, if no log output is necessary
 *
 * @return length of encrypted data, -1 if there was an error.
 */
public static byte[] encrypt(GCMBlockCipher aesEngine, CipherParameters aesIVAndKey, byte[] data, int length,
        Logger logger) {

    aesEngine.reset();
    aesEngine.init(true, aesIVAndKey);

    int minSize = aesEngine.getOutputSize(length);
    byte[] outArray = new byte[minSize];

    int actualLength = aesEngine.processBytes(data, 0, length, outArray, 0);

    try {
        actualLength += aesEngine.doFinal(outArray, actualLength);
    } catch (Exception e) {
        if (logger != null) {
            logger.error("Unable to perform AES cipher.", e);
        }
        return new byte[0];
    }

    if (outArray.length == actualLength) {
        return outArray;
    } else {
        byte[] result = new byte[actualLength];
        System.arraycopy(outArray, 0, result, 0, result.length);
        return result;
    }
}

From source file:dorkbox.util.crypto.CryptoAES.java

License:Apache License

/**
 * AES decrypt (if we already know the aes IV -- and it's NOT included in the data)
 *
 * @param aesIV//from  w  ww.  j a  v a 2  s.  c o  m
 *                 must be a nonce (unique value) !!
 * @param logger
 *                 may be null, if no log output is necessary
 *
 * @return empty byte[] if error
 */
public static byte[] decrypt(GCMBlockCipher aesEngine, byte[] aesKey, byte[] aesIV, byte[] data,
        Logger logger) {
    int length = data.length;

    CipherParameters aesIVAndKey = new ParametersWithIV(new KeyParameter(aesKey), aesIV);
    aesEngine.reset();
    aesEngine.init(false, aesIVAndKey);

    int minSize = aesEngine.getOutputSize(length);
    byte[] outBuf = new byte[minSize];

    int actualLength = aesEngine.processBytes(data, 0, length, outBuf, 0);

    try {
        actualLength += aesEngine.doFinal(outBuf, actualLength);
    } catch (Exception e) {
        if (logger != null) {
            logger.debug("Unable to perform AES cipher.", e);
        }
        return new byte[0];
    }
    if (outBuf.length == actualLength) {
        return outBuf;
    } else {
        byte[] result = new byte[actualLength];
        System.arraycopy(outBuf, 0, result, 0, result.length);
        return result;
    }
}

From source file:dorkbox.util.crypto.PerformanceTest.java

License:Apache License

PerformanceTest(boolean isWarmup) {
    final byte[] bytes = new byte[64 * 1024];
    byte[] encrypted = null;
    final byte[] aesKey = new byte[32];
    final byte[] aesIV = new byte[12];

    final Random random = new SecureRandom(entropySeed.getBytes());
    random.nextBytes(bytes);//  w  w  w .jav a 2  s . com
    random.nextBytes(aesKey);
    random.nextBytes(aesIV);

    int length = bytes.length;

    if (!isWarmup) {
        System.out.println("Benchmarking AES-256 GCM encryption");
    }

    long javaEncryptInputBytes = 0;
    long javaEncryptStartTime = System.currentTimeMillis();

    // convert to bouncycastle
    GCMBlockCipher aesEngine = new GCMBlockCipher(new AESFastEngine());
    CipherParameters aesIVAndKey = new ParametersWithIV(new KeyParameter(aesKey), aesIV);

    long encryptInitTime = 0L;
    long encryptUpdate1Time = 0L;
    long encryptDoFinalTime = 0L;

    while (System.currentTimeMillis() - javaEncryptStartTime < 10000) {
        random.nextBytes(aesIV);

        long n1 = System.nanoTime();

        aesEngine.reset();
        aesEngine.init(true, aesIVAndKey);

        if (encrypted == null) {
            int minSize = aesEngine.getOutputSize(length);
            encrypted = new byte[minSize];
        }

        long n2 = System.nanoTime();
        int actualLength = aesEngine.processBytes(bytes, 0, length, encrypted, 0);

        long n3 = System.nanoTime();
        try {
            actualLength += aesEngine.doFinal(encrypted, actualLength);
        } catch (Exception e) {
            logger.error("Unable to perform AES cipher.", e);
        }

        if (encrypted.length != actualLength) {
            byte[] result = new byte[actualLength];
            System.arraycopy(encrypted, 0, result, 0, result.length);
            encrypted = result;
        }

        long n4 = System.nanoTime();

        javaEncryptInputBytes += actualLength;

        encryptInitTime = n2 - n1;
        encryptUpdate1Time = n3 - n2;
        encryptDoFinalTime = n4 - n3;
    }

    long javaEncryptEndTime = System.currentTimeMillis();

    if (!isWarmup) {
        System.out.println("Time init (ns): " + encryptInitTime);
        System.out.println("Time update (ns): " + encryptUpdate1Time);
        System.out.println("Time do final (ns): " + encryptDoFinalTime);
        System.out.println("Java calculated at "
                + (javaEncryptInputBytes / 1024 / 1024 / ((javaEncryptEndTime - javaEncryptStartTime) / 1000))
                + " MB/s");

        System.out.println("Benchmarking AES-256 GCM decryption");
    }

    long javaDecryptInputBytes = 0;
    long javaDecryptStartTime = System.currentTimeMillis();

    length = encrypted.length;

    long decryptInitTime = 0L;
    long decryptUpdate1Time = 0L;
    long decryptDoFinalTime = 0L;

    while (System.currentTimeMillis() - javaDecryptStartTime < 10000) {
        long n1 = System.nanoTime();

        aesEngine.reset();
        aesEngine.init(false, aesIVAndKey);

        long n2 = System.nanoTime();

        int actualLength = aesEngine.processBytes(encrypted, 0, length, bytes, 0);

        long n3 = System.nanoTime();

        try {
            actualLength += aesEngine.doFinal(bytes, actualLength);
        } catch (Exception e) {
            logger.debug("Unable to perform AES cipher.", e);
        }

        long n4 = System.nanoTime();

        javaDecryptInputBytes += actualLength;

        decryptInitTime += n2 - n1;
        decryptUpdate1Time += n3 - n2;
        decryptDoFinalTime += n4 - n3;
    }
    long javaDecryptEndTime = System.currentTimeMillis();

    if (!isWarmup) {
        System.out.println("Time init (ns): " + decryptInitTime);
        System.out.println("Time update 1 (ns): " + decryptUpdate1Time);
        System.out.println("Time do final (ns): " + decryptDoFinalTime);
        System.out.println("Total bytes processed: " + javaDecryptInputBytes);
        System.out.println("Java calculated at "
                + (javaDecryptInputBytes / 1024 / 1024 / ((javaDecryptEndTime - javaDecryptStartTime) / 1000))
                + " MB/s");
    }
}

From source file:org.openmuc.jdlms.internal.security.CipheringGcm.java

License:Open Source License

public static byte[] encrypt(byte[] plaintext, int off, int len, byte[] systemTitle, int frameCounter,
        byte[] encryptionKey, byte[] authenticationKey, byte tag) throws IOException {

    byte[] frameCounterBytes = intToByteArray(frameCounter);

    byte[] iv = concat(systemTitle, frameCounterBytes);

    byte[] associatedData = new byte[authenticationKey.length + 1];
    associatedData[0] = SECURITY_CONTROL_BYTES_AUTH_CIPH;
    System.arraycopy(authenticationKey, 0, associatedData, 1, authenticationKey.length);

    AEADParameters parameters = new AEADParameters(new KeyParameter(encryptionKey), 96, iv, associatedData);

    GCMBlockCipher encCipher = new GCMBlockCipher(new AESFastEngine(), new BasicGCMMultiplier());
    encCipher.init(true, parameters);/*from  w w  w . j  a v a  2 s. c om*/

    byte[] enc = new byte[encCipher.getOutputSize(len)];
    int length = encCipher.processBytes(plaintext, off, len, enc, 0);
    try {
        length += encCipher.doFinal(enc, length);
    } catch (IllegalStateException e) {
        throw new IOException("Unable to cipher/encrypt xDLMS pdu", e);
    } catch (InvalidCipherTextException e) {
        throw new IOException("Unable to cipher/encrypt xDLMS pdu", e);
    }

    byte[] result = new byte[enc.length + 7];
    result[0] = tag;
    result[1] = (byte) (enc.length + 5);
    result[2] = SECURITY_CONTROL_BYTES_AUTH_CIPH;
    System.arraycopy(frameCounterBytes, 0, result, 3, 4);
    System.arraycopy(enc, 0, result, 7, enc.length);

    return result;
}

From source file:org.openmuc.jdlms.internal.security.CipheringGcm.java

License:Open Source License

public static byte[] decrypt(byte[] ciphertext, byte[] systemTitle, byte[] encryptionKey,
        byte[] authenticationKey) throws IOException {

    byte[] iv = new byte[12];
    System.arraycopy(systemTitle, 0, iv, 0, systemTitle.length);
    // copy frame counter
    System.arraycopy(ciphertext, 1, iv, 8, 4);

    byte[] associatedData = new byte[authenticationKey.length + 1];
    associatedData[0] = SECURITY_CONTROL_BYTES_AUTH_CIPH;
    System.arraycopy(authenticationKey, 0, associatedData, 1, authenticationKey.length);

    AEADParameters parameters = new AEADParameters(new KeyParameter(encryptionKey), 96, iv, associatedData);

    GCMBlockCipher decCipher = new GCMBlockCipher(new AESFastEngine(), new BasicGCMMultiplier());
    decCipher.init(false, parameters);//from   w w  w  .  ja  v  a2  s .c  o m

    byte[] dec = new byte[decCipher.getOutputSize(ciphertext.length - 5)];
    int len = decCipher.processBytes(ciphertext, 5, ciphertext.length - 5, dec, 0);
    try {
        len += decCipher.doFinal(dec, len);
    } catch (IllegalStateException e) {
        throw new IOException("Unable to decipher/decrypt xDLMS pdu", e);
    } catch (InvalidCipherTextException e) {
        throw new IOException("Unable to decipher/decrypt xDLMS pdu", e);
    }

    return dec;
}

From source file:org.panbox.core.crypto.io.AESGCMRandomAccessFileCompat.java

License:Open Source License

@Override
protected byte[] _readChunk(long index) throws IOException, FileEncryptionException, FileIntegrityException {
    // first, get chunk iv for decryption
    long oldpos = backingRandomAccessFile.getFilePointer();
    backingRandomAccessFile.seek(chunkOffset(index));

    // read iv/*from   w  w w  .j a v  a2  s . c  om*/
    byte[] iv = new byte[CHUNK_IV_SIZE];
    int ret = backingRandomAccessFile.read(iv);
    if (ret != CHUNK_IV_SIZE) {
        throw new FileEncryptionException("Size mismatch reading chunk IV!");
    }

    // prepare params for GCM decryption
    // retrieve key bytes from SecretKey
    byte[] key = getFileKeyBytes();
    if ((key == null) || (key.length != KeyConstants.SYMMETRIC_FILE_KEY_SIZE_BYTES)) {
        throw new FileEncryptionException("Invalid encryption key format!");
    }

    // prepare additional authenticated data (index and lastchunkflag as
    // bytes) for verifying metadata integrity
    // byte[] indexAsBytes = IntByteConv.int2byte(index);
    byte[] indexAsBytes = LongByteConv.long2Bytes(index);
    byte[] lastchunkflagAsBytes = BooleanByteConv.bool2byte(false);

    if ((indexAsBytes == null) || (lastchunkflagAsBytes == null) || (indexAsBytes.length == 0)
            || (lastchunkflagAsBytes.length == 0)) {
        throw new FileEncryptionException("Invalid additional autenticated data!");
    }

    byte[] associatedText = new byte[indexAsBytes.length + lastchunkflagAsBytes.length];
    System.arraycopy(indexAsBytes, 0, associatedText, 0, indexAsBytes.length);
    System.arraycopy(lastchunkflagAsBytes, 0, associatedText, indexAsBytes.length, lastchunkflagAsBytes.length);

    AEADParameters gcmParams = new AEADParameters(new KeyParameter(key), GCM_AUTHENTICATION_TAG_LEN, iv,
            associatedText);

    GCMBlockCipher gcmEngine = new GCMBlockCipher(new AESFastEngine());
    gcmEngine.init(false, gcmParams);

    byte[] decMsg = new byte[gcmEngine.getOutputSize(CHUNK_ENC_DATA_SIZE)];
    byte[] encMsg = new byte[CHUNK_ENC_DATA_SIZE];

    ret = backingRandomAccessFile.read(encMsg);
    backingRandomAccessFile.seek(oldpos);

    if (ret != CHUNK_ENC_DATA_SIZE) {
        throw new FileEncryptionException("Size mismatch reading encrypted chunk data!");
    }

    int decLen = gcmEngine.processBytes(encMsg, 0, encMsg.length, decMsg, 0);
    try {
        decLen += gcmEngine.doFinal(decMsg, decLen);
    } catch (IllegalStateException | InvalidCipherTextException e) {
        if ((e instanceof InvalidCipherTextException) && (e.getMessage().contains("mac check in GCM failed"))) {
            throw new FileIntegrityException(
                    "Decryption error in chunk " + index + ". Possible file integrity violation.", e);
        } else {
            throw new FileEncryptionException("Decryption error in chunk " + index + ": " + e.getMessage(), e);
        }
    }

    if ((decMsg == null) || (decMsg.length != CHUNK_DATA_SIZE)) {
        throw new FileEncryptionException("Decryption error or chunk size mismatch during decryption!");
    } else {
        if (implementsAuthentication()) {
            // check authentication tag for integrity
            byte[] tag = Arrays.copyOfRange(encMsg, decMsg.length, encMsg.length);
            if (!getAuthTagVerifier().verifyChunkAuthTag((int) index, tag)) {
                throw new FileIntegrityException(
                        "File authentication tag verification failed in chunk " + index);
            }
        }
        return decMsg;
    }
}

From source file:org.picketlink.json.jose.crypto.AESGCM.java

License:Open Source License

/**
 * Encrypts the specified plain text using AES/GCM/NoPadding.
 *
 * @param secretKey The AES key. Must not be {@code null}.
 * @param plainText The plain text. Must not be {@code null}.
 * @param iv The initialization vector (IV). Must not be {@code null}.
 * @param authData The authenticated data. Must not be {@code null}.
 *
 * @return The authenticated cipher text.
 *
 * @throws RuntimeException If encryption failed.
 *//*w  w w  .  j  ava 2s  .  c o m*/
public static AuthenticatedCipherText encrypt(final SecretKey secretKey, final byte[] iv,
        final byte[] plainText, final byte[] authData) {

    // Initialise AES/GCM cipher for encryption
    GCMBlockCipher cipher = createAESGCMCipher(secretKey, true, iv, authData);

    // Prepare output buffer
    int outputLength = cipher.getOutputSize(plainText.length);
    byte[] output = new byte[outputLength];

    // Produce cipher text
    int outputOffset = cipher.processBytes(plainText, 0, plainText.length, output, 0);

    // Produce authentication tag
    try {
        outputOffset += cipher.doFinal(output, outputOffset);
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException("Couldn't generate GCM authentication tag: " + e.getMessage(), e);
    }

    // Split output into cipher text and authentication tag
    int authTagLength = AUTH_TAG_BIT_LENGTH / 8;

    byte[] cipherText = new byte[outputOffset - authTagLength];
    byte[] authTag = new byte[authTagLength];

    System.arraycopy(output, 0, cipherText, 0, cipherText.length);
    System.arraycopy(output, outputOffset - authTagLength, authTag, 0, authTag.length);

    return new AuthenticatedCipherText(cipherText, authTag);
}

From source file:org.picketlink.json.jose.crypto.AESGCM.java

License:Open Source License

/**
 * Decrypts the specified cipher text using AES/GCM/NoPadding.
 *
 * @param secretKey The AES key. Must not be {@code null}.
 * @param iv The initialisation vector (IV). Must not be {@code null}.
 * @param cipherText The cipher text. Must not be {@code null}.
 * @param authData The authenticated data. Must not be {@code null}.
 * @param authTag The authentication tag. Must not be {@code null}.
 *
 * @return The decrypted plain text./*from   w  ww .ja va 2s.c  om*/
 *
 * @throws RuntimeException If decryption failed.
 */
public static byte[] decrypt(final SecretKey secretKey, final byte[] iv, final byte[] cipherText,
        final byte[] authData, final byte[] authTag) {

    // Initialise AES/GCM cipher for decryption
    GCMBlockCipher cipher = createAESGCMCipher(secretKey, false, iv, authData);

    // Join cipher text and authentication tag to produce cipher input
    byte[] input = new byte[cipherText.length + authTag.length];

    System.arraycopy(cipherText, 0, input, 0, cipherText.length);
    System.arraycopy(authTag, 0, input, cipherText.length, authTag.length);

    int outputLength = cipher.getOutputSize(input.length);

    byte[] output = new byte[outputLength];

    // Decrypt
    int outputOffset = cipher.processBytes(input, 0, input.length, output, 0);

    // Validate authentication tag
    try {
        outputOffset += cipher.doFinal(output, outputOffset);
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException("Couldn't validate GCM authentication tag: " + e.getMessage(), e);
    }
    return output;
}