Java Code Examples for javax.crypto.Cipher#getIV()

The following examples show how to use javax.crypto.Cipher#getIV() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeyStoreHelper.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.M)
public static SealedData seal(@NonNull byte[] input) {
  SecretKey secretKey = getOrCreateKeyStoreEntry();

  try {
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    byte[] iv   = cipher.getIV();
    byte[] data = cipher.doFinal(input);

    return new SealedData(iv, data);
  } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
    throw new AssertionError(e);
  }
}
 
Example 2
Source File: AESCrypto.java    From weMessage with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Generates a random IV and encrypts this plain text with the given key. Then attaches
 * a hashed MAC, which is contained in the CipherTextIvMac class.
 *
 * @param plaintext The text that will be encrypted
 * @param secretKeys The combined AES & HMAC keys with which to encrypt
 * @return a tuple of the IV, ciphertext, mac
 * @throws GeneralSecurityException if AES is not implemented on this system
 */
public static CipherTextIvMac encrypt(byte[] plaintext, SecretKeys secretKeys)
        throws GeneralSecurityException {
    byte[] iv = generateIv();
    Cipher aesCipherForEncryption = Cipher.getInstance(CIPHER_TRANSFORMATION);
    aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKeys.getConfidentialityKey(), new IvParameterSpec(iv));

    /*
     * Now we get back the IV that will actually be used. Some Android
     * versions do funny stuff w/ the IV, so this is to work around bugs:
     */
    iv = aesCipherForEncryption.getIV();
    byte[] byteCipherText = aesCipherForEncryption.doFinal(plaintext);
    byte[] ivCipherConcat = CipherTextIvMac.ivCipherConcat(iv, byteCipherText);

    byte[] integrityMac = generateMac(ivCipherConcat, secretKeys.getIntegrityKey());
    return new CipherTextIvMac(byteCipherText, iv, integrityMac);
}
 
Example 3
Source File: ExtendedKey.java    From BlockchainWallet-Crypto with GNU General Public License v3.0 6 votes vote down vote up
public byte[] encrypt(String passphrase, boolean production) throws ValidationException {
    try {
        byte[] key = SCrypt.generate(passphrase.getBytes("UTF-8"), BITCOIN_SEED, 16384, 8, 8,
                32);
        SecretKeySpec keyspec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, keyspec);
        byte[] iv = cipher.getIV();
        byte[] c = cipher.doFinal(serialize(production).getBytes());
        byte[] result = new byte[iv.length + c.length];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(c, 0, result, iv.length, c.length);
        return result;
    } catch (UnsupportedEncodingException | NoSuchAlgorithmException |
            NoSuchProviderException | NoSuchPaddingException | InvalidKeyException
            | IllegalBlockSizeException | BadPaddingException e) {
        throw new ValidationException(e);
    }
}
 
Example 4
Source File: KeyStoreHelper.java    From Hauk with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts the given data.
 *
 * @param data The data to encrypt.
 * @return The encrypted data and IV.
 * @throws EncryptionException if there was an error while encrypting.
 */
private EncryptedData encrypt(byte[] data) throws EncryptionException {
    Log.v("Encrypting data"); //NON-NLS

    // Catch errors during initialization.
    if (this.key == null) throw new EncryptionException(new InvalidKeyException("Encryption key is null"));

    try {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, this.key);
        byte[] iv = cipher.getIV();
        byte[] message = cipher.doFinal(data);
        return new EncryptedData(iv, message);
    } catch (Exception e) {
        throw new EncryptionException(e);
    }
}
 
Example 5
Source File: HookCryptoImpl.java    From Introspy-Android with GNU General Public License v2.0 6 votes vote down vote up
protected void _getIV(Cipher cipher) {
	if (cipher.getIV() != null) {
		String iv = _getReadableByteArr(cipher.getIV());
		_out += "; IV: " + iv;
		_logParameter("IV", iv);

		if (cipher.getIV()[0] == 0) {
			Log.w("Introspy", "!!! IV of 0");
			_warning = true;
		}
		else {
			// check if this IV has already been used
			if (IVList.contains(cipher.getIV())) {
				_out  += " - !!! Static IV";
				_warning = true;
			}
			IVList.push(cipher.getIV());
			// keep a list of a max of 10 IVs
			if (IVList.size() > 10)
				IVList.pop();
		}
	}
}
 
