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.chililog.server.common.CryptoUtils.java

/**
 * <p>/*  w ww.j ava 2  s  . c  o  m*/
 * Decrypt an encrypted text string using TripleDES. The output is the plain text string.
 * </p>
 * 
 * @param encryptedText
 *            encrypted text returned by <code>encrypt</code>
 * @param password
 *            password used at the time of encryption
 * @return decrypted plain text string
 * @throws ChiliLogException
 */
public static String decryptTripleDES(String encryptedText, byte[] password) throws ChiliLogException {
    try {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest(password);
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        Base64 decoder = new Base64(1000, new byte[] {}, false);
        byte[] encryptedTextBytes = decoder.decode(encryptedText);

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        decipher.init(Cipher.DECRYPT_MODE, key, iv);
        final byte[] plainTextBytes = decipher.doFinal(encryptedTextBytes);

        return new String(plainTextBytes, "UTF-8");
    } catch (Exception ex) {
        throw new ChiliLogException(ex, "Error attempting to decrpt. " + ex.getMessage());
    }
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java

@Override
public boolean changePassphrase(String oldPassphrase, String newPassphrase) {
    SecretKeyFactory secretKeyFactory;

    File headerFileOld = new File(this.vaultPath + VAULT_HEADER_FILENAME);
    File headerFileNew = new File(this.vaultPath + VAULT_HEADER_FILENAME + "NEW");
    if (!headerFileNew.exists()) {
        try {/*from  ww w  . j  a  v a 2s  . com*/
            // Decrypt AES encryption key
            secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
            SecretKey oldKeyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(oldPassphrase.toCharArray(), vaultHeader.getSalt().toByteArray(),
                            vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT));
            Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
            c.init(Cipher.UNWRAP_MODE, oldKeyFromPassphrase,
                    new IvParameterSpec(vaultHeader.getVaultIV().toByteArray()));
            Key decryptedKey = c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM,
                    Cipher.SECRET_KEY);

            // Create new vault nonce and salt
            byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE];
            byte[] salt = new byte[SALT_SIZE_BYTE];
            secureRandom.nextBytes(vaultNonce);
            secureRandom.nextBytes(salt);

            int pbkdf2Iterations = generatePBKDF2IterationCount(newPassphrase, salt);

            // Create new key for AES key encryption
            SecretKey newKeyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(newPassphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT));

            writeVaultHeader(headerFileNew, vaultNonce, salt, pbkdf2Iterations, decryptedKey,
                    newKeyFromPassphrase);

        } catch (Exception e) {
            Util.log("Error while reading or creating new vault header!");
            return false;
        }
    } else {
        Util.log("New header file already exists. Cannot change passphrase!");
        return false;
    }

    // Try to parse new header file
    try {
        FileInputStream headerInputStream = new FileInputStream(headerFileNew);
        vaultHeader = VaultHeader.parseFrom(headerInputStream);
    } catch (Exception e) {
        Util.log("Cannot read vault header!");
        headerFileNew.delete();
        return false;
    }

    // Delete old header file and replace with new header file
    if (!headerFileOld.delete()) {
        headerFileNew.delete();
        Util.log("Cannot delete old vault header!");
        return false;
    }
    try {
        org.apache.commons.io.FileUtils.copyFile(headerFileNew, headerFileOld);
    } catch (IOException e) {
        Util.log("Cannot replace old vault header!");
        return false;
    }

    headerFileNew.delete();
    return true;
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipClientHandler.java

