Example usage for javax.crypto.spec IvParameterSpec IvParameterSpec

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

Introduction

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

Prototype

public IvParameterSpec(byte[] iv) 

Source Link

Document

Creates an IvParameterSpec object using the bytes in iv as the IV.

Usage

From source file:org.wisdom.crypto.CryptoServiceSingleton.java

/**
 * Utility method encrypting/decrypting the given message.
 * The sense of the operation is specified using the `encryptMode` parameter.
 *
 * @param encryptMode  encrypt or decrypt mode ({@link javax.crypto.Cipher#DECRYPT_MODE} or
 *                     {@link javax.crypto.Cipher#ENCRYPT_MODE}).
 * @param generatedKey the generated key
 * @param vector       the initialization vector
 * @param message      the plain/cipher text to encrypt/decrypt
 * @return the encrypted or decrypted message
 *//*from  w ww  .j  ava  2 s  .  c om*/
private byte[] doFinal(int encryptMode, SecretKey generatedKey, String vector, byte[] message) {
    try {
        byte[] raw = decodeHex(vector);
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(encryptMode, generatedKey, new IvParameterSpec(raw));
        return cipher.doFinal(message);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.keepassdroid.fingerprint.FingerPrintHelper.java

private void initDecryptKey(final String ivSpecValue, boolean deleteExistingKey) throws Exception {

    createNewKeyIfNeeded(deleteExistingKey);
    keyStore.load(null);//from  w  ww .  j a  v a2s  .  c  o m
    final SecretKey key = (SecretKey) keyStore.getKey(ALIAS_KEY, null);

    // important to restore spec here that was used for decryption
    final byte[] iv = Base64Coder.decode(ivSpecValue);
    final IvParameterSpec spec = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, key, spec);
    cryptoInitOk = true;

    stopListening();
    startListening();
}

From source file:org.sejda.sambox.pdmodel.encryption.SecurityHandler.java

/**
 * Encrypt or decrypt data with AES with key length other than 256 bits.
 *
 * @param finalKey The final key obtained with via {@link #calcFinalKey()}.
 * @param data The data to encrypt./*from   w ww  .  j  av  a2  s  .c om*/
 * @param output The output to write the encrypted data to.
 *
 * @throws IOException If there is an error reading the data.
 */
private void decryptDataAESother(byte[] finalKey, InputStream data, OutputStream output) throws IOException {
    byte[] iv = new byte[16];

    int ivSize = data.read(iv);
    if (ivSize == -1) {
        return;
    }
    if (ivSize != iv.length) {
        throw new IOException("AES initialization vector not fully read: only " + ivSize
                + " bytes read instead of " + iv.length);
    }

    try {
        Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        SecretKey aesKey = new SecretKeySpec(finalKey, "AES");
        IvParameterSpec ips = new IvParameterSpec(iv);
        decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ips);
        byte[] buffer = new byte[256];
        int n;
        while ((n = data.read(buffer)) != -1) {
            byte[] update = decryptCipher.update(buffer, 0, n);
            if (update != null) {
                output.write(update);
            }
        }
        output.write(decryptCipher.doFinal());
    } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException
            | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new IOException(e);
    }
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java

@Override
public CipherOutputStream getCipherOutputStream(File file, String outputFileName)
        throws SecrecyCipherStreamException, FileNotFoundException {
    Cipher c;//from w w w  .  j  a va2 s . co m
    try {
        c = Cipher.getInstance(encryptionMode);
    } catch (NoSuchAlgorithmException e) {
        throw new SecrecyCipherStreamException("Encryption algorithm not found!");
    } catch (NoSuchPaddingException e) {
        throw new SecrecyCipherStreamException("Selected padding not found!");
    }

    File headerFile = new File(vaultPath + FILE_HEADER_PREFIX + outputFileName);
    File outputFile = new File(vaultPath + "/" + outputFileName);

    byte[] fileEncryptionNonce = new byte[NONCE_LENGTH_BYTE];
    byte[] fileNameNonce = new byte[NONCE_LENGTH_BYTE];
    secureRandom.nextBytes(fileEncryptionNonce);
    secureRandom.nextBytes(fileNameNonce);

    try {
        c.init(Cipher.ENCRYPT_MODE, vaultFileEncryptionKey, new IvParameterSpec(fileNameNonce));
    } catch (InvalidKeyException e) {
        throw new SecrecyCipherStreamException("Invalid encryption key!");
    } catch (InvalidAlgorithmParameterException e) {
        throw new SecrecyCipherStreamException("Invalid algorithm parameter!");
    }

    byte[] encryptedFileName;
    try {
        encryptedFileName = c.doFinal(file.getName().getBytes());
    } catch (IllegalBlockSizeException e) {
        throw new SecrecyCipherStreamException("Illegal block size!");
    } catch (BadPaddingException e) {
        throw new SecrecyCipherStreamException("Bad padding");
    }

    FileHeader.Builder fileHeaderBuilder = FileHeader.newBuilder();
    fileHeaderBuilder.setVersion(FILE_HEADER_VERSION);
    fileHeaderBuilder.setFileIV(ByteString.copyFrom(fileEncryptionNonce));
    fileHeaderBuilder.setFileNameIV(ByteString.copyFrom(fileNameNonce));
    fileHeaderBuilder.setEncryptedFileName(ByteString.copyFrom(encryptedFileName));

    FileOutputStream headerOutputStream = new FileOutputStream(headerFile);
    try {
        fileHeaderBuilder.build().writeTo(headerOutputStream);
        headerOutputStream.close();
    } catch (IOException e) {
        throw new SecrecyCipherStreamException("IO exception while writing file header");
    }

    try {
        c.init(Cipher.ENCRYPT_MODE, vaultFileEncryptionKey, new IvParameterSpec(fileEncryptionNonce));
    } catch (InvalidKeyException e) {
        throw new SecrecyCipherStreamException("Invalid encryption key!");
    } catch (InvalidAlgorithmParameterException e) {
        throw new SecrecyCipherStreamException("Invalid algorithm parameter!");
    }

    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile),
            Config.BLOCK_SIZE);

    return new CipherOutputStream(bufferedOutputStream, c);
}