Example 6
Source File: CryptoConverter.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public String convertToDatabaseColumn(String attrValue) {

    if (attrValue == null || attrValue.isEmpty()) {
        return attrValue;
    }

    try {
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, key);
        //retrieves the initialization vector which needs to be stored along the ciphered data
        byte[] iv = c.getIV();
        //the '.' is a safe delimiter for Base64 data
        String base64IV = Base64.getEncoder().encodeToString(iv);
        String base64EncryptedData = Base64.getEncoder().encodeToString(c.doFinal(attrValue.getBytes("UTF-8")));
        return base64IV + "." + base64EncryptedData;
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "Cannot encrypt, stores the value unchanged", ex);
        return attrValue;
    }
}
 
Example 7
Source File: StringUtils.java    From RestServices with Apache License 2.0 6 votes vote down vote up
public static String encryptString(String key, String valueToEncrypt) throws Exception
{
	if (valueToEncrypt == null)
		return null;
	if (key == null)
		throw new MendixRuntimeException("Key should not be empty");
	if (key.length() != 16)
		throw new MendixRuntimeException("Key length should be 16");
	Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
	SecretKeySpec k = new SecretKeySpec(key.getBytes(), "AES");
	c.init(Cipher.ENCRYPT_MODE, k);
	byte[] encryptedData = c.doFinal(valueToEncrypt.getBytes());
	byte[] iv = c.getIV();

	return Base64.getEncoder().encodeToString(iv) + ";" + Base64.getEncoder().encodeToString(encryptedData);
}
 
Example 8
Source File: TestDelegatedKey.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] encrypt(byte[] plainText, byte[] additionalAssociatedData, String algorithm)
        throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException,
        NoSuchPaddingException {
    Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm));
    cipher.init(Cipher.ENCRYPT_MODE, realKey);
    byte[] iv = cipher.getIV();
    byte[] result = new byte[cipher.getOutputSize(plainText.length) + iv.length + 1];
    result[0] = (byte) iv.length;
    System.arraycopy(iv, 0, result, 1, iv.length);
    try {
        cipher.doFinal(plainText, 0, plainText.length, result, iv.length + 1);
    } catch (ShortBufferException e) {
        throw new RuntimeException(e);
    }
    return result;
}
 
Example 9
Source File: TestDelegatedKey.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] encrypt(byte[] plainText, byte[] additionalAssociatedData, String algorithm)
        throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException,
        NoSuchPaddingException {
    Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm));
    cipher.init(Cipher.ENCRYPT_MODE, realKey);
    byte[] iv = cipher.getIV();
    byte[] result = new byte[cipher.getOutputSize(plainText.length) + iv.length + 1];
    result[0] = (byte) iv.length;
    System.arraycopy(iv, 0, result, 1, iv.length);
    try {
        cipher.doFinal(plainText, 0, plainText.length, result, iv.length + 1);
    } catch (ShortBufferException e) {
        throw new RuntimeException(e);
    }
    return result;
}
 
Example 10
Source File: AesCrypto.java    From android-showcase-template with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypt the given text.
 * @param keyAlias The alias of the key in the keystore that will be used for the encryption.
 * @param plainText the text to encrypt
 * @return the encrypted data. The first 12 bytes will be the IV (initial vector) used for the encryption.
 * @throws GeneralSecurityException
 * @throws IOException
 */
public byte[] encrypt(String keyAlias, byte[] plainText) throws GeneralSecurityException, IOException {
    SecretKey secretKey = loadOrGenerateSecretKey(keyAlias, true);
    Cipher cipher = Cipher.getInstance(secureKeyStore.getSupportedAESMode());
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    //get the iv that is being used
    byte[] iv = cipher.getIV();
    byte[] encrypted = cipher.doFinal(plainText);
    GCMEncrypted encryptedData = new GCMEncrypted(iv, encrypted);
    return encryptedData.toByteArray();
}
 
