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:de.petendi.commons.crypto.HybridCrypto.java

public byte[] decrypt(HybridEncrypted encrypted, String recipientIdentifier, char[] password,
        InputStream pkcs12Stream) {
    byte[] encryptedPassphrase = encrypted.getRecipients().get(recipientIdentifier);
    try {//from  w w w  . j  a  va  2  s .c  o  m
        ArrayList<byte[]> splitted = retrieveSecretAndIV(encryptedPassphrase, password, pkcs12Stream);
        Cipher cipher = Cipher.getInstance(SYMMETRIC_CIPHER_ALGORITHM);
        SecretKey originalKey = new SecretKeySpec(splitted.get(1), 0, splitted.get(1).length, "AES");
        cipher.init(Cipher.DECRYPT_MODE, originalKey, new IvParameterSpec(splitted.get(0)));
        return cipher.doFinal(encrypted.getEncryptedBody());
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:hjow.hgtable.util.SecurityUtil.java

/**
 * <p>? ?  ?? ? .</p>//from  ww  w.jav a 2  s .c om
 * 
 * @param text : ? ?
 * @param key : ? ? 
 * @param algorithm : ? ?   (null  AES  )
 * @return ?? ?
 */
public static String decrypt(String text, String key, String algorithm) {
    try {
        String passwords = hash(key, null);
        String methods = algorithm;
        if (methods == null)
            methods = "AES";

        String paddings;
        int need_keySize = -1;
        boolean useIv = false;

        byte[] befores = text.getBytes("UTF-8");
        byte[] keyByte = passwords.getBytes("UTF-8");

        if (methods.equalsIgnoreCase("DES")) {
            paddings = "DES/CBC/PKCS5Padding";
            need_keySize = 8;
            useIv = true;
        } else if (methods.equalsIgnoreCase("DESede")) {
            paddings = "TripleDES/ECB/PKCS5Padding";
            need_keySize = 168;
            useIv = true;
        } else if (methods.equalsIgnoreCase("AES")) {
            paddings = "AES";
            need_keySize = 16;
            useIv = false;
        } else
            return null;

        befores = Base64.decodeBase64(befores);

        byte[] checkKeyByte = new byte[need_keySize];
        byte[] ivBytes = new byte[checkKeyByte.length];
        for (int i = 0; i < checkKeyByte.length; i++) {
            if (i < keyByte.length) {
                checkKeyByte[i] = keyByte[i];
            } else {
                checkKeyByte[i] = 0;
            }
        }
        keyByte = checkKeyByte;

        SecretKeySpec keySpec = new SecretKeySpec(keyByte, methods);
        IvParameterSpec ivSpec = null;
        if (useIv)
            ivSpec = new IvParameterSpec(ivBytes);

        Cipher cipher = null;

        try {
            cipher = Cipher.getInstance(paddings);
            if (useIv) {
                cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            } else {
                cipher.init(Cipher.DECRYPT_MODE, keySpec);
            }
            byte[] outputs = new byte[cipher.getOutputSize(befores.length)];
            for (int i = 0; i < outputs.length; i++) {
                outputs[i] = 0;
            }
            int enc_len = cipher.update(befores, 0, befores.length, outputs, 0);
            enc_len = enc_len + cipher.doFinal(outputs, enc_len);

            return new String(outputs, "UTF-8").trim();
        } catch (Throwable e) {
            Main.logError(e, Manager.applyStringTable("On decryption"));
            return text;
        }
    } catch (Throwable e) {

    }
    return null;
}

From source file:it.doqui.index.ecmengine.business.personalization.encryption.content.DecryptingContentReaderDecorator.java

public InputStream getContentInputStream() throws ContentIOException {
    logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] BEGIN");

    IvParameterSpec iv = null;//from w  w w  .j a  va 2s . c  om

    try {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec),
                    "SunJCE");
        } catch (NoSuchProviderException e) {
            logger.warn(
                    "[DecryptingContentReaderDecorator::getContentInputStream] Unknown provider \"SunJCE\". Using default...");
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec));
        }

        if (transformationSpec.getMode() != null && !transformationSpec.getMode().equalsIgnoreCase("ECB")) {
            iv = new IvParameterSpec(transformationSpec.getIv());
            logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] IvParameterSpec: " + iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
        }

        logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] "
                + "Cipher initialized: DECRYPT - " + cipher.getProvider() + " - " + cipher.getAlgorithm());

        CipherInputStream cis = new CipherInputStream(reader.getContentInputStream(), cipher);
        return cis;
    } catch (NoSuchPaddingException e) {
        logger.warn("[DecryptingContentReaderDecorator::getContentInputStream] Invalid padding: "
                + transformationSpec.getPadding());
        throw new EncryptionRuntimeException("Invalid padding: " + transformationSpec.getPadding(), e);
    } catch (NoSuchAlgorithmException e) {
        logger.warn("[DecryptingContentReaderDecorator::getContentInputStream] Invalid algorithm: "
                + transformationSpec.getAlgorithm());
        throw new EncryptionRuntimeException("Invalid algorithm: " + transformationSpec.getAlgorithm(), e);
    } catch (InvalidKeyException e) {
        logger.warn("[DecryptingContentReaderDecorator::getContentInputStream] Invalid key!");
        throw new EncryptionRuntimeException("Invalid key!", e);
    } catch (InvalidAlgorithmParameterException e) {
        logger.warn(
                "[DecryptingContentReaderDecorator::getContentInputStream] Invalid algorithm parameter: " + iv);
        throw new EncryptionRuntimeException("Invalid algorithm parameter: " + iv, e);
    } finally {
        logger.debug("[DecryptingContentReaderDecorator::getContentInputStream] END");
    }
}