From source file:org.codice.ddf.configuration.migration.MigrationZipFileTest.java

private Cipher createEncryptionCipher(Path keyPath) throws Exception {
    Cipher cipher = Cipher.getInstance(MigrationZipConstants.CIPHER_ALGORITHM);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(MigrationZipConstants.CIPHER_IV);
    cipher.init(Cipher.ENCRYPT_MODE, createSecretKey(keyPath), ivParameterSpec);
    return cipher;
}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
 * We have the password from initializing the class. pass the iv and salt here which is
 * obtained when encrypting the file initially.
 *
 * @param inFile - The Encrypted File containing encrypted data , salt and InitVec
 * @throws NoSuchAlgorithmException//from   w w w.j  a  v  a2  s .  co  m
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 * @throws IOException
 */
public void setupDecrypt(File inFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, DecoderException, IOException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    byte[] vSalt = new byte[8];
    byte[] vInitVec = new byte[16];

    RandomAccessFile vFile = new RandomAccessFile(inFile, "rw");

    //The last 8 bits are salt so seek to length of file minus 9 bits
    vFile.seek(vFile.length() - 8);
    vFile.readFully(vSalt);

    //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24
    //Thus to seek to length of file minus 24 bits
    vFile.seek(vFile.length() - 24);
    vFile.readFully(vInitVec);
    vFile.seek(0);

    File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file");

    RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw");

    for (int i = 0; i < (vFile.length() - 24); ++i) {
        vTmpFile.write(vFile.readByte());
    }
    vFile.close();
    vTmpFile.close();

    inFile.delete();
    tmpFile.renameTo(inFile);

    Db("got salt " + Hex.encodeHexString(vSalt));

    Db("got initvector :" + Hex.encodeHexString(vInitVec));

    /* Derive the key, given password and salt. */
    // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
    // The end user must also install them (not compiled in) so beware.
    // see here:
    // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
    // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function
    //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard)

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);

    tmp = factory.generateSecret(spec);
    secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    // Decrypt the message, given derived key and initialization vector.
    vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec));
}

From source file:org.openmrs.util.Security.java

/**
 * decrypt text to a string with specific initVector and secretKey; rarely used except in
 * testing and where specifically necessary
 *
 * @see #decrypt(String)//from www  .j  a va  2 s. c o m
 *
 * @param text text to be decrypted
 * @param initVector custom init vector byte array
 * @param secretKey custom secret key byte array
 * @return decrypted text
 * @since 1.9
 */
public static String decrypt(String text, byte[] initVector, byte[] secretKey) {
    IvParameterSpec initVectorSpec = new IvParameterSpec(initVector);
    SecretKeySpec secret = new SecretKeySpec(secretKey, OpenmrsConstants.ENCRYPTION_KEY_SPEC);
    String decrypted = null;

    try {
        Cipher cipher = Cipher.getInstance(OpenmrsConstants.ENCRYPTION_CIPHER_CONFIGURATION);
        cipher.init(Cipher.DECRYPT_MODE, secret, initVectorSpec);
        byte[] original = cipher.doFinal(Base64.decode(text));
        decrypted = new String(original, encoding);
    } catch (GeneralSecurityException e) {
        throw new APIException("could.not.decrypt.text", null, e);
    } catch (UnsupportedEncodingException e) {
        throw new APIException("system.cannot.find.encoding", new Object[] { encoding }, e);
    }

    return decrypted;
}

