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.fegor.alfresco.security.crypto.Crypto.java

/**
 * Decryption configuration//from w  w  w .jav a  2s .c o m
 * 
 * @param initvec
 * @param salt
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 */
public void configDecrypt(String initvec, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    salt_pos = Hex.decodeHex(salt.toCharArray());

    if (logger.isDebugEnabled())
        logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]");

    vector_init = Hex.decodeHex(initvec.toCharArray());
    if (logger.isDebugEnabled())
        logger.debug(
                this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]");

    /*
     * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files
     * .shtml
     */
    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS);

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

    deCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    deCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vector_init));
}

From source file:com.fujitsu.dc.common.auth.token.LocalToken.java

/**
 * ??./*from  www .jav  a 2  s .  co  m*/
 * @param in ?
 * @param ivBytes 
 * @return ???
 * @throws AbstractOAuth2Token.TokenParseException 
 */
public static String decode(final String in, final byte[] ivBytes)
        throws AbstractOAuth2Token.TokenParseException {
    byte[] inBytes = DcCoreUtils.decodeBase64Url(in);
    Cipher cipher;
    try {
        cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
    } catch (NoSuchAlgorithmException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    } catch (NoSuchPaddingException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    }
    try {
        cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(ivBytes));
    } catch (InvalidKeyException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    } catch (InvalidAlgorithmParameterException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    }
    byte[] plainBytes;
    try {
        plainBytes = cipher.doFinal(inBytes);
    } catch (IllegalBlockSizeException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    } catch (BadPaddingException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    }
    try {
        return new String(plainBytes, CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    }
}

From source file:io.personium.common.auth.token.LocalToken.java

/**
 * ??./*  www . ja v  a  2 s . co m*/
 * @param in ?
 * @param ivBytes 
 * @return ???
 * @throws AbstractOAuth2Token.TokenParseException 
 */
public static String decode(final String in, final byte[] ivBytes)
        throws AbstractOAuth2Token.TokenParseException {
    byte[] inBytes = PersoniumCoreUtils.decodeBase64Url(in);
    Cipher cipher;
    try {
        cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
    } catch (NoSuchAlgorithmException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    } catch (NoSuchPaddingException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    }
    try {
        cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(ivBytes));
    } catch (InvalidKeyException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    } catch (InvalidAlgorithmParameterException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    }
    byte[] plainBytes;
    try {
        plainBytes = cipher.doFinal(inBytes);
    } catch (IllegalBlockSizeException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    } catch (BadPaddingException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    }
    try {
        return new String(plainBytes, CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw AbstractOAuth2Token.PARSE_EXCEPTION;
    }
}

From source file:org.cryptomator.crypto.aes256.Aes256CryptorTest.java

License:asdf

@Test
public void foo() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
        NoSuchProviderException {
    Security.addProvider(new BouncyCastleProvider());

    final byte[] iv = new byte[16];
    final byte[] keyBytes = new byte[16];
    final SecretKey key = new SecretKeySpec(keyBytes, "AES");
    final Cipher pkcs5PaddedCipher = Cipher.getInstance("AES/CTR/PKCS5Padding",
            BouncyCastleProvider.PROVIDER_NAME);
    pkcs5PaddedCipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
    final Cipher unpaddedCipher = Cipher.getInstance("AES/CTR/NoPadding");
    unpaddedCipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));

    // test data:
    final byte[] plaintextData = "Hello World".getBytes();
    final byte[] pkcs5PaddedCiphertext = pkcs5PaddedCipher.doFinal(plaintextData);
    final byte[] unpaddedCiphertext = unpaddedCipher.doFinal(plaintextData);

    Assert.assertFalse(Arrays.equals(pkcs5PaddedCiphertext, unpaddedCiphertext));
}

From source file:org.alfresco.util.encryption.impl.AES256PasswordBasedEncrypter.java

/**
 * @see org.alfresco.util.encryption.Encrypter#decrypt(byte[])
 *///ww  w .ja va  2  s . c om