From source file:edu.tamu.tcat.crypto.bouncycastle.SecureTokenImpl.java

private Cipher createCipher(int mode, byte[] iv) throws TokenException {
    try {//from  ww w. jav  a 2 s  .c  om
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding",
                Activator.getDefault().getBouncyCastleProvider());
        cipher.init(mode, key, new IvParameterSpec(iv));
        return cipher;
    } catch (NoSuchPaddingException e) {
        throw new TokenException("Missing algorithm", e);
    } catch (InvalidKeyException e) {
        throw new TokenException("Invalid Key (maybe you need to install the Java Cryptography Extension?)", e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new TokenException("Invalid parameter (bad IV?)", e);
    } catch (NoSuchAlgorithmException e) {
        throw new TokenException("Missing algorithm", e);
    }
}

From source file:mobisocial.musubi.nearby.GpsBroadcastTask.java

@Override
protected Void doInBackground(Void... params) {
    if (DBG)/*from w  w  w .  j a  v a 2 s.  c  o m*/
        Log.d(TAG, "Uploading group for nearby gps...");
    while (!mmLocationScanComplete) {
        synchronized (mmLocationResult) {
            if (!mmLocationScanComplete) {
                try {
                    if (DBG)
                        Log.d(TAG, "Waiting for location results...");
                    mmLocationResult.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    }
    if (DBG)
        Log.d(TAG, "Got location " + mmLocation);
    if (isCancelled()) {
        return null;
    }

    try {
        SQLiteOpenHelper db = App.getDatabaseSource(mContext);
        FeedManager fm = new FeedManager(db);
        IdentitiesManager im = new IdentitiesManager(db);
        String group_name = UiUtil.getFeedNameFromMembersList(fm, mFeed);
        byte[] group_capability = mFeed.capability_;
        List<MIdentity> owned = im.getOwnedIdentities();
        MIdentity sharer = null;
        for (MIdentity i : owned) {
            if (i.type_ != Authority.Local) {
                sharer = i;
                break;
            }
        }
        String sharer_name = UiUtil.safeNameForIdentity(sharer);
        byte[] sharer_hash = sharer.principalHash_;

        byte[] thumbnail = fm.getFeedThumbnailForId(mFeed.id_);
        if (thumbnail == null)
            thumbnail = im.getMusubiThumbnail(sharer) != null ? sharer.musubiThumbnail_
                    : im.getThumbnail(sharer);
        int member_count = fm.getFeedMemberCount(mFeed.id_);

        JSONObject group = new JSONObject();
        group.put("group_name", group_name);
        group.put("group_capability", Base64.encodeToString(group_capability, Base64.DEFAULT));
        group.put("sharer_name", sharer_name);
        group.put("sharer_type", sharer.type_.ordinal());
        group.put("sharer_hash", Base64.encodeToString(sharer_hash, Base64.DEFAULT));
        if (thumbnail != null)
            group.put("thumbnail", Base64.encodeToString(thumbnail, Base64.DEFAULT));
        group.put("member_count", member_count);

        byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes());
        byte[] data = group.toString().getBytes();
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);

        byte[] partial_enc_data;
        Cipher cipher;
        AlgorithmParameterSpec iv_spec;
        SecretKeySpec sks;
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        } catch (Exception e) {
            throw new RuntimeException("AES not supported on this platform", e);
        }
        try {
            iv_spec = new IvParameterSpec(iv);
            sks = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, sks, iv_spec);
        } catch (Exception e) {
            throw new RuntimeException("bad iv or key", e);
        }
        try {
            partial_enc_data = cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException("body encryption failed", e);
        }

        TByteArrayList bal = new TByteArrayList(iv.length + partial_enc_data.length);
        bal.add(iv);
        bal.add(partial_enc_data);
        byte[] enc_data = bal.toArray();

        if (DBG)
            Log.d(TAG, "Posting to gps server...");

        Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/sharegroup");

        StringBuffer sb = new StringBuffer();
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(uri.toString());
        httpPost.addHeader("Content-Type", "application/json");
        JSONArray buckets = new JSONArray();
        JSONObject descriptor = new JSONObject();

        double lat = mmLocation.getLatitude();
        double lng = mmLocation.getLongitude();
        long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2);
        for (long c : coords) {
            MessageDigest md;
            try {
                byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes();
                md = MessageDigest.getInstance("SHA-256");
                ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length);
                b.putLong(c);
                b.put(obfuscate);
                String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT);
                buckets.put(buckets.length(), secret_bucket);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("your platform does not support sha256", e);
            }
        }
        descriptor.put("buckets", buckets);
        descriptor.put("data", Base64.encodeToString(enc_data, Base64.DEFAULT));
        descriptor.put("expiration", new Date().getTime() + 1000 * 60 * 60);

        httpPost.setEntity(new StringEntity(descriptor.toString()));
        try {
            HttpResponse execute = client.execute(httpPost);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                if (isCancelled()) {
                    return null;
                }
                sb.append(s);
            }
            if (sb.toString().equals("ok"))
                mSucceeded = true;
            else {
                System.err.println(sb);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //TODO: report failures etc
    } catch (Exception e) {
        Log.e(TAG, "Failed to broadcast group", e);
    }
    return null;
}

