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:com.cl.roadshow.crypto.AESCtr.java

/**
 * Private encryption method./*from  w w  w .  java  2 s . co m*/
 * 
 * @param keystring
 * @param message
 * @param bits
 * @return bytearray containing encrypted message
 * @throws Exception
 */
private static byte[] encrypt(String keystring, String message, int bits) throws Exception {
    byte[] encValue = null;
    SecureRandom random = new SecureRandom();
    byte[] nonceBytes = new byte[8];
    random.nextBytes(nonceBytes);
    IvParameterSpec nonce = new IvParameterSpec(Arrays.copyOf(nonceBytes, 16));

    Key key = generateKey(keystring, bits);
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.ENCRYPT_MODE, key, nonce);
    byte[] ciphertextWithoutNonce = c.doFinal(message.getBytes("UTF-8"));
    encValue = Arrays.copyOf(nonceBytes, nonceBytes.length + ciphertextWithoutNonce.length);
    for (int i = 0; i < ciphertextWithoutNonce.length; i++) {
        encValue[i + 8] = ciphertextWithoutNonce[i];
    }

    return encValue;
}

From source file:com.diona.fileReader.CipherUtil.java

/**
 * Decrypts a given encrypted string./*  w w w  . j  av  a  2 s .co  m*/
 * 
 * @param bytes
 *          encrypted string to be decrypted.
 * @param context
 *          context to fetch preferences.
 * @return the original string.
 */
public byte[] decryptBytes(final byte[] bytes, final Context context) {
    // Transaction.checkLongRunningProcessing("decryptBytes");

    if (!ENCRYPTION_ENABLED) {
        return bytes;
    }

    byte[] decryptedTextBytes = null;
    try {
        final IvParameterSpec ivspec = new IvParameterSpec(getIV(context));
        final Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(context), ivspec);
        decryptedTextBytes = cipher.doFinal(bytes);

    } catch (final Exception e) {
        Log.e(TAG, "e" + e);
    }
    return decryptedTextBytes;
}

From source file:com.anteam.demo.codec.cipher.symmetric.DESTest.java

License:asdf

public byte[] testDESedeEn(String plainText) {
    try {//  ww  w . ja va  2  s.c o  m
        // Create an array to hold the key
        byte[] encryptKey = "This is a test DESede key".getBytes();

        // Create a DESede key spec from the key
        DESedeKeySpec spec = new DESedeKeySpec(encryptKey);

        // Get the secret key factor for generating DESede keys
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");

        // Generate a DESede SecretKey object
        SecretKey theKey = keyFactory.generateSecret(spec);

        // Create a DESede Cipher
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");

        // Create an initialization vector (necessary for CBC mode)

        IvParameterSpec IvParameters = new IvParameterSpec(
                new byte[] { 0x01, 0x02, 0x03, 0x04, 0x0F, 0x0E, 0x0D, 0x0C });

        // Initialize the cipher and put it into encrypt mode
        cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters);
        return cipher.doFinal(plainText.getBytes());

    } catch (Exception exc) {
        exc.printStackTrace();
    }
    return null;
}

From source file:edu.utdallas.bigsecret.cipher.AesCtr.java

/**
 * Decrypts input data starting and including the offset index position<br>
 * with AES CTR mode./* w  w  w.  jav  a  2s.c o m*/
 * @param data Input byte array.
 * @param offset Offset to start decryption.
 * @return Decryption result.
 * @throws Exception Throws exception if there is no data to decrypt.<br>
 *                 Throws exception if offset is invalid.<br>
 *                 May throw exception based on Javax.Crypto.Cipher class.
 */
public byte[] decrypt(byte[] data, int offset) throws Exception {
    //check if there is data to decrypt after the offset and iv
    if (data.length <= BLOCK_SIZE_BYTES + offset) {
        throw new Exception("No data to decrypt");
    }

    //get iv value from the beggining of data
    byte[] iv = new byte[BLOCK_SIZE_BYTES];
    System.arraycopy(data, offset, iv, 0, BLOCK_SIZE_BYTES);

    //init cipher instance
    m_cipher.init(javax.crypto.Cipher.DECRYPT_MODE, m_keySpec, new IvParameterSpec(iv));

    //return decrypted value
    return m_cipher.doFinal(data, (BLOCK_SIZE_BYTES + offset), data.length - (BLOCK_SIZE_BYTES + offset));
}

