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.hdiv.cipher.CipherHTTP.java

/**
 * <p>/*from w  w  w.j  a va  2s.c o m*/
 * Generates a Cipher object that implements the specified <code>transformation</code>, initializes cipher vector
 * and initializes cipher to encryption mode with a key and a set of algorithm parameters.
 * </p>
 * <p>
 * The name of the transformation, e.g., DES/CBC/PKCS5Padding. See Appendix A in the <a
 * href="../../../guide/security/jce/JCERefGuide.html#AppA"> Java Cryptography Extension Reference Guide for
 * information about standard transformation names.
 * </p>
 * 
 * @param key
 *            the encryption key
 * @throws HDIVException
 *             if there is an initialization error.
 */
public void initEncryptMode(Key key) {

    try {
        // vector initialization
        this.ivSpec = new IvParameterSpec(key.getInitVector());

        // Constant used to initialize cipher to encryption mode
        this.cipher.init(Cipher.ENCRYPT_MODE, key.getKey(), this.ivSpec);
        this.encryptMode = true;

    } catch (Exception e) {
        String errorMessage = HDIVUtil.getMessage("cipher.init.encrypt", e.getMessage());
        throw new HDIVException(errorMessage, e);
    }
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Encrypts a message./*  www .j a  v  a2  s  .  c o  m*/
 * @param args Arguments: data, publicKey[, privateKey]
 * @param callback Callback
 */
public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        PRNGProvider.init(); // Ensure OpenSSL fix

        // Get the arguments
        String data = args.getString(0);
        String pub = args.getString(1);
        String priv = null;
        if (args.length() == 3) {
            priv = args.getString(2);
        }
        String sig = null;

        // Convert everything into byte arrays
        byte[] dataRaw = data.getBytes("utf-8");
        byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);

        // Generate random AES key and IV
        byte[] aesKey = new byte[AES_BYTES];
        new SecureRandom().nextBytes(aesKey);
        byte[] aesIv = new byte[16]; // Block size
        new SecureRandom().nextBytes(aesIv);
        Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));

        // Encrypt data with AES
        byte[] encData = c.doFinal(dataRaw);

        // Encrypt aes data with RSA
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec));
        c.update(aesKey);
        c.update(aesIv);
        byte[] encKey = c.doFinal();

        // Concatenate and transform
        byte[] encRaw = new byte[encKey.length + encData.length];
        System.arraycopy(encKey, 0, encRaw, 0, encKey.length);
        System.arraycopy(encData, 0, encRaw, encKey.length, encData.length);
        encKey = null;
        encData = null;
        String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8");

        // Sign
        if (priv != null) {
            // Fail on error (no try-catch)
            byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT);
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw);
            Signature s = Signature.getInstance("SHA1withRSA", "BC");
            s.initSign(kf.generatePrivate(privateKeySpec));
            s.update(encRaw);
            sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8");
        }

        JSONArray res = new JSONArray();
        res.put(enc);
        res.put(sig);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:org.casbah.provider.SSLeayEncoder.java

private static byte[] performCipherOperation(byte[] data, byte[] salt, String keypass, int opMode)
        throws GeneralSecurityException, IOException {
    Cipher cipher = Cipher.getInstance(JAVA_ENC_ALGORITHM);
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(JAVA_KEY_TYPE);
    SecretKey secretKey = secretKeyFactory.generateSecret(calculateKeyFromPassKey(keypass.getBytes(), salt));
    IvParameterSpec iv = new IvParameterSpec(salt);
    cipher.init(opMode, secretKey, iv);/*from ww w  . ja  va 2  s .  c  o  m*/
    return cipher.doFinal(data);
}

From source file:com.alliander.osgp.shared.security.EncryptionService.java

/**
 * Decrypts the data using the key, Strips off iv bytes when they are there
 * (first 16 0 bytes).//  w w  w  . j  av a  2  s .co  m
 */
public byte[] decrypt(final byte[] inputData) {

    try {
        final Cipher cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
        cipher.init(Cipher.DECRYPT_MODE, this.key, new IvParameterSpec(IVBYTES));
        final byte[] decryptedData = cipher.doFinal(inputData);
        if (this.checkNullBytesPrepended(decryptedData)) {
            return Arrays.copyOfRange(decryptedData, IVBYTES.length, decryptedData.length);
        } else {
            return decryptedData;
        }
    } catch (final NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | IllegalBlockSizeException | BadPaddingException | NoSuchProviderException
            | InvalidAlgorithmParameterException ex) {
        LOGGER.error(UNEXPECTED_EXCEPTION_DURING_DECRYPTION, ex);
        throw new EncrypterException("Unexpected exception during decryption!", ex);
    }
}

From source file:net.alegen.datpass.library.crypto.CryptoManager.java

public String decrypt(EncryptionOutput encryptionOutput, String password) {
    final String ctext = encryptionOutput.getCypherText();
    final String salt = encryptionOutput.getSalt();
    final String iv = encryptionOutput.getIV();
    try {/*from w  ww.  jav  a 2 s. co  m*/
        // set up the decryption key
        byte[] saltBytes = Base64.decodeBase64(salt.getBytes("UTF-8"));
        SecretKey key = this.derivateKey(KeyDerivationFunctions.PBKDF2_HMAC_SHA1, password, saltBytes,
                AES_KEY_LENGTH, DEFAULT_ITERATIONS);
        key = new SecretKeySpec(key.getEncoded(), "AES");

        // decrypt cipher text with AES using generated key
        byte[] cipherBytes = Base64.decodeBase64(ctext.getBytes("UTF-8"));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iVBytes = Base64.decodeBase64(iv.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iVBytes));
        byte[] plaintext = cipher.doFinal(cipherBytes);

        // return plaintext
        return new String(plaintext, "UTF-8");
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | UnsupportedEncodingException | InvalidAlgorithmParameterException e) {
        log.error("An error occured while decrypting the message.");
        return null;
    }
}

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