From source file:com.microsoft.azure.storage.blob.BlobEncryptionPolicy.java

/**
 * Return a reference to a {@link OutputStream} given a user stream. This method is used for decrypting blobs.
 * @param userProvidedStream/*from  w w w .j  a va 2s.  c o  m*/
 *          The output stream provided by the user.
 * @param metadata
 *          Reference to blob metadata object that is used to get the encryption materials.
 * @param requireEncryption
 *          A value to indicate that the data read from the server should be encrypted.
 * @param iv
 *          The iv to use if pre-buffered. Used only for range reads.
 * @param noPadding
 *          Value indicating if the padding mode should be set or not.
 * @return A reference to a {@link OutputStream} that will be written to.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
OutputStream decryptBlob(OutputStream userProvidedStream, Map<String, String> metadata,
        Boolean requireEncryption, byte[] iv, boolean noPadding) throws StorageException {
    Utility.assertNotNull("metadata", metadata);

    // If encryption policy is set but the encryption metadata is absent, throw
    // an exception.
    String encryptionDataString = metadata.get("encryptiondata");
    if (requireEncryption != null && requireEncryption && encryptionDataString == null) {
        throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                SR.ENCRYPTION_DATA_NOT_PRESENT_ERROR, null);
    }

    try {
        if (encryptionDataString != null) {
            BlobEncryptionData encryptionData = BlobEncryptionData.deserialize(encryptionDataString);

            Utility.assertNotNull("encryptionData", encryptionData);
            Utility.assertNotNull("contentEncryptionIV", encryptionData.getContentEncryptionIV());
            Utility.assertNotNull("encryptedKey", encryptionData.getWrappedContentKey().getEncryptedKey());

            // Throw if the encryption protocol on the message doesn't match the version that this client library understands
            // and is able to decrypt.
            if (!Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1
                    .equals(encryptionData.getEncryptionAgent().getProtocol())) {
                throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                        SR.ENCRYPTION_PROTOCOL_VERSION_INVALID, null);
            }

            // Throw if neither the key nor the key resolver are set.
            if (this.keyWrapper == null && this.keyResolver == null) {
                throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                        SR.KEY_AND_RESOLVER_MISSING, null);
            }

            byte[] contentEncryptionKey = null;

            // 1. Invoke the key resolver if specified to get the key. If the resolver is specified but does not have a
            // mapping for the key id, an error should be thrown. This is important for key rotation scenario.
            // 2. If resolver is not specified but a key is specified, match the key id on the key and and use it.
            // Calling UnwrapKeyAsync synchronously is fine because for the storage client scenario, unwrap happens
            // locally. No service call is made.
            if (this.keyResolver != null) {
                IKey keyEncryptionKey = this.keyResolver
                        .resolveKeyAsync(encryptionData.getWrappedContentKey().getKeyId()).get();

                Utility.assertNotNull("keyEncryptionKey", keyEncryptionKey);
                contentEncryptionKey = keyEncryptionKey
                        .unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(),
                                encryptionData.getWrappedContentKey().getAlgorithm())
                        .get();
            } else {
                if (encryptionData.getWrappedContentKey().getKeyId().equals(this.keyWrapper.getKid())) {
                    contentEncryptionKey = this.keyWrapper
                            .unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(),
                                    encryptionData.getWrappedContentKey().getAlgorithm())
                            .get();
                } else {
                    throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.KEY_MISMATCH, null);
                }
            }

            switch (encryptionData.getEncryptionAgent().getEncryptionAlgorithm()) {
            case AES_CBC_256:

                Cipher myAes;
                if (noPadding) {
                    myAes = Cipher.getInstance("AES/CBC/NoPadding");
                } else {
                    myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
                }

                IvParameterSpec ivParameterSpec = new IvParameterSpec(
                        iv != null ? iv : encryptionData.getContentEncryptionIV());
                SecretKey keySpec = new SecretKeySpec(contentEncryptionKey, 0, contentEncryptionKey.length,
                        "AES");
                myAes.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);

                return new CipherOutputStream(userProvidedStream, myAes);

            default:
                throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                        SR.INVALID_ENCRYPTION_ALGORITHM, null);
            }
        } else {
            return userProvidedStream;
        }
    } catch (StorageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.DECRYPTION_LOGIC_ERROR, ex);
    }
}

From source file:org.cablelabs.widevine.keyreq.KeyRequest.java

/**
 * Perform the key request./*from  ww w.j ava 2  s .c o  m*/
 * 
 * @return the response message
 */