Example 11
Source File: AESProvenanceEventEncryptor.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypts the provided {@link ProvenanceEventRecord}, serialized to a byte[] by the RecordWriter.
 *
 * @param plainRecord the plain record, serialized to a byte[]
 * @param recordId    an identifier for this record (eventId, generated, etc.)
 * @param keyId       the ID of the key to use
 * @return the encrypted record
 * @throws EncryptionException if there is an issue encrypting this record
 */
@Override
public byte[] encrypt(byte[] plainRecord, String recordId, String keyId) throws EncryptionException {
    if (plainRecord == null || CryptoUtils.isEmpty(keyId)) {
        throw new EncryptionException("The provenance record and key ID cannot be missing");
    }

    if (keyProvider == null || !keyProvider.keyExists(keyId)) {
        throw new EncryptionException("The requested key ID is not available");
    } else {
        byte[] ivBytes = new byte[IV_LENGTH];
        new SecureRandom().nextBytes(ivBytes);
        try {
            logger.debug("Encrypting provenance record " + recordId + " with key ID " + keyId);
            Cipher cipher = initCipher(EncryptionMethod.AES_GCM, Cipher.ENCRYPT_MODE, keyProvider.getKey(keyId), ivBytes);
            ivBytes = cipher.getIV();

            // Perform the actual encryption
            byte[] cipherBytes = cipher.doFinal(plainRecord);

            // Serialize and concat encryption details fields (keyId, algo, IV, version, CB length) outside of encryption
            EncryptionMetadata metadata = new EncryptionMetadata(keyId, ALGORITHM, ivBytes, VERSION, cipherBytes.length);
            byte[] serializedEncryptionMetadata = serializeEncryptionMetadata(metadata);

            // Add the sentinel byte of 0x01
            logger.debug("Encrypted provenance event record " + recordId + " with key ID " + keyId);
            return CryptoUtils.concatByteArrays(SENTINEL, serializedEncryptionMetadata, cipherBytes);
        } catch (EncryptionException | BadPaddingException | IllegalBlockSizeException | IOException | KeyManagementException e) {
            final String msg = "Encountered an exception encrypting provenance record " + recordId;
            logger.error(msg, e);
            throw new EncryptionException(msg, e);
        }
    }
}
 
Example 12
Source File: RC2AlgorithmParameters.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] testParams(AlgorithmParameters rc2Params,
    RC2ParameterSpec rc2Spec) throws Exception {

    // test getParameterSpec returns object equal to input
    rc2Params.init(rc2Spec);
    RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec)
        rc2Params.getParameterSpec(RC2ParameterSpec.class);
    if (!rc2Spec.equals(rc2OtherSpec)) {
        throw new Exception("AlgorithmParameterSpecs should be equal");
    }

    // test RC2ParameterSpec with RC2 Cipher
    Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);

    // get IV
    byte[] iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }

    // test encoding and decoding
    byte[] encoded = rc2Params.getEncoded();
    AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
    params.init(encoded);

    // test RC2 AlgorithmParameters with RC2 Cipher
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);

    // get IV
    iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }
    return encoded;
}
 
Example 13
Source File: RC2AlgorithmParameters.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] testParams(AlgorithmParameters rc2Params,
    RC2ParameterSpec rc2Spec) throws Exception {

    // test getParameterSpec returns object equal to input
    rc2Params.init(rc2Spec);
    RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec)
        rc2Params.getParameterSpec(RC2ParameterSpec.class);
    if (!rc2Spec.equals(rc2OtherSpec)) {
        throw new Exception("AlgorithmParameterSpecs should be equal");
    }

    // test RC2ParameterSpec with RC2 Cipher
    Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);

    // get IV
    byte[] iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }

    // test encoding and decoding
    byte[] encoded = rc2Params.getEncoded();
    AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
    params.init(encoded);

    // test RC2 AlgorithmParameters with RC2 Cipher
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);

    // get IV
    iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }
    return encoded;
}
 