/**
 * Creates a {@link Cipher} for use during file encryption and stores the secret key in a file
 *
 * @throws MigrationException when an invalid key is provided
 * @throws MigrationException when an invalid key padding is used
 * @throws MigrationException when and invalid cipher algorithm is used
 * @return a {@link Cipher} in encrypt mode
 *///from   ww  w  . j  a v  a 2  s.c om
private Cipher createEncryptionCipher() {
    try {
        Cipher iCipher = Cipher.getInstance(MigrationZipConstants.CIPHER_ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(MigrationZipConstants.CIPHER_IV);
        iCipher.init(Cipher.ENCRYPT_MODE, initKey(keyPath), ivParameterSpec);
        return iCipher;
    } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException
            | InvalidAlgorithmParameterException e) {
        throw new MigrationException(MigrationZipConstants.KEY_INVALID_ERROR, keyPath, e);
    }
}

From source file:org.openmrs.module.clinicalsummary.io.UploadSummariesTask.java

/**
 * Method to initialize the cipher object with the correct encryption algorithm.
 *
 * @throws Exception/* w ww  .j a  va  2 s. c o  m*/
 */
protected void initializeCipher() throws Exception {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY);
    KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128);
    SecretKey tmp = factory.generateSecret(spec);

    if (log.isDebugEnabled())
        log.debug("Secret Key Length: " + tmp.getEncoded().length);

    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC);

    cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION);
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(initVector));
}

From source file:org.slc.sli.encryption.tool.Encryptor.java

public String encrypt(String alias, String password, String algorithm, String initVec, String message)
        throws GeneralSecurityException {
    Key key = keystore.getKey(alias, password.toCharArray());
    Cipher cipher = Cipher.getInstance(algorithm);

    IvParameterSpec ivspec = null;
    if (initVec != null) {
        byte[] ivBytes;
        try {//from  ww w.ja  v a 2  s.co m
            ivBytes = Hex.decodeHex(initVec.toCharArray());
        } catch (DecoderException e) {
            throw new RuntimeException(e);
        }
        ivspec = new IvParameterSpec(ivBytes);

        cipher.init(Cipher.ENCRYPT_MODE, (SecretKey) key, ivspec);
    } else {
        cipher.init(Cipher.ENCRYPT_MODE, (SecretKey) key);
    }

    byte[] encryptedBytes = cipher.doFinal(message.getBytes());
    String encoded = Base64.encodeBase64String(encryptedBytes);

    return encoded;
}

From source file:com.springcryptoutils.core.cipher.symmetric.Base64EncodedCiphererImpl.java

/**
 * Encrypts or decrypts a message. The encryption/decryption mode depends on
 * the configuration of the mode parameter.
 *
 * @param key a base64 encoded version of the symmetric key
 * @param initializationVector a base64 encoded version of the
 *        initialization vector/*ww  w.j  a v  a  2 s.  com*/
 * @param message if in encryption mode, the clear-text message to encrypt,
 *        otherwise a base64 encoded version of the message to decrypt
 * @return if in encryption mode, returns a base64 encoded version of the
 *         encrypted message, otherwise returns the decrypted clear-text
 *         message
 * @throws SymmetricEncryptionException on runtime errors
 * @see #setMode(com.google.code.springcryptoutils.core.cipher.Mode)
 */
public String encrypt(String key, String initializationVector, String message) {
    try {
        IvParameterSpec initializationVectorSpec = new IvParameterSpec(
                Base64.decodeBase64(initializationVector));
        final SecretKeySpec keySpec = new SecretKeySpec(Base64.decodeBase64(key), keyAlgorithm);
        final Cipher cipher = (((provider == null) || (provider.length() == 0))
                ? Cipher.getInstance(cipherAlgorithm)
                : Cipher.getInstance(cipherAlgorithm, provider));
        byte[] messageAsByteArray;

        switch (mode) {
        case ENCRYPT:
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, initializationVectorSpec);
            messageAsByteArray = message.getBytes(charsetName);
            final byte[] encryptedMessage = cipher.doFinal(messageAsByteArray);
            return new String(Base64.encodeBase64(encryptedMessage, chunkOutput));
        case DECRYPT:
            cipher.init(Cipher.DECRYPT_MODE, keySpec, initializationVectorSpec);
            messageAsByteArray = Base64.decodeBase64(message);
            final byte[] decryptedMessage = cipher.doFinal(messageAsByteArray);
            return new String(decryptedMessage, charsetName);
        default:
            return null;
        }
    } catch (Exception e) {
        throw new SymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e);
    }
}

From source file:ai.serotonin.backup.Restore.java

File decryptFile(final File encryptedFile) throws Exception {
    String filename = encryptedFile.getName();

    int pos = filename.indexOf('_');
    final String saltStr = filename.substring(0, pos);
    final byte[] salt = Hex.decodeHex(saltStr.toCharArray());
    filename = filename.substring(pos + 1);

    pos = filename.indexOf('_');
    final String ivStr = filename.substring(0, pos);
    final byte[] iv = Hex.decodeHex(ivStr.toCharArray());
    filename = filename.substring(pos + 1);

    final File file = new File(filename);

    final SecretKey secret = createSecretKey(salt);

    final Cipher cipher = createCipher();
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));

    cipherizeFile(encryptedFile, file, cipher);

    LOG.info("Decrypted archive to " + filename);

    return file;/* w  ww .ja v a2  s. com*/
}