From source file:org.apache.shindig.common.crypto.Crypto.java

/**
 * AES-128-CBC decryption with a particular IV.
 * /*  w  ww  .jav a  2 s  .  c o m*/
 * @param key decryption key
 * @param iv initial vector for decryption
 * @param cipherText cipher text to decrypt
 * @param offset offset into cipher text to begin decryption
 * 
 * @return the plain text
 * 
 * @throws GeneralSecurityException
 */
public static byte[] aes128cbcDecryptWithIv(byte[] key, byte[] iv, byte[] cipherText, int offset)
        throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
    Key cipherKey = new SecretKeySpec(key, CIPHER_KEY_TYPE);
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, cipherKey, ivSpec);
    return cipher.doFinal(cipherText, offset, cipherText.length - offset);
}

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

License:asdf

public byte[] testDESedeDe(byte[] encryptedText) {
    try {// w w  w .  j  a 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.DECRYPT_MODE, theKey, IvParameters);

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

From source file:gobblin.crypto.RotatingAESCodecTest.java

private void manuallyDecodeAndVerifyBytes(byte[] originalBytes, byte[] encryptedBytes,
        SimpleCredentialStore credStore) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    // Manually decode
    InputStream in = new ByteArrayInputStream(encryptedBytes);
    verifyKeyId(in, 1);/*from w  ww .  java2 s. c o  m*/

    Integer ivLen = verifyIvLen(in);

    byte[] ivBinary = verifyAndExtractIv(in, ivLen);

    byte[] body = readAndBase64DecodeBody(in);

    // feed back into cipheroutput stream
    Cipher inputCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBinary);
    inputCipher.init(Cipher.DECRYPT_MODE, credStore.getKey(), ivParameterSpec);

    CipherInputStream cis = new CipherInputStream(new ByteArrayInputStream(body), inputCipher);
    byte[] decoded = IOUtils.toByteArray(cis);
    Assert.assertEquals(decoded, originalBytes, "Expected decoded output to match encoded output");
}

From source file:net.seleucus.wsp.crypto.FwknopSymmetricCrypto.java

public static String decrypt(byte[] key, String ciphertext)
        throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    if (!ciphertext.startsWith(FWKNOP_ENCRYPTION_HEADER)) {
        ciphertext = FWKNOP_ENCRYPTION_HEADER.concat(ciphertext);
    }//from  w  w w  .java  2  s.  c  o  m
    // we need to remove Salted__ from the salt_and_ciphertext therefore -> SALT_LEN +/- 8

    byte[] salt_and_ciphertext = Base64.decodeBase64(ciphertext);
    byte[] salt = new byte[SALT_LEN];
    byte[] cipher = new byte[salt_and_ciphertext.length - SALT_LEN - 8];
    System.arraycopy(salt_and_ciphertext, 8, salt, 0, SALT_LEN);
    System.arraycopy(salt_and_ciphertext, 8 + SALT_LEN, cipher, 0, cipher.length);
    byte[][] key_and_iv = deriveKeyAndIV(salt, key);

    SecretKeySpec enc_key;
    enc_key = new SecretKeySpec(key_and_iv[0], "AES");
    Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec iv = new IvParameterSpec(key_and_iv[1]);
    aes.init(Cipher.DECRYPT_MODE, enc_key, iv);
    byte[] plain = aes.doFinal(cipher);

    return new String(plain, "UTF-8");
}

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

public byte[] decrypt(byte[] data)
        throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        IllegalBlockSizeException, BadPaddingException, IOException, InvalidAlgorithmParameterException {
    Cipher cipher = getCipherInstance();
    if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES);
        cipher.init(Cipher.DECRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec);
    } else {//  w w w. j  ava2 s .  com
        cipher.init(Cipher.DECRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()));
    }

    byte[] bData = null;
    if (jcrypto.isApplyBase64()) {

        //byte[] temp = new sun.misc.BASE64Decoder().decodeBuffer(new String(   data));
        byte[] temp = Base64.decodeBase64(data);
        bData = temp;
    } else {
        bData = data;
    }

    return cipher.doFinal(bData);

}