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.invariantproperties.sandbox.springentitylistener.service.EncryptorBean.java

/**
 * Decrypt string/*from   w  ww.  j  a  v  a2  s .  c om*/
 */
public String decryptString(String ciphertext, String salt) {
    String plaintext = null;

    if (ciphertext != null) {
        try {
            // Encryptor encryptor = JavaEncryptor.getInstance();
            // CipherText ct =
            // CipherText.fromPortableSerializedBytes(Base64.decode(ciphertext));
            // plaintext = encryptor.decrypt(key, ct).toString();
            IvParameterSpec iv = new IvParameterSpec(Base64.decode(salt));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, iv);

            plaintext = new String(cipher.doFinal(Base64.decode(ciphertext)));
        } catch (NoSuchAlgorithmException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (NoSuchPaddingException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (InvalidKeyException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (BadPaddingException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (IllegalBlockSizeException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace(System.out);
        }
    }

    return plaintext;
}

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

/**
 * Encrypts the given string (plaintext).
 * /*from w w  w .  ja  v  a2 s.  c  om*/
 * @param bytes
 *          byte array to be encrypted.
 * @param context
 *          context to fetch preferences.
 * @return encrypted byte array.
 */
@SuppressLint("TrulyRandom")
public byte[] encryptBytes(final byte[] bytes, final Context context) {

    // Transaction.checkLongRunningProcessing("encryptBytes");

    if (!ENCRYPTION_ENABLED) {
        return bytes;
    }

    byte[] encryptedTextBytes = null;
    try {
        // Derive the secret key
        final SecretKeySpec secretKey = getSecretKey(context);

        // encrypt the message
        final Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        final IvParameterSpec ivspec = new IvParameterSpec(getIV(context));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
        encryptedTextBytes = cipher.doFinal(bytes);
    } catch (final Exception e) {
        Log.e(TAG, "" + e);
    }
    return encryptedTextBytes;
}

From source file:press.gfw.chat.Encrypt.java

/**
 * //from   ww  w .j a va2 s .c  o  m
 *
 * @param key
 *            SecretKey
 * @param cipher_data
 *            ?
 * @param IV
 *            IV
 *
 * @return ?
 *
 */
public byte[] decrypt(SecretKey key, byte[] cipher_data, byte[] IV) {

    if (key == null || cipher_data == null || cipher_data.length == 0 || IV == null || IV.length == 0) {

        return null;

    }

    IvParameterSpec IVSpec = new IvParameterSpec(IV);

    try {

        cipher.init(Cipher.DECRYPT_MODE, key, IVSpec);

    } catch (InvalidKeyException | InvalidAlgorithmParameterException ex) {

        log("?Cipher");

        ex.printStackTrace();

        return null;

    }

    try {

        return cipher.doFinal(cipher_data);

    } catch (IllegalBlockSizeException | BadPaddingException ex) {

        log("?");

        ex.printStackTrace();

        return null;

    }

}

From source file:org.craftercms.commons.crypto.SimpleCipher.java

public byte[] decrypt(byte[] encrypted) throws CryptoException {
    if (key == null) {
        throw new CryptoException(ERROR_KEY_KEY_NOT_SET);
    }/*w ww  .jav a  2  s.c  o  m*/
    if (iv == null) {
        throw new CryptoException(ERROR_KEY_IV_NOT_SET);
    }
    if (cipher == null) {
        cipher = createDefaultCipher();
    }

    try {
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));

        return cipher.doFinal(encrypted);
    } catch (GeneralSecurityException e) {
        throw new CryptoException(ERROR_KEY_DEC_ERROR, e);
    } finally {
        logger.debug(LOG_KEY_DEC_SUCCESSFUL);
    }
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.Cipherer.java

/**
* Initializes the encoder and decoder. // ww w  .j a  v a  2  s  .co m
* Note: The vaues of CIPHER_TRANSFORMATION, KEY_BYTES, KEY_ALGORITHM should be set before calling this method,
*       otherwise it will use the default values.
*/
public void init() {
    try {
        /*
                 byte[] nonce = new byte[16];
                 NONCE_GEN.nextBytes(nonce);
                 AlgorithmParameterSpec paramSpec = new IvParameterSpec(nonce);
        */
        AlgorithmParameterSpec paramSpec = cipherTransformation.toUpperCase().startsWith("AES")
                ? new IvParameterSpec(INIT_VECTOR_16)
                : new IvParameterSpec(INIT_VECTOR_8);

        E_CIPHER = Cipher.getInstance(cipherTransformation);
        D_CIPHER = Cipher.getInstance(cipherTransformation);

        SecretKeySpec spec = new SecretKeySpec(keyBytes, keyAlgorithm);

        // CBC requires an initialization vector
        E_CIPHER.init(Cipher.ENCRYPT_MODE, spec, paramSpec);
        D_CIPHER.init(Cipher.DECRYPT_MODE, spec, paramSpec);
    } catch (Exception e) {
        log.error("Cipher init failed", e);
        throw new RuntimeException(e);
    }
}

From source file:org.cogroo.addon.util.SecurityUtil.java

private byte[] decrypt(byte[] secretKey, byte[] encryptedText) {
    byte[] text = null;
    try {//from   w w w  .  j a  v a 2s. com
        Cipher aescf = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivspec = new IvParameterSpec(new byte[16]);
        aescf.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey, "AES"), ivspec);
        text = aescf.doFinal(encryptedText);

    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Should not happen", e);
    }

    return text;
}