public ResponseMessage requestKeys() {

    int i;

    Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    Gson prettyGson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create();

    // Create request object
    RequestMessage requestMessage = new RequestMessage();
    requestMessage.content_id = Base64.encodeBase64String(content_id.getBytes());
    requestMessage.policy = POLICY;
    requestMessage.client_id = CLIENT_ID;
    requestMessage.drm_types = DRM_TYPES;

    // Add the track requests to the message
    requestMessage.tracks = new RequestMessage.Track[tracks.size()];
    i = 0;
    for (Track t : tracks) {
        RequestMessage.Track track = new RequestMessage.Track();
        track.type = t.type;
        requestMessage.tracks[i++] = track;
    }

    // Rolling keys
    if (rollingKeyCount != -1 && rollingKeyStart != -1) {
        requestMessage.crypto_period_count = rollingKeyCount;
        requestMessage.first_crypto_period_index = rollingKeyStart;
    }

    // Convert request message to JSON and base64 encode
    String jsonRequestMessage = gson.toJson(requestMessage);
    System.out.println("Request Message:");
    System.out.println(prettyGson.toJson(requestMessage));

    // Create request JSON
    Request request = new Request();
    request.request = Base64.encodeBase64String(jsonRequestMessage.getBytes());

    String serverURL = null;
    if (sign_request) {
        // Create message signature
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(jsonRequestMessage.getBytes());
            byte[] sha1_b = sha1.digest();
            System.out.println("SHA-1 hash of JSON request message = 0x" + Hex.encodeHexString(sha1_b));

            // Use AES/CBC/PKCS5Padding with CableLabs Key and InitVector
            SecretKeySpec keySpec = new SecretKeySpec(sign_key, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(sign_iv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            // Encrypt the SHA-1 hash of our request message
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encrypted = cipher.doFinal(sha1_b);
            System.out
                    .println("AES/CBC/PKCS5Padding Encrypted SHA1-hash = 0x" + Hex.encodeHexString(encrypted));

            request.signer = provider;
            request.signature = Base64.encodeBase64String(encrypted);

            serverURL = license_url;
        } catch (Exception e) {
            System.out.println("Error performing message encryption!  Message = " + e.getMessage());
            System.exit(1);
        }
    } else {
        request.signer = TEST_PROVIDER;
        serverURL = TEST_SERVER_URL;
    }

    String jsonRequest = gson.toJson(request);
    System.out.println("Request:");
    System.out.println(prettyGson.toJson(request));

    String jsonResponseStr = null;
    try {

        // Create URL connection
        URL url = new URL(serverURL);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setDoOutput(true);

        System.out.println("Sending HTTP POST to " + serverURL);

        // Write POST data
        DataOutputStream out = new DataOutputStream(con.getOutputStream());
        out.writeBytes(jsonRequest);
        out.flush();
        out.close();

        // Wait for response
        int responseCode = con.getResponseCode();
        System.out.println("Received response code -- " + responseCode);

        // Read response data
        DataInputStream dis = new DataInputStream(con.getInputStream());
        int bytesRead;
        byte responseData[] = new byte[1024];
        StringBuffer sb = new StringBuffer();
        while ((bytesRead = dis.read(responseData)) != -1) {
            sb.append(new String(responseData, 0, bytesRead));
        }
        jsonResponseStr = sb.toString();
    } catch (Exception e) {
        System.err.println("Error in HTTP communication! -- " + e.getMessage());
        System.exit(1);
    }

    Response response = gson.fromJson(jsonResponseStr, Response.class);
    System.out.println("Response:");
    System.out.println(prettyGson.toJson(response));

    String responseMessageStr = new String(Base64.decodeBase64(response.response));
    ResponseMessage responseMessage = gson.fromJson(responseMessageStr, ResponseMessage.class);
    System.out.println("ResponseMessage:");
    System.out.println(prettyGson.toJson(responseMessage));

    return responseMessage;
}

From source file:org.parelon.pskc.CryptManager.java

/**
 * Encrypt the plain text value using AES-128-CBC/PKCS5Padding.
 * /*from w  w w  .ja  v  a  2s  .co m*/
 * @param plainValue Value to encrypt.
 * @return Ciphered secret.
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException 
 * @throws com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException 
 */
public byte[] aesEncryptSecret(byte[] plainValue) throws InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
        Base64DecodingException, UnsupportedEncodingException, NoSuchAlgorithmException, DecoderException {
    byte[] Iv = new byte[16]; // MUST be random
    randomize.nextBytes(Iv);
    byte[] secretBytes = Hex.decodeHex(new String(plainValue).trim().toCharArray());
    this.cipherParamSpec = new IvParameterSpec(Iv);
    this.aesCipher.init(Cipher.ENCRYPT_MODE, this.aesKey, this.cipherParamSpec);
    byte[] encryptedSecret = this.aesCipher.doFinal(secretBytes);
    return concatByteArrays(Iv, encryptedSecret);
}