Example 14
Source File: RC2AlgorithmParameters.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] testParams(AlgorithmParameters rc2Params,
    RC2ParameterSpec rc2Spec) throws Exception {

    // test getParameterSpec returns object equal to input
    rc2Params.init(rc2Spec);
    RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec)
        rc2Params.getParameterSpec(RC2ParameterSpec.class);
    if (!rc2Spec.equals(rc2OtherSpec)) {
        throw new Exception("AlgorithmParameterSpecs should be equal");
    }

    // test RC2ParameterSpec with RC2 Cipher
    Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);

    // get IV
    byte[] iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }

    // test encoding and decoding
    byte[] encoded = rc2Params.getEncoded();
    AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
    params.init(encoded);

    // test RC2 AlgorithmParameters with RC2 Cipher
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);

    // get IV
    iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }
    return encoded;
}
 
Example 15
Source File: RC2AlgorithmParameters.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] testParams(AlgorithmParameters rc2Params,
    RC2ParameterSpec rc2Spec) throws Exception {

    // test getParameterSpec returns object equal to input
    rc2Params.init(rc2Spec);
    RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec)
        rc2Params.getParameterSpec(RC2ParameterSpec.class);
    if (!rc2Spec.equals(rc2OtherSpec)) {
        throw new Exception("AlgorithmParameterSpecs should be equal");
    }

    // test RC2ParameterSpec with RC2 Cipher
    Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);

    // get IV
    byte[] iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }

    // test encoding and decoding
    byte[] encoded = rc2Params.getEncoded();
    AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
    params.init(encoded);

    // test RC2 AlgorithmParameters with RC2 Cipher
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);

    // get IV
    iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }
    return encoded;
}
 
Example 16
Source File: RepositoryObjectAESGCMEncryptor.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypts the serialized byte[].
 *
 * @param plainRecord the plain record, serialized to a byte[]
 * @param recordId    an identifier for this record (eventId, generated, etc.)
 * @param keyId       the ID of the key to use
 * @return the encrypted record
 * @throws EncryptionException if there is an issue encrypting this record
 */
@Override
public byte[] encrypt(byte[] plainRecord, String recordId, String keyId) throws EncryptionException {
    if (plainRecord == null || CryptoUtils.isEmpty(keyId)) {
        throw new EncryptionException("The repository object and key ID cannot be missing");
    }

    if (keyProvider == null || !keyProvider.keyExists(keyId)) {
        throw new EncryptionException("The requested key ID is not available");
    } else {
        byte[] ivBytes = new byte[IV_LENGTH];
        new SecureRandom().nextBytes(ivBytes);
        try {
            // TODO: Add object type to description
            logger.debug("Encrypting repository object " + recordId + " with key ID " + keyId);
            Cipher cipher = RepositoryEncryptorUtils.initCipher(aesKeyedCipherProvider, EncryptionMethod.AES_GCM, Cipher.ENCRYPT_MODE, keyProvider.getKey(keyId), ivBytes);
            ivBytes = cipher.getIV();

            // Perform the actual encryption
            byte[] cipherBytes = cipher.doFinal(plainRecord);

            // Serialize and concat encryption details fields (keyId, algo, IV, version, CB length) outside of encryption
            RepositoryObjectEncryptionMetadata metadata = new BlockEncryptionMetadata(keyId, ALGORITHM, ivBytes, VERSION, cipherBytes.length);
            byte[] serializedEncryptionMetadata = RepositoryEncryptorUtils.serializeEncryptionMetadata(metadata);
            logger.debug("Generated encryption metadata ({} bytes) for repository object {}", serializedEncryptionMetadata.length, recordId);

            // Add the sentinel byte of 0x01
            // TODO: Remove (required for prov repo but not FF repo)
            logger.debug("Encrypted repository object " + recordId + " with key ID " + keyId);
            // return CryptoUtils.concatByteArrays(SENTINEL, serializedEncryptionMetadata, cipherBytes);
            return CryptoUtils.concatByteArrays(serializedEncryptionMetadata, cipherBytes);
        } catch (EncryptionException | BadPaddingException | IllegalBlockSizeException | IOException | KeyManagementException e) {
            final String msg = "Encountered an exception encrypting repository object " + recordId;
            logger.error(msg, e);
            throw new EncryptionException(msg, e);
        }
    }
}
 