From source file:com.miyue.util.Cryptos.java

/**
 * AES?, ?.// ww  w.  j  a  v  a 2  s. c o  m
 * 
 * @param input 
 * @param key ?AES?
 * @param iv ???
 * @param mode Cipher.ENCRYPT_MODE  Cipher.DECRYPT_MODE
 */
private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) {
    try {
        SecretKey secretKey = new SecretKeySpec(key, AES);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance(AES_CBC);
        cipher.init(mode, secretKey, ivSpec);
        return cipher.doFinal(input);
    } catch (GeneralSecurityException e) {
        throw Exceptions.unchecked(e);
    }
}

From source file:net.thewaffleshop.nimbus.api.EncryptionAPI.java

/**
 * Decrypt/*from w  w  w  .  ja  v  a2 s .com*/
 *
 * @param secretKey
 * @param iv
 * @param secret
 * @return
 */
public byte[] decrypt(SecretKey secretKey, byte[] iv, byte[] secret) {
    try {
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        byte[] ret = cipher.doFinal(secret);
        return ret;
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jumpmind.security.SecurityService.java

protected void initializeCipher(Cipher cipher, int mode) throws Exception {
    AlgorithmParameterSpec paramSpec = Cipher.getMaxAllowedParameterSpec(cipher.getAlgorithm());

    if (paramSpec instanceof PBEParameterSpec
            || (paramSpec == null && cipher.getAlgorithm().startsWith("PBE"))) {
        paramSpec = new PBEParameterSpec(SecurityConstants.SALT, SecurityConstants.ITERATION_COUNT);
        cipher.init(mode, secretKey, paramSpec);
    } else if (paramSpec instanceof IvParameterSpec) {
        paramSpec = new IvParameterSpec(SecurityConstants.SALT);
        cipher.init(mode, secretKey, paramSpec);
    } else {/*from  www .  j ava2 s .c o  m*/
        cipher.init(mode, secretKey, (AlgorithmParameterSpec) null);
    }
}

From source file:bobs.is.compress.sevenzip.AES256SHA256Decoder.java

@Override
InputStream decode(final String archiveName, final InputStream in, final long uncompressedLength,
        final Coder coder, final byte[] passwordBytes) throws IOException {
    return new InputStream() {
        private boolean isInitialized = false;
        private CipherInputStream cipherInputStream = null;

        private CipherInputStream init() throws IOException {
            if (isInitialized) {
                return cipherInputStream;
            }/*from   ww w .  j  a v  a2  s .  c o m*/
            final int byte0 = 0xff & coder.properties[0];
            final int numCyclesPower = byte0 & 0x3f;
            final int byte1 = 0xff & coder.properties[1];
            final int ivSize = ((byte0 >> 6) & 1) + (byte1 & 0x0f);
            final int saltSize = ((byte0 >> 7) & 1) + (byte1 >> 4);
            if (2 + saltSize + ivSize > coder.properties.length) {
                throw new IOException("Salt size + IV size too long in " + archiveName);
            }
            final byte[] salt = new byte[saltSize];
            System.arraycopy(coder.properties, 2, salt, 0, saltSize);
            final byte[] iv = new byte[16];
            System.arraycopy(coder.properties, 2 + saltSize, iv, 0, ivSize);

            if (passwordBytes == null) {
                throw new PasswordRequiredException(archiveName);
            }
            final byte[] aesKeyBytes;
            if (numCyclesPower == 0x3f) {
                aesKeyBytes = new byte[32];
                System.arraycopy(salt, 0, aesKeyBytes, 0, saltSize);
                System.arraycopy(passwordBytes, 0, aesKeyBytes, saltSize,
                        Math.min(passwordBytes.length, aesKeyBytes.length - saltSize));
            } else {
                final MessageDigest digest;
                try {
                    digest = MessageDigest.getInstance("SHA-256");
                } catch (final NoSuchAlgorithmException noSuchAlgorithmException) {
                    throw new IOException("SHA-256 is unsupported by your Java implementation",
                            noSuchAlgorithmException);
                }
                final byte[] extra = new byte[8];
                for (long j = 0; j < (1L << numCyclesPower); j++) {
                    digest.update(salt);
                    digest.update(passwordBytes);
                    digest.update(extra);
                    for (int k = 0; k < extra.length; k++) {
                        ++extra[k];
                        if (extra[k] != 0) {
                            break;
                        }
                    }
                }
                aesKeyBytes = digest.digest();
            }

            final SecretKey aesKey = new SecretKeySpec(aesKeyBytes, "AES");
            try {
                final Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
                cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
                cipherInputStream = new CipherInputStream(in, cipher);
                isInitialized = true;
                return cipherInputStream;
            } catch (final GeneralSecurityException generalSecurityException) {
                throw new IOException("Decryption error "
                        + "(do you have the JCE Unlimited Strength Jurisdiction Policy Files installed?)",
                        generalSecurityException);
            }
        }

        @Override
        public int read() throws IOException {
            return init().read();
        }

        @Override
        public int read(final byte[] b, final int off, final int len) throws IOException {
            return init().read(b, off, len);
        }

        @Override
        public void close() {
        }
    };
}