Search in sources :

Example 61 with GCMParameterSpec

use of javax.crypto.spec.GCMParameterSpec in project tink by google.

the class AesGcmJce method encrypt.

@Override
public byte[] encrypt(final byte[] plaintext, final byte[] associatedData) throws GeneralSecurityException {
    // Check that ciphertext is not longer than the max. size of a Java array.
    if (plaintext.length > Integer.MAX_VALUE - IV_SIZE_IN_BYTES - TAG_SIZE_IN_BYTES) {
        throw new GeneralSecurityException("plaintext too long");
    }
    byte[] ciphertext = new byte[IV_SIZE_IN_BYTES + plaintext.length + TAG_SIZE_IN_BYTES];
    byte[] iv = Random.randBytes(IV_SIZE_IN_BYTES);
    System.arraycopy(iv, 0, ciphertext, 0, IV_SIZE_IN_BYTES);
    Cipher cipher = instance();
    GCMParameterSpec params = new GCMParameterSpec(8 * TAG_SIZE_IN_BYTES, iv);
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, params);
    if (associatedData != null && associatedData.length != 0) {
        cipher.updateAAD(associatedData);
    }
    int unusedWritten = cipher.doFinal(plaintext, 0, plaintext.length, ciphertext, IV_SIZE_IN_BYTES);
    return ciphertext;
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) Cipher(javax.crypto.Cipher) GCMParameterSpec(javax.crypto.spec.GCMParameterSpec)

Example 62 with GCMParameterSpec

use of javax.crypto.spec.GCMParameterSpec in project Bytecoder by mirkosertic.

the class CipherBox method createExplicitNonce.

/*
     * Creates the explicit nonce/IV to this cipher. This method is used to
     * encrypt an SSL/TLS output record.
     *
     * The size of the returned array is the SecurityParameters.record_iv_length
     * in RFC 4346/5246.  It is the size of explicit IV for CBC mode, and the
     * size of explicit nonce for AEAD mode.
     *
     * @param  authenticator the authenticator to get the additional
     *         authentication data
     * @param  contentType the content type of the input record
     * @param  fragmentLength the fragment length of the output record, it is
     *         the TLSCompressed.length in RFC 4346/5246.
     *
     * @return the explicit nonce of the cipher.
     */
byte[] createExplicitNonce(Authenticator authenticator, byte contentType, int fragmentLength) {
    byte[] nonce = new byte[0];
    switch(cipherType) {
        case BLOCK_CIPHER:
            if (protocolVersion.useTLS11PlusSpec()) {
                // For block ciphers, the explicit IV length is of length
                // SecurityParameters.record_iv_length, which is equal to
                // the SecurityParameters.block_size.
                // 
                // Generate a random number as the explicit IV parameter.
                nonce = new byte[cipher.getBlockSize()];
                random.nextBytes(nonce);
            }
            break;
        case AEAD_CIPHER:
            // To be unique and aware of overflow-wrap, sequence number
            // is used as the nonce_explicit of AEAD cipher suites.
            nonce = authenticator.sequenceNumber();
            // initialize the AEAD cipher for the unique IV
            byte[] iv = Arrays.copyOf(fixedIv, fixedIv.length + nonce.length);
            System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length);
            GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv);
            try {
                cipher.init(mode, key, spec, random);
            } catch (InvalidKeyException | InvalidAlgorithmParameterException ikae) {
                // unlikely to happen
                throw new RuntimeException("invalid key or spec in GCM mode", ikae);
            }
            // Update the additional authentication data, using the
            // implicit sequence number of the authenticator.
            byte[] aad = authenticator.acquireAuthenticationBytes(contentType, fragmentLength, null);
            cipher.updateAAD(aad);
            break;
    }
    return nonce;
}
Also used : GCMParameterSpec(javax.crypto.spec.GCMParameterSpec)

Example 63 with GCMParameterSpec

use of javax.crypto.spec.GCMParameterSpec in project pwm by pwm-project.

the class SecureEngine method encryptToBytes.

public static byte[] encryptToBytes(final String value, final PwmSecurityKey key, final PwmBlockAlgorithm blockAlgorithm) throws PwmUnrecoverableException {
    try {
        if (value == null || value.length() < 1) {
            return null;
        }
        final SecretKey aesKey = key.getKey(blockAlgorithm.getBlockKey());
        final byte[] nonce;
        final Cipher cipher;
        if (blockAlgorithm == PwmBlockAlgorithm.AES128_GCM) {
            nonce = AES_GCM_NONCE_GENERATOR.nextValue();
            final GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
            cipher = Cipher.getInstance(blockAlgorithm.getAlgName());
            cipher.init(Cipher.ENCRYPT_MODE, aesKey, spec);
        } else {
            cipher = Cipher.getInstance(blockAlgorithm.getAlgName());
            cipher.init(Cipher.ENCRYPT_MODE, aesKey, cipher.getParameters());
            nonce = null;
        }
        final byte[] encryptedBytes = cipher.doFinal(value.getBytes(PwmConstants.DEFAULT_CHARSET));
        final byte[] output;
        if (blockAlgorithm.getHmacAlgorithm() != null) {
            final byte[] hashChecksum = computeHmacToBytes(blockAlgorithm.getHmacAlgorithm(), key, encryptedBytes);
            output = appendByteArrays(blockAlgorithm.getPrefix(), hashChecksum, encryptedBytes);
        } else {
            if (nonce == null) {
                output = appendByteArrays(blockAlgorithm.getPrefix(), encryptedBytes);
            } else {
                final byte[] nonceLength = new byte[1];
                nonceLength[0] = (byte) nonce.length;
                output = appendByteArrays(blockAlgorithm.getPrefix(), nonceLength, nonce, encryptedBytes);
            }
        }
        return output;
    } catch (Exception e) {
        final String errorMsg = "unexpected error performing simple crypt operation: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, errorMsg);
        LOGGER.error(errorInformation.toDebugStr());
        throw new PwmUnrecoverableException(errorInformation);
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) SecretKey(javax.crypto.SecretKey) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) Cipher(javax.crypto.Cipher) GCMParameterSpec(javax.crypto.spec.GCMParameterSpec) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 64 with GCMParameterSpec