Example 17
Source File: RC2AlgorithmParameters.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static byte[] testParams(AlgorithmParameters rc2Params,
    RC2ParameterSpec rc2Spec) throws Exception {

    // test getParameterSpec returns object equal to input
    rc2Params.init(rc2Spec);
    RC2ParameterSpec rc2OtherSpec = (RC2ParameterSpec)
        rc2Params.getParameterSpec(RC2ParameterSpec.class);
    if (!rc2Spec.equals(rc2OtherSpec)) {
        throw new Exception("AlgorithmParameterSpecs should be equal");
    }

    // test RC2ParameterSpec with RC2 Cipher
    Cipher rc2Cipher = Cipher.getInstance("RC2/CBC/PKCS5PADDING", "SunJCE");
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), rc2Spec);

    // get IV
    byte[] iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }

    // test encoding and decoding
    byte[] encoded = rc2Params.getEncoded();
    AlgorithmParameters params = AlgorithmParameters.getInstance("RC2");
    params.init(encoded);

    // test RC2 AlgorithmParameters with RC2 Cipher
    rc2Cipher.init(Cipher.ENCRYPT_MODE,
        new SecretKeySpec("secret".getBytes("ASCII"), "RC2"), params);

    // get IV
    iv = rc2Cipher.getIV();
    if (!Arrays.equals(iv, rc2Spec.getIV())) {
        throw new Exception("ivs should be equal");
    }
    return encoded;
}
 
Example 18
Source File: TempOutputStream.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private BufferedOutputStream createOutputStream(File file) throws IOException
{
    BufferedOutputStream fileOutputStream;
    if (encrypt)
    {
        try
        {
            // Generate a symmetric key
            final KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
            keyGen.init(KEY_SIZE);
            symKey = keyGen.generateKey();

            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, symKey);

            iv = cipher.getIV();

            fileOutputStream = new BufferedOutputStream(new CipherOutputStream(new FileOutputStream(file), cipher));
        }
        catch (Exception e)
        {
            if (logger.isErrorEnabled())
            {
                logger.error("Cannot initialize encryption cipher", e);
            }

            throw new IOException("Cannot initialize encryption cipher", e);
        }
    }
    else
    {
        fileOutputStream = new BufferedOutputStream(new FileOutputStream(file));
    }

    return fileOutputStream;
}
 
Example 19
Source File: Common.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
     * Function to make a key-handle for transporting to the FIDO U2F server
     *
     * @param pvk PrivateKey of the ECDSA key-pair
     * @param originHash String Message digest of the origin for which this
     * private-key is valid
     * @return String Base64-encoded key-handle
     *
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws NoSuchPaddingException
     * @throws FileNotFoundException
     * @throws DecoderException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws InvalidAlgorithmParameterException
     * @throws ShortBufferException
     * @throws InvalidKeySpecException
     * @throws SignatureException
     * @throws java.security.spec.InvalidParameterSpecException
     */
    public static String makeKeyHandle(PrivateKey pvk, String originHash)
            throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, FileNotFoundException, DecoderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException, ShortBufferException, InvalidKeySpecException, SignatureException, InvalidParameterSpecException {
        // Get wrapping key
        byte[] Seckeybytes = Hex.decodeHex(Constants.FIXED_AES256_WRAPPING_KEY.toCharArray());
        SecretKeySpec sks = new SecretKeySpec(Seckeybytes, "AES");
        ECPrivateKey ecpk = (ECPrivateKey) pvk;
        byte[] s = org.bouncycastle.util.encoders.Hex.decode(String.format("%064x", ecpk.getS()));

        // Encode plaintext key-handle into JSON structure
        String ptkh = encodeKeyHandle(Base64.getUrlEncoder().encodeToString(s), originHash, getDigest(pvk.getEncoded(), "SHA1"));
//        System.out.println("PlaintextKeyHandle:     " + ptkh);

        // Encrypt key handle to create ciphertext
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BCFIPS");
        cipher.init(Cipher.ENCRYPT_MODE, sks, new SecureRandom());
        byte[] ctkh = cipher.doFinal(ptkh.getBytes("UTF-8"));

        // Recover IV from cipher and prepend to encrypted keyhandle in new array
        byte[] iv = cipher.getIV();
        byte[] ctkhiv = new byte[ctkh.length + Constants.ENCRYPTION_MODE_CBC_IV_LENGTH];
        System.arraycopy(iv, 0, ctkhiv, 0, Constants.ENCRYPTION_MODE_CBC_IV_LENGTH);              // Copy IV to new array
        System.arraycopy(ctkh, 0, ctkhiv, Constants.ENCRYPTION_MODE_CBC_IV_LENGTH, ctkh.length);  // Append ciphertext KH to IV

        // Base64-encode ciphertext keyhandle + IV
        String ctkhivb64 = Base64.getUrlEncoder().encodeToString(ctkhiv);

        // Test recovery of plaintext key-handle before returning
        //String ptkh2 = decryptKeyHandle(ctkhivb64);
        //if (!ptkh2.trim().equalsIgnoreCase(ptkh.trim())) {
        //    System.err.println("Decryption of keyhandle failed during test");
        //    return null;
        //}
        // Decryption succeeded - return Base64-encoded, encrypted keyhandle + IV
        return ctkhivb64;
    }
 