From source file:de.petendi.commons.crypto.HybridCrypto.java

private byte[] encryptInternal(byte[] message) {
    createSymmetricPassphrase();//from w  w  w  . j  av  a  2 s  .co  m

    try {
        Cipher cipher = Cipher.getInstance(SYMMETRIC_CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, symmetricKey, new IvParameterSpec(iv));
        byte[] encryptedBody = cipher.doFinal(message);
        encryptedMessage.setEncryptedBody(encryptedBody);
        return encryptedBody;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:egovframework.com.ext.jfile.security.service.CipherServiceImpl.java

public byte[] encrypt(byte[] data) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,
        IOException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException,
        InvalidAlgorithmParameterException {
    Cipher cipher = getCipherInstance();

    if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES);
        cipher.init(Cipher.ENCRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec);
    } else {/*from   w  w  w.j a v a  2 s  .c o  m*/
        cipher.init(Cipher.ENCRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()));
    }
    if (jcrypto.isApplyBase64()) {
        //sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
        //return encoder.encode(cipher.doFinal(data)).getBytes();
        return Base64.encodeBase64(cipher.doFinal(data));

    } else {
        return cipher.doFinal(data);
    }
}

From source file:edu.cmu.sei.ams.cloudlet.impl.AESEncrypter.java

public byte[] decrypt(String encrypted) throws EncryptionException {
    try {//from   w  w  w.j  a v a2  s.  c o m
        //log.info("Encrypted string: " + encrypted);
        byte[] cryptedBytes = Base64.decodeBase64(encrypted.getBytes());

        byte[] iv = new byte[16];
        System.arraycopy(cryptedBytes, 0, iv, 0, 16);
        //log.info("IV: " + String.valueOf(Hex.encodeHex(iv)));
        byte[] crypted = new byte[cryptedBytes.length - 16];
        System.arraycopy(cryptedBytes, 16, crypted, 0, crypted.length);
        //log.info("Cipher Text: " + String.valueOf(Hex.encodeHex(crypted)));

        // TODO: change to CBC method with padding.
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, this.skeySpec, new IvParameterSpec(iv));

        byte[] decrypted = cipher.doFinal(crypted);
        log.info("Data decrypted.");
        return decrypted;
    } catch (Exception e) {
        throw new EncryptionException("Error decrypting information", e);
    }
}

From source file:de.schildbach.wallet.util.FingerprintHelper.java

@Nullable
@RequiresApi(api = Build.VERSION_CODES.M)
private Cipher createCipher(int mode) throws NoSuchPaddingException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, InvalidKeyException, InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC
            + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);

    Key key = keyStore.getKey(KEYSTORE_ALIAS, null);
    if (key == null) {
        return null;
    }//  w  w w.j a va  2  s .  c  o m
    if (mode == Cipher.ENCRYPT_MODE) {
        cipher.init(mode, key);
        byte[] iv = cipher.getIV();
        saveIv(iv);
    } else {
        byte[] lastIv = getLastIv();
        cipher.init(mode, key, new IvParameterSpec(lastIv));
    }
    return cipher;
}

From source file:de.siegmar.securetransfer.component.Cryptor.java

public OutputStream getCryptOut(final OutputStream out, final KeyIv keyIv) throws IOException {
    return new CryptoOutputStream(TRANSFORM, new Properties(), out, new SecretKeySpec(keyIv.getKey(), "AES"),
            new IvParameterSpec(keyIv.getIv()));
}

From source file:com.muk.services.commerce.CryptoServiceImpl.java

@PostConstruct
public void postConstruct() {
    try {/*from www.  jav  a 2 s .c o m*/
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        temporaryKey = new SecretKeySpec(kgen.generateKey().getEncoded(), "AES");

        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        final byte[] iv = new byte[cipher.getBlockSize()];
        new SecureRandom().nextBytes(iv);
        ivSpec = new IvParameterSpec(iv);
    } catch (final NoSuchAlgorithmException ex) {
        LOG.error("Failed to initalize encryption key", ex);
    } catch (final NoSuchPaddingException padEx) {
        LOG.error("Failed to get cipher.", padEx);
    }
}