use of javax.crypto.spec.GCMParameterSpec in project pwm by pwm-project.

the class SecureEngine method decryptBytes.

public static String decryptBytes(final byte[] value, final PwmSecurityKey key, final PwmBlockAlgorithm blockAlgorithm) throws PwmUnrecoverableException {
    try {
        if (value == null || value.length < 1) {
            return null;
        }
        byte[] workingValue = verifyAndStripPrefix(blockAlgorithm, value);
        final SecretKey aesKey = key.getKey(blockAlgorithm.getBlockKey());
        if (blockAlgorithm.getHmacAlgorithm() != null) {
            final HmacAlgorithm hmacAlgorithm = blockAlgorithm.getHmacAlgorithm();
            final int checksumSize = hmacAlgorithm.getLength();
            if (workingValue.length <= checksumSize) {
                throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, "incoming " + blockAlgorithm.toString() + " data is missing checksum"));
            }
            final byte[] inputChecksum = Arrays.copyOfRange(workingValue, 0, checksumSize);
            final byte[] inputPayload = Arrays.copyOfRange(workingValue, checksumSize, workingValue.length);
            final byte[] computedChecksum = computeHmacToBytes(hmacAlgorithm, key, inputPayload);
            if (!Arrays.equals(inputChecksum, computedChecksum)) {
                throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, "incoming " + blockAlgorithm.toString() + " data has incorrect checksum"));
            }
            workingValue = inputPayload;
        }
        final Cipher cipher;
        if (blockAlgorithm == PwmBlockAlgorithm.AES128_GCM) {
            final int nonceLength = workingValue[0];
            workingValue = Arrays.copyOfRange(workingValue, 1, workingValue.length);
            if (workingValue.length <= nonceLength) {
                throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, "incoming " + blockAlgorithm.toString() + " data is missing nonce"));
            }
            final byte[] nonce = Arrays.copyOfRange(workingValue, 0, nonceLength);
            workingValue = Arrays.copyOfRange(workingValue, nonceLength, workingValue.length);
            final GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
            cipher = Cipher.getInstance(blockAlgorithm.getAlgName());
            cipher.init(Cipher.DECRYPT_MODE, aesKey, spec);
        } else {
            cipher = Cipher.getInstance(blockAlgorithm.getAlgName());
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
        }
        final byte[] decrypted = cipher.doFinal(workingValue);
        return new String(decrypted, PwmConstants.DEFAULT_CHARSET);
    } catch (GeneralSecurityException e) {
        final String errorMsg = "unexpected error performing simple decrypt operation: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, errorMsg);
        throw new PwmUnrecoverableException(errorInformation);
    }
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) SecretKey(javax.crypto.SecretKey) GeneralSecurityException(java.security.GeneralSecurityException) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) Cipher(javax.crypto.Cipher) GCMParameterSpec(javax.crypto.spec.GCMParameterSpec)

Example 65 with GCMParameterSpec

use of javax.crypto.spec.GCMParameterSpec in project toshi-android-client by toshiapp.

the class KeystoreHandler23 method decryptCurrentKeystoreVersion.

@NonNull
private String decryptCurrentKeystoreVersion(String encryptedData) throws KeyStoreException {
    try {
        final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), spec);
        final byte[] encryptedBytes = Base64.decode(encryptedData, Base64.DEFAULT);
        final byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, UTF_8);
    } catch (UnrecoverableEntryException | UnsupportedEncodingException | IllegalBlockSizeException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException | java.security.KeyStoreException | BadPaddingException | NoSuchAlgorithmException e) {
        throw new KeyStoreException(new Throwable(e.getMessage()));
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) GCMParameterSpec(javax.crypto.spec.GCMParameterSpec) KeyStoreException(com.toshi.exception.KeyStoreException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) Cipher(javax.crypto.Cipher) NonNull(android.support.annotation.NonNull)

Aggregations

GCMParameterSpec (javax.crypto.spec.GCMParameterSpec)101 Cipher (javax.crypto.Cipher)71 SecretKeySpec (javax.crypto.spec.SecretKeySpec)46 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)35 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)32 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)31 InvalidKeyException (java.security.InvalidKeyException)30 BadPaddingException (javax.crypto.BadPaddingException)29 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)29 SecretKey (javax.crypto.SecretKey)21 GeneralSecurityException (java.security.GeneralSecurityException)12 AEADBadTagException (javax.crypto.AEADBadTagException)12 Key (java.security.Key)11 ByteBuffer (java.nio.ByteBuffer)7 IOException (java.io.IOException)6 Test (org.junit.Test)6 ExcludedTest (com.google.security.wycheproof.WycheproofRunner.ExcludedTest)5 NoPresubmitTest (com.google.security.wycheproof.WycheproofRunner.NoPresubmitTest)5 SlowTest (com.google.security.wycheproof.WycheproofRunner.SlowTest)5 FileNotFoundException (java.io.FileNotFoundException)5