Example 20
Source File: DynamoDbEncryptor.java    From aws-dynamodb-encryption-java with Apache License 2.0 4 votes vote down vote up
/**
 * This method has the side effect of replacing the plaintext
 * attribute-values of "itemAttributes" with ciphertext attribute-values
 * (which are always in the form of ByteBuffer) as per the corresponding
 * attribute flags.
 */
private void actualEncryption(Map<String, AttributeValue> itemAttributes,
        Map<String, Set<EncryptionFlags>> attributeFlags,
        Map<String, String> materialDescription,
        SecretKey encryptionKey) throws GeneralSecurityException {
    String encryptionMode = null;
    if (encryptionKey != null) {
        materialDescription.put(this.symmetricEncryptionModeHeader,
                SYMMETRIC_ENCRYPTION_MODE);
        encryptionMode = encryptionKey.getAlgorithm() + SYMMETRIC_ENCRYPTION_MODE;
    }
    Cipher cipher = null;
    int blockSize = -1;

    for (Map.Entry<String, AttributeValue> entry: itemAttributes.entrySet()) {
        Set<EncryptionFlags> flags = attributeFlags.get(entry.getKey());
        if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) {
            if (!flags.contains(EncryptionFlags.SIGN)) {
                throw new IllegalArgumentException("All encrypted fields must be signed. Bad field: " + entry.getKey());
            }
            ByteBuffer plainText = AttributeValueMarshaller.marshall(entry.getValue());
            plainText.rewind();
            ByteBuffer cipherText;
            if (encryptionKey instanceof DelegatedKey) {
                DelegatedKey dk = (DelegatedKey) encryptionKey;
                cipherText = ByteBuffer.wrap(
                        dk.encrypt(toByteArray(plainText), null, encryptionMode));
            } else {
                if (cipher == null) {
                    blockSize = getBlockSize(encryptionMode);
                    cipher = Cipher.getInstance(encryptionMode);
                }
                // Encryption format: <iv><ciphertext>
                // Note a unique iv is generated per attribute
                cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, Utils.getRng());
                cipherText = ByteBuffer.allocate(blockSize + cipher.getOutputSize(plainText.remaining()));
                cipherText.position(blockSize);
                cipher.doFinal(plainText, cipherText);
                cipherText.flip();
                final byte[] iv = cipher.getIV();
                if (iv.length != blockSize) {
                    throw new IllegalStateException(String.format("Generated IV length (%d) not equal to block size (%d)",
                            iv.length, blockSize));
                }
                cipherText.put(iv);
                cipherText.rewind();
            }
            // Replace the plaintext attribute value with the encrypted content
            entry.setValue(AttributeValue.builder().b(SdkBytes.fromByteBuffer(cipherText)).build());
        }
    }
}