public void issueAppRequest(String body)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException {
    final String S_ProcName = "issueAppRequest";

    if (responseHandler == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Response handler must be set first by setResponseHandler()");
    }/*w w  w .j a  v  a 2  s  . co m*/

    if (serverInfo == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Server info must be queried first by requestServerInfo()");
    }

    if (sessionKey == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Session key must be set first by logging in");
    }

    if ((body == null) || (body.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1, "body");
    }

    SecureRandom random = new SecureRandom();
    byte iv[] = new byte[16];
    random.nextBytes(iv);
    byte[] base64IV = Base64.encodeBase64(iv);
    String stringIV = new String(base64IV);
    IvParameterSpec ivspec = new IvParameterSpec(iv);

    byte bodyBytes[] = body.getBytes();
    byte serverEncrypted[] = encryptWithSessionKey(ivspec, bodyBytes);
    byte base64Encrypted[] = Base64.encodeBase64(serverEncrypted);
    String encoded = new String(base64Encrypted);

    final String msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<CFTIPEnvelope\n"
            + "\t\txmlns=\"uri://net.sourceforge.msscodefactory/cftipenvelope\"\n"
            + "\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n"
            + "\t\txsi:schemaLocation=\"uri://net.sourceforge.msscodefactory/cftipenvelope file://xsd/cftip-envelope.xsd\" >\n"
            + "\t<AppRequest MessageIV=\"" + stringIV + "\" Payload=\"" + encoded + "\" />\n"
            + "</CFTIPEnvelope>\n";
    String response = sendReceive(msg);
    if ((response == null) || (response.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "response");
    }
    byte responseBytes[] = Base64.decodeBase64(response);
    byte decrypted[] = decryptWithSessionKey(ivspec, responseBytes);
    String decryptedResponse = new String(decrypted);
    responseHandler.parseStringContents(decryptedResponse);
}

From source file:com.microsoft.azure.storage.blob.CloudBlobClientEncryptionTests.java

@Test
public void testBlockBlobValidateEncryption() throws InvalidKeyException, NoSuchAlgorithmException,
        NoSuchPaddingException, StorageException, IOException, InvalidAlgorithmParameterException,
        URISyntaxException, InterruptedException, ExecutionException {
    int size = 5 * 1024 * 1024;
    byte[] buffer = TestHelper.getRandomBuffer(size);

    CloudBlockBlob blob = container.getBlockBlobReference("blob1");

    // Create the Key to be used for wrapping.
    SymmetricKey aesKey = TestHelper.getSymmetricKey();

    // Create the encryption policy to be used for upload.
    BlobEncryptionPolicy uploadPolicy = new BlobEncryptionPolicy(aesKey, null);

    // Set the encryption policy on the request options.
    BlobRequestOptions uploadOptions = new BlobRequestOptions();
    uploadOptions.setEncryptionPolicy(uploadPolicy);

    // Upload the encrypted contents to the blob.
    ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
    blob.upload(stream, size, null, uploadOptions, null);

    // Encrypt locally.
    String metadata = blob.getMetadata().get(Constants.EncryptionConstants.BLOB_ENCRYPTION_DATA);
    BlobEncryptionData encryptionData = BlobEncryptionData.deserialize(metadata);

    Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(encryptionData.getContentEncryptionIV());

    byte[] contentEncryptionKey = aesKey.unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(),
            encryptionData.getWrappedContentKey().getAlgorithm()).get();
    SecretKey keySpec = new SecretKeySpec(contentEncryptionKey, 0, contentEncryptionKey.length, "AES");

    myAes.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);

    CipherInputStream encryptedStream = new CipherInputStream(new ByteArrayInputStream(buffer), myAes);

    // Download the encrypted contents from the blob.
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    blob.download(outputStream);//from w  w w .  j a v  a  2s  .  co m

    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    for (int i = 0; i < outputStream.size(); i++) {
        assertEquals(encryptedStream.read(), inputStream.read());
    }

    encryptedStream.close();
}

From source file:com.guillaumesoft.escapehellprison.PurchaseActivity.java

public void requestPurchase(final Product product)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", product.getIdentifier());
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);/*from  ww w.j  a  va 2s  .  com*/
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(product.getIdentifier());

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }
    mOuyaFacade.requestPurchase(this, purchasable, new PurchaseListener(product));
}

From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java

/**
 * Decrypts the given input stream into the given output stream.
 *//*from   w w  w  . j  ava  2s  .c  o  m*/