@Override
public String decrypt(final String encryptedText) throws CannotDecryptException {
    String result = null;
    long start = -1;
    long end = -1;

    if (log.isDebugEnabled())
        start = System.nanoTime();

    if (encryptedText != null) {
        try {
            byte[] encrypted = Base64.decodeBase64(encryptedText.getBytes(CHARACTER_ENCODING));
            String intermediate = new String(encrypted, CHARACTER_ENCODING);

            int separatorIndex = intermediate.indexOf(SEPARATOR);

            if (separatorIndex == -1) {
                throw new CannotDecryptException("Encrypted text " + intermediate + " is malformed.");
            }

            byte[] ivBase64 = intermediate.substring(0, separatorIndex).getBytes();
            byte[] iv = Base64.decodeBase64(ivBase64);
            byte[] cipherTextBase64 = intermediate.substring(separatorIndex + SEPARATOR.length()).getBytes();
            byte[] cipherText = Base64.decodeBase64(cipherTextBase64);

            Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
            result = new String(cipher.doFinal(cipherText), CHARACTER_ENCODING);
        } catch (final RuntimeException re) {
            throw re;
        } catch (final Exception e) {
            throw new CannotDecryptException("Unable to decrypt text: " + encryptedText, e);
        }
    }

    if (log.isDebugEnabled()) {
        end = System.nanoTime();
        long diff = end - start;
        double diffInMs = (double) diff / 1000000;
        log.debug("Decryption took " + String.valueOf(diffInMs) + "ms");
    }

    return (result);
}

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

/**
 * //from  w w w . j av  a  2 s.  com
 *
 * @param key
 *            SecretKey
 * @param data
 *            ?
 *
 * @return ?
 *
 */
public byte[] encrypt(SecretKey key, byte[] data) {

    if (key == null || data == null) {

        return null;

    }

    byte[] IV = getSecureRandom(IV_SIZE);

    IvParameterSpec IVSpec = new IvParameterSpec(IV);

    try {

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

    } catch (InvalidKeyException | InvalidAlgorithmParameterException ex) {

        log("?Cipher");

        ex.printStackTrace();

        return null;

    }

    byte[] cipher_bytes = null;

    try {

        cipher_bytes = cipher.doFinal(data);

    } catch (IllegalBlockSizeException | BadPaddingException ex) {

        log("?");

        ex.printStackTrace();

        return null;

    }

    byte[] iv_cipher_bytes = new byte[cipher_bytes.length + IV_SIZE];

    System.arraycopy(IV, 0, iv_cipher_bytes, 0, IV.length);

    System.arraycopy(cipher_bytes, 0, iv_cipher_bytes, IV.length, cipher_bytes.length);

    return iv_cipher_bytes;

}

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

private Cipher initCipher() throws ZipException {
    try {//  ww  w  . jav a 2s.  c  o  m
        Cipher iCipher = Cipher.getInstance(MigrationZipConstants.CIPHER_ALGORITHM);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(MigrationZipConstants.CIPHER_IV);
        SecretKey key = initKey(keyPath);
        iCipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
        return iCipher;
    } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException
            | InvalidAlgorithmParameterException e) {
        String message = String.format(MigrationZipConstants.KEY_INVALID_ERROR, keyPath, e);
        LOGGER.error(message);
        throw new ZipException(message);
    }
}

From source file:com.cyberninjas.xerobillableexpenses.util.Settings.java

private String decryptText(String cipherText) {
    try {/*from ww w.j  av a  2s  .c  om*/
        this.iv = prefs.getByteArray("DRUGS", null);
        if (this.iv == null)
            return "";
        byte[] cText = Base64.decodeBase64(cipherText);
        /* Decrypt the message, given derived key and initialization vector. */
        cipher.init(Cipher.DECRYPT_MODE, this.secret, new IvParameterSpec(this.iv));
        String ret = new String(cipher.doFinal(cText), "UTF-8");
        return ret;
    } catch (IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException
            | InvalidKeyException | InvalidAlgorithmParameterException ex) {
        Logger.getLogger(RSAx509CertGen.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

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

/**
 * Encrypts the data using the key//from  w  w  w . ja v a  2 s .c  o  m
 */
public byte[] encrypt(final byte[] inputData) {
    try {
        final Cipher cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
        cipher.init(Cipher.ENCRYPT_MODE, this.key, new IvParameterSpec(IVBYTES));
        return cipher.doFinal(inputData);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        LOGGER.error(UNEXPECTED_EXCEPTION_DURING_ENCRYPTION, e);
        throw new EncrypterException("Unexpected exception during encryption!", e);
    }
}

From source file:com.cl.roadshow.crypto.AESCtr.java

/**
 * Private decryption method.//w  w w.  jav a  2s  .  c  om
 * 
 * @param keystring
 * @param message
 * @param bits
 * @return bytearray containing decrypted message
 * @throws Exception
 */
private static byte[] decrypt(String keystring, byte[] message, int bits) throws Exception {
    byte[] decValue = null;
    byte[] nonceBytes = Arrays.copyOf(Arrays.copyOf(message, 8), 16);
    IvParameterSpec nonce = new IvParameterSpec(nonceBytes);

    Key key = generateKey(keystring, bits);
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.DECRYPT_MODE, key, nonce);
    decValue = c.doFinal(message, 8, message.length - 8);

    return decValue;
}