/** * Returns the initialization vector (IV) in a new buffer. * * <p>This is useful in the case where a random IV was created, * or in the context of password-based encryption or * decryption, where the IV is derived from a user-supplied password. * * @return the initialization vector in a new buffer, or null if the * underlying algorithm does not use an IV, or if the IV has not yet * been set. */ final byte[] getIV() { return cipher.getIV(); }
private void initCipher() { if (origStream == null) { throw new IllegalStateException("Can't initCipher stream before encodeOutputStream() has been called!"); } try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey.getSecretKey()); byte[] iv = cipher.getIV(); base64Iv = DatatypeConverter.printBase64Binary(iv); this.headerWritten = false; } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { throw new IllegalStateException("Error creating AES algorithm? Should always exist in JRE"); } catch (InvalidKeyException e) { throw new IllegalStateException("Key " + secretKey.getKeyId() + " is illegal - please check credential store"); } }
/** * Recreates a new instance of CipherLite from the current one. */ CipherLite recreate() { return scheme.createCipherLite(secreteKey, cipher.getIV(), this.cipherMode, cipher.getProvider(), true); }
/** * Returns the inverse of the current {@link CipherLite}. */ CipherLite createInverse() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException { int inversedMode; if (cipherMode == Cipher.DECRYPT_MODE) inversedMode = Cipher.ENCRYPT_MODE; else if (cipherMode == Cipher.ENCRYPT_MODE) inversedMode = Cipher.DECRYPT_MODE; else throw new UnsupportedOperationException(); return scheme.createCipherLite(secreteKey, cipher.getIV(), inversedMode, cipher.getProvider(), true); }
private byte[] getCiphertext(byte[] plaintext, SecretKeySpec cipherKey, SecretKeySpec macKey) throws CryptoEncodingException { try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, cipherKey); Mac hmac = Mac.getInstance("HmacSHA256"); hmac.init(macKey); hmac.update(VERSION); byte[] ivBytes = cipher.getIV(); hmac.update(ivBytes); byte[] ciphertext = cipher.doFinal(plaintext); byte[] mac = hmac.doFinal(ciphertext); byte[] truncatedMac = new byte[MAC_SIZE]; System.arraycopy(mac, 0, truncatedMac, 0, truncatedMac.length); return Util.combine(VERSION, ivBytes, ciphertext, truncatedMac); } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { throw new AssertionError(e); } catch (InvalidKeyException e) { logger.warn("Invalid Key", e); throw new CryptoEncodingException("Invalid key!"); } }
/** * Returns an auxiliary {@link CipherLite} for partial plaintext * re-encryption (or re-decryption) purposes. * * @param startingBytePos * the starting byte position of the plaintext. Must be a * multiple of the cipher block size. */ CipherLite createAuxiliary(long startingBytePos) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException { return scheme.createAuxillaryCipher(secreteKey, cipher.getIV(), cipherMode, cipher.getProvider(), startingBytePos); }
private void saveSecretKey(String ksAlias, ObjectOutputStream oos, KeyStore.SecretKeyEntry entry) throws IOException, GeneralSecurityException { ByteArrayOutputStream entryData = new ByteArrayOutputStream(1024); ObjectOutputStream entryOos = new ObjectOutputStream(entryData); entryOos.writeUTF(ksAlias); writeBytes(entry.getSecretKey().getEncoded(), entryOos); entryOos.flush(); encrypt.init(Cipher.ENCRYPT_MODE, storageSecretKey, (AlgorithmParameterSpec) null); // ELY-1308: third param need to workaround BouncyCastle bug int blockSize = encrypt.getBlockSize(); if (blockSize == 0) throw log.algorithmNotBlockBased(encrypt.getAlgorithm()); Assert.checkMaximumParameter("cipher block size", 256, blockSize); byte[] padded = pkcs7Pad(entryData.toByteArray(), blockSize); byte[] encrypted = encrypt.doFinal(padded); byte[] iv = encrypt.getIV(); if (iv == null) throw log.algorithmNotIV(encrypt.getAlgorithm()); oos.writeInt(SECRET_KEY_ENTRY_TYPE); writeBytes(encrypted, oos); writeBytes(iv, oos); }
@Override public void process(final InputStream in, final OutputStream out) throws IOException { // Initialize cipher provider KeyedCipherProvider cipherProvider = (KeyedCipherProvider) CipherProviderFactory.getCipherProvider(KeyDerivationFunction.NONE); // Generate cipher try { Cipher cipher = cipherProvider.getCipher(encryptionMethod, key, iv, true); cipherProvider.writeIV(cipher.getIV(), out); CipherUtility.processStreams(cipher, in, out); } catch (Exception e) { throw new ProcessException(e); } } }
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();
/** * Returns the initialization vector (IV) in a new buffer. * <p> * This is useful in the case where a random IV was created, or in the * context of password-based encryption or decryption, where the IV is * derived from a user-supplied password. * * @return the initialization vector in a new buffer, or null if the * underlying algorithm does not use an IV, or if the IV has not yet * been set. */ final byte[] getIV() { return cipher.getIV(); }
@Override public void process(final InputStream in, final OutputStream out) throws IOException { // Initialize cipher provider PBECipherProvider cipherProvider = (PBECipherProvider) CipherProviderFactory.getCipherProvider(kdf); // Generate salt byte[] salt; // NiFi legacy code determined the salt length based on the cipher block size if (cipherProvider instanceof org.apache.nifi.security.util.crypto.NiFiLegacyCipherProvider) { salt = ((org.apache.nifi.security.util.crypto.NiFiLegacyCipherProvider) cipherProvider).generateSalt(encryptionMethod); } else { salt = cipherProvider.generateSalt(); } // Write to output stream cipherProvider.writeSalt(salt, out); // Determine necessary key length int keyLength = CipherUtility.parseKeyLengthFromAlgorithm(encryptionMethod.getAlgorithm()); // Generate cipher try { Cipher cipher = cipherProvider.getCipher(encryptionMethod, new String(password.getPassword()), salt, keyLength, true); // Write IV if necessary if (cipherProvider instanceof RandomIVPBECipherProvider) { ((RandomIVPBECipherProvider) cipherProvider).writeIV(cipher.getIV(), out); } CipherUtility.processStreams(cipher, in, out); } catch (Exception e) { throw new ProcessException(e); } } }
/** * Creates a new Cipher instance based on the crypto parameters specified in * the constructor. Each Cipher instance is identical to any other Cipher * produced by this CipherFactory. * * @return A new Cipher instance, identical to each Cipher produced by this * factory instance. */ public Cipher createCipher() { Cipher cipher = EncryptionUtils.createSymmetricCipher(symmetricKey, cipherMode, cryptoProvider, initVectorBytes); // If we weren't given an IV to use, make sure we store the one the // first Cipher // used so we can use it for all future Ciphers created by this // instance. if (initVectorBytes == null) initVectorBytes = cipher.getIV(); return cipher; }
/** * Recreates a new instance of CipherLite from the current one. */ CipherLite recreate() { return scheme.createCipherLite(secreteKey, cipher.getIV(), this.cipherMode, cipher.getProvider()); }
final byte[] iv = encryptCipher.getIV(); final byte[] encrypted = encryptCipher.doFinal(data);
/** * Returns the inverse of the current {@link CipherLite}. */ CipherLite createInverse() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException { int inversedMode; if (cipherMode == Cipher.DECRYPT_MODE) inversedMode = Cipher.ENCRYPT_MODE; else if (cipherMode == Cipher.ENCRYPT_MODE) inversedMode = Cipher.DECRYPT_MODE; else throw new UnsupportedOperationException(); return scheme.createCipherLite(secreteKey, cipher.getIV(), inversedMode, cipher.getProvider()); }
/** * Returns an auxiliary {@link CipherLite} for partial plaintext * re-encryption (or re-decryption) purposes. * * @param startingBytePos the starting byte position of the plaintext. Must * be a multiple of the cipher block size. */ CipherLite createAuxiliary(long startingBytePos) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException { return scheme.createAuxillaryCipher(secreteKey, cipher.getIV(), cipherMode, cipher.getProvider(), startingBytePos); }
/** * Returns a JSONObject representation of the instruction object. */ private static Map<String, String> convertInstructionToJSONObject( EncryptionInstruction instruction) { Map<String, String> instructionJSON = new HashMap<String, String>(); String materialsDescription = JsonUtils.mapToString(instruction.getMaterialsDescription()); instructionJSON.put(Headers.MATERIALS_DESCRIPTION, materialsDescription); instructionJSON.put(Headers.CRYPTO_KEY, Base64.encodeAsString(instruction.getEncryptedSymmetricKey())); byte[] iv = instruction.getSymmetricCipher().getIV(); instructionJSON.put(Headers.CRYPTO_IV, Base64.encodeAsString(iv)); return instructionJSON; }
byte[] iv = cipher.getIV(); data.writeInt(iv.length); data.write(iv);
private static void updateMetadata(ObjectMetadata metadata, byte[] keyBytesToStoreInMetadata, Cipher symmetricCipher, Map<String, String> materialsDescription) { // If we generated a symmetric key to encrypt the data, store it in the // object metadata. if (keyBytesToStoreInMetadata != null) { metadata.addUserMetadata(Headers.CRYPTO_KEY, Base64.encodeAsString(keyBytesToStoreInMetadata)); } // Put the cipher initialization vector (IV) into the object metadata metadata.addUserMetadata(Headers.CRYPTO_IV, Base64.encodeAsString(symmetricCipher.getIV())); // Put the materials description into the object metadata as JSON String description = JsonUtils.mapToString(materialsDescription); metadata.addUserMetadata(Headers.MATERIALS_DESCRIPTION, description); }
public byte[] getIV() throws IOException, GeneralSecurityException { final Cipher enc = getCoder(false); if (enc != null) return enc.getIV(); return null; }