protected void decrypt(InputStream in, OutputStream out) throws IOException {
    byte[] magic = new byte[FILE_MAGIC.length];
    IOUtils.read(in, magic);
    if (!Arrays.equals(magic, FILE_MAGIC)) {
        throw new IOException("Invalid file (bad magic)");
    }
    DataInputStream data = new DataInputStream(in);
    byte magicvers = data.readByte();
    if (magicvers != FILE_VERSION_1) {
        throw new IOException("Invalid file (bad version)");
    }

    byte usepb = data.readByte();
    if (usepb == USE_PBKDF2) {
        if (!usePBKDF2) {
            throw new NuxeoException("File requires PBKDF2 password");
        }
    } else if (usepb == USE_KEYSTORE) {
        if (usePBKDF2) {
            throw new NuxeoException("File requires keystore");
        }
    } else {
        throw new IOException("Invalid file (bad use)");
    }

    try {
        // secret key
        Key secret;
        if (usePBKDF2) {
            // read salt first
            int saltLen = data.readInt();
            if (saltLen <= 0 || saltLen > MAX_SALT_LEN) {
                throw new NuxeoException("Invalid salt length: " + saltLen);
            }
            byte[] salt = new byte[saltLen];
            data.read(salt, 0, saltLen);
            secret = generateSecretKey(salt);
        } else {
            secret = getSecretKey();
        }

        // read IV
        int ivLen = data.readInt();
        if (ivLen <= 0 || ivLen > MAX_IV_LEN) {
            throw new NuxeoException("Invalid IV length: " + ivLen);
        }
        byte[] iv = new byte[ivLen];
        data.read(iv, 0, ivLen);

        // cipher
        Cipher cipher;
        cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));

        // read the encrypted data
        try (InputStream cipherIn = new CipherInputStream(in, cipher)) {
            IOUtils.copy(cipherIn, out);
        } catch (IOException e) {
            Throwable cause = e.getCause();
            if (cause != null && cause instanceof BadPaddingException) {
                throw new NuxeoException(cause.getMessage(), e);
            }
        }
    } catch (GeneralSecurityException e) {
        throw new NuxeoException(e);
    }
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Decrypt string with RSA algorithm, ECB mode, OAEPWithSHA-256AndMGF1 padding
 * Asymmetric encryption, with private and public key
 *
 * @param string             string to decrypt
 * @param encryptionKeyBytes key from metadata
 * @return decrypted string//from w w  w .j a v a 2 s. co  m
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String decryptStringSymmetric(String string, byte[] encryptionKeyBytes)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance(AES_CIPHER);

    int delimiterPosition = string.lastIndexOf(ivDelimiter);
    String cipherString = string.substring(0, delimiterPosition);
    String ivString = string.substring(delimiterPosition + ivDelimiter.length(), string.length());

    byte[] iv = new IvParameterSpec(decodeStringToBase64Bytes(ivString)).getIV();

    Key key = new SecretKeySpec(encryptionKeyBytes, AES);

    GCMParameterSpec spec = new GCMParameterSpec(128, iv);
    cipher.init(Cipher.DECRYPT_MODE, key, spec);

    byte[] bytes = decodeStringToBase64Bytes(cipherString);
    byte[] encodedBytes = cipher.doFinal(bytes);

    return decodeBase64BytesToString(encodedBytes);
}

From source file:MegaHandler.java

public void download(String url, String path)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException {
    //TODO DOWNLOAD mismatch?
    print("Download started");
    String[] s = url.split("!");
    String file_id = s[1];//from   w ww  .j  a v a2 s.c  o m
    byte[] file_key = MegaCrypt.base64_url_decode_byte(s[2]);

    int[] intKey = MegaCrypt.aByte_to_aInt(file_key);
    JSONObject json = new JSONObject();
    try {
        json.put("a", "g");
        json.put("g", "1");
        json.put("p", file_id);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JSONObject file_data = new JSONObject(api_request(json.toString()));
    int[] keyNOnce = new int[] { intKey[0] ^ intKey[4], intKey[1] ^ intKey[5], intKey[2] ^ intKey[6],
            intKey[3] ^ intKey[7], intKey[4], intKey[5] };
    byte[] key = MegaCrypt.aInt_to_aByte(keyNOnce[0], keyNOnce[1], keyNOnce[2], keyNOnce[3]);

    int[] iiv = new int[] { keyNOnce[4], keyNOnce[5], 0, 0 };
    byte[] iv = MegaCrypt.aInt_to_aByte(iiv);

    @SuppressWarnings("unused")
    int file_size = file_data.getInt("s");
    String attribs = (file_data.getString("at"));
    attribs = new String(MegaCrypt.aes_cbc_decrypt(MegaCrypt.base64_url_decode_byte(attribs), key));

    String file_name = attribs.substring(10, attribs.lastIndexOf("\""));
    print(file_name);
    final IvParameterSpec ivSpec = new IvParameterSpec(iv);
    final SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES/CTR/nopadding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
    InputStream is = null;
    String file_url = file_data.getString("g");

    FileOutputStream fos = new FileOutputStream(path + File.separator + file_name);
    final OutputStream cos = new CipherOutputStream(fos, cipher);
    final Cipher decipher = Cipher.getInstance("AES/CTR/NoPadding");
    decipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
    int read = 0;
    final byte[] buffer = new byte[32767];
    try {

        URLConnection urlConn = new URL(file_url).openConnection();

        print(file_url);
        is = urlConn.getInputStream();
        while ((read = is.read(buffer)) > 0) {
            cos.write(buffer, 0, read);
        }
    } finally {
        try {
            cos.close();
            if (is != null) {
                is.close();
            }
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
    }
    print("Download finished");
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Make an IV for the AES encryption. This needs to be the same for both the
 * encryption and decryption and, if unspecified, the Cipher will make a new one
 * in each case - so the content won't be able to be decrypted. Use the first 
 * 16 bytes of the payload's manifest id as an IV.
 * // w w w.  j  a  v  a  2 s . c  om
 * @return IvParameter spec made from the data as described.
 * @throws Exception 
 */
private IvParameterSpec getInitialisationVector() throws Exception {
    byte[] iv = new byte[IVLENGTH];
    for (int i = 0; i < IVLENGTH; i++) {
        iv[i] = 0;
    }
    int j = (manifestId.startsWith("uuid")) ? 4 : 0;
    byte[] id = manifestId.getBytes("UTF-8");
    for (int i = 0; i < manifestId.length(); i++) {
        if (i == IVLENGTH)
            break;
        iv[i] = id[i + j];
    }
    return new IvParameterSpec(iv);
}

From source file:com.kactech.otj.Utils.java

public static String open(byte[] encryptedEnvelope, PrivateKey privateKey)
        throws InvalidKeyException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    String str;//from  w w  w .  j  a  v a2 s. c  o  m
    byte[] by;
    ByteBuffer buff = ByteBuffer.wrap(encryptedEnvelope);
    buff.order(ByteOrder.BIG_ENDIAN);
    int envType = buff.getShort();// expected 1(asymmetric)
    if (envType != 1)
        throw new UnsupportedOperationException("unexpected envelope type " + envType);
    int arraySize = buff.getInt();// can result in negative integer but not expecting it here
    if (arraySize != 1)//TODO
        throw new UnsupportedOperationException("current code doesn't support multi-nym response");
    byte[] encKeyBytes = null;
    byte[] vectorBytes = null;
    for (int i = 0; i < arraySize; i++) {
        int nymIDLen = buff.getInt();
        by = new byte[nymIDLen];
        buff.get(by);
        String nymID;
        try {
            nymID = new String(by, 0, by.length - 1, Utils.US_ASCII);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } // take nymID W/O trailing \0
          //TODO nymID matching!
        int keyLength = buff.getInt();
        encKeyBytes = new byte[keyLength];
        buff.get(encKeyBytes);
        int vectorLength = buff.getInt();
        vectorBytes = new byte[vectorLength];
        buff.get(vectorBytes);

    }
    byte[] encryptedMsg = new byte[buff.remaining()];
    buff.get(encryptedMsg);

    Cipher cipher;
    try {
        cipher = Cipher.getInstance(WRAP_ALGO);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.UNWRAP_MODE, privateKey);
    SecretKeySpec aesKey = (SecretKeySpec) cipher.unwrap(encKeyBytes, "AES", Cipher.SECRET_KEY);
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(vectorBytes));
    by = cipher.doFinal(encryptedMsg);
    try {
        str = new String(by, 0, by.length - 1, Utils.UTF8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } // w/o trailing \0
    return str;
}