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.launchkey.sdk.crypto.JCECrypto.java

private byte[] processAES(int mode, byte[] message, byte[] key, byte[] iv) throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance(AES_CRYPTO_CIPHER, provider);
    cipher.init(mode, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
    byte[] out = cipher.doFinal(message);
    return new String(out).trim().getBytes();
}

From source file:om.edu.squ.squportal.portlet.dps.security.CryptoAES.java

/**
* 
* method name  : doFinal/*from  w w w .j  a va 2 s. com*/
* @param encryptMode
* @param key
* @param iv
* @param bytes
* @return
* CryptoAES
* return type  : byte[]
* 
* purpose      :
*
* Date          :   Nov 15, 2017 7:28:27 PM
*/
private byte[] doFinal(int encryptMode, SecretKey key, String iv, byte[] bytes) {
    byte[] byteFinal = null;
    try {
        cipher.init(encryptMode, key, new IvParameterSpec(hex(iv)));
        byteFinal = cipher.doFinal(bytes);
    } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException
            | BadPaddingException e) {
        logger.error(":: Crypto Error :: Error in final. Details : {}", e.getMessage());
    }
    return byteFinal;
}

From source file:Networking.Server.java

public byte[] encryptMessage() {
    byte[] cipherText = null;
    byte[] text = null;
    try {/*from w w  w.  j  a v  a 2 s.c  o  m*/

        byte[] plainText = message.getBytes();

        SecretKeySpec myKey;
        myKey = new SecretKeySpec(this.d.getSessionKey(), "AES");

        SecureRandom random = new SecureRandom();
        byte randombytes[] = new byte[16];
        random.nextBytes(randombytes);
        this.d.setIv(randombytes);

        IvParameterSpec iv = new IvParameterSpec(this.d.getIv());
        Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, myKey, iv);
        cipherText = new byte[c.getOutputSize(plainText.length)];
        c.doFinal(plainText, 0, plainText.length, cipherText);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(iv.getIV());
        outputStream.write((cipherText));
        text = outputStream.toByteArray();

        File ivMsgFile = new File("./write_iv.txt");
        if (ivMsgFile.createNewFile()) {
            System.out.println("File is created!");
        }

        FileOutputStream sigfos = new FileOutputStream(ivMsgFile);
        sigfos.write(text);
        sigfos.flush();
        sigfos.close();

        byte[] sig_bytes = new byte[(int) ivMsgFile.length()];
        BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(ivMsgFile));
        bis1.read(sig_bytes, 0, sig_bytes.length);

        sendMesLen((int) ivMsgFile.length());
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println("sent time: " + timestamp);
        Socket writeSocket = new Socket(Ip, port);
        writeSocket.getOutputStream().write(sig_bytes, 0, sig_bytes.length);
        writeSocket.getOutputStream().flush();
        writeSocket.close();

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException | ShortBufferException | IllegalBlockSizeException
            | BadPaddingException | IOException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    }
    return Base64.encodeBase64(text);
}

From source file:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java

private Association loadFromHandle(String handle)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, IOException, InvalidAlgorithmParameterException {
    byte[] encodedHandle = Base64.decodeBase64(handle);
    if (null != this.macSecretKeySpec) {
        byte[] signature = new byte[32];
        System.arraycopy(encodedHandle, 0, signature, 0, 32);
        byte[] toBeSigned = new byte[encodedHandle.length - 32];
        System.arraycopy(encodedHandle, 32, toBeSigned, 0, encodedHandle.length - 32);
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(this.macSecretKeySpec);
        byte[] actualSignature = mac.doFinal(toBeSigned);
        if (false == Arrays.equals(actualSignature, signature)) {
            return null;
        }// w w  w  .j a v a 2s  .  com
        encodedHandle = toBeSigned;
    }
    byte[] iv = new byte[16];
    System.arraycopy(encodedHandle, 0, iv, 0, iv.length);
    byte[] encodedData = Arrays.copyOfRange(encodedHandle, 16, encodedHandle.length);
    Cipher cipher = Cipher.getInstance(CIPHER_ALGO);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, this.secretKeySpec, ivParameterSpec);
    byte[] associationBytes = cipher.doFinal(encodedData);
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(associationBytes);
    int typeByte = byteArrayInputStream.read();
    if (typeByte == 1) {
        byte[] macKeyBytes = new byte[160 / 8];
        byteArrayInputStream.read(macKeyBytes);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        long exp = dataInputStream.readLong();
        Date expDate = new Date(exp);
        return Association.createHmacSha1(handle, macKeyBytes, expDate);
    } else if (typeByte == 2) {
        byte[] macKeyBytes = new byte[256 / 8];
        byteArrayInputStream.read(macKeyBytes);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        long exp = dataInputStream.readLong();
        Date expDate = new Date(exp);
        return Association.createHmacSha256(handle, macKeyBytes, expDate);
    } else {
        return null;
    }
}

From source file:com.microsoft.azure.storage.table.TableEncryptionPolicy.java

/**
 * Return an encrypted entity. This method is used for encrypting entity properties.
 *//*from  www .  j a v  a  2  s .c o m*/
Map<String, EntityProperty> encryptEntity(Map<String, EntityProperty> properties, String partitionKey,
        String rowKey, EncryptionResolver encryptionResolver) throws StorageException {
    Utility.assertNotNull("properties", properties);

    // The Key should be set on the policy for encryption. Otherwise, throw an error.
    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

    EncryptionData encryptionData = new EncryptionData();
    encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1,
            EncryptionAlgorithm.AES_CBC_256));

    try {
        Map<String, EntityProperty> encryptedProperties = new HashMap<String, EntityProperty>();
        HashSet<String> encryptionPropertyDetailsSet = new HashSet<String>();

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

        // Wrap key
        Pair<byte[], String> encryptedKey = this.keyWrapper
                .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get();
        encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(),
                encryptedKey.getKey(), encryptedKey.getValue()));

        encryptionData.setContentEncryptionIV(myAes.getIV());

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        for (Map.Entry<String, EntityProperty> kvp : properties.entrySet()) {
            if (encryptionResolver != null
                    && encryptionResolver.encryptionResolver(partitionKey, rowKey, kvp.getKey())) {
                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity case
                // where a user adds a new property as follows - ent.Properties.Add("foo2", null);
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                kvp.getValue().setIsEncrypted(true);
            }

            // IsEncrypted is set to true when either the EncryptPropertyAttribute is set on a property or when it is 
            // specified in the encryption resolver or both.
            if (kvp.getValue() != null && kvp.getValue().isEncrypted()) {
                // Throw if users try to encrypt non-string properties.
                if (kvp.getValue().getEdmType() != EdmType.STRING) {
                    throw new IllegalArgumentException(String
                            .format(SR.UNSUPPORTED_PROPERTY_TYPE_FOR_ENCRYPTION, kvp.getValue().getEdmType()));
                }

                byte[] columnIVFull = digest
                        .digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                                (partitionKey + rowKey + kvp.getKey()).getBytes(Constants.UTF8_CHARSET)));

                byte[] columnIV = new byte[16];
                System.arraycopy(columnIVFull, 0, columnIV, 0, 16);
                myAes.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(columnIV));

                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity or POCO
                // case when the property value is null.
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                byte[] src = kvp.getValue().getValueAsString().getBytes(Constants.UTF8_CHARSET);
                byte[] dest = myAes.doFinal(src, 0, src.length);

                // Store the encrypted properties as binary values on the service instead of base 64 encoded strings because strings are stored as a sequence of 
                // WCHARs thereby further reducing the allowed size by half. During retrieve, it is handled by the response parsers correctly 
                // even when the service does not return the type for JSON no-metadata.
                encryptedProperties.put(kvp.getKey(), new EntityProperty(dest));
                encryptionPropertyDetailsSet.add(kvp.getKey());
            } else {
                encryptedProperties.put(kvp.getKey(), kvp.getValue());
            }

            // Encrypt the property details set and add it to entity properties.
            byte[] metadataIVFull = digest.digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                    (partitionKey + rowKey + Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS)
                            .getBytes(Constants.UTF8_CHARSET)));

            byte[] metadataIV = new byte[16];
            System.arraycopy(metadataIVFull, 0, metadataIV, 0, 16);
            myAes.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(metadataIV));

            byte[] src = Arrays.toString(encryptionPropertyDetailsSet.toArray())
                    .getBytes(Constants.UTF8_CHARSET);
            byte[] dest = myAes.doFinal(src, 0, src.length);
            encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS,
                    new EntityProperty(dest));
        }

        encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS,
                new EntityProperty(encryptionData.serialize()));

        return encryptedProperties;
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:org.slc.sli.bulk.extract.files.ExtractFileTest.java

private static File decrypt(File file) throws Exception {
    byte[] responseData = FileUtils.readFileToByteArray(file);

    byte[] encodediv = Arrays.copyOfRange(responseData, 0, 256);
    byte[] encodedsecret = Arrays.copyOfRange(responseData, 256, 512);
    byte[] message = Arrays.copyOfRange(responseData, 512, responseData.length);

    Cipher decrypt = Cipher.getInstance("RSA");
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(PRIVATE_KEY.getBytes()));
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    decrypt.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] iv = decrypt.doFinal(encodediv);
    byte[] secret = decrypt.doFinal(encodedsecret);

    decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec key = new SecretKeySpec(secret, "AES");
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    decrypt.init(Cipher.DECRYPT_MODE, key, ivSpec);

    byte[] unencryptedMessage = decrypt.doFinal(message);

    File decryptedTar = new File("decrypted-" + FILE_NAME + FILE_EXT);

    FileUtils.writeByteArrayToFile(decryptedTar, unencryptedMessage);

    return decryptedTar;

}

From source file:org.picketbox.json.enc.JSONWebEncryption.java

/**
 * Decrypt using a {@link PrivateKey}// w  w  w  .  ja va2  s . com
 *
 * @param encryptedText
 * @param privateKey
 * @return
 * @throws ProcessingException
 */
public String decrypt(String encryptedText, PrivateKey privateKey) throws ProcessingException {
    if (privateKey == null) {
        throw PicketBoxJSONMessages.MESSAGES.invalidNullArgument("privateKey");
    }
    try {
        String[] splitBits = encryptedText.split("\\.");
        int length = splitBits.length;
        String encodedHeader = splitBits[0];
        String encodedKey = splitBits[1];
        String encodedValue = splitBits[2];
        String encodedIntegrity = null;
        if (length == 4) {
            encodedIntegrity = splitBits[3];
        }

        String decodedHeader = new String(Base64.decode(encodedHeader));
        JSONWebEncryptionHeader header = new JSONWebEncryptionHeader();
        header.load(decodedHeader);

        if (header.needIntegrity()) {

            byte[] decodedKey = Base64.decode(encodedKey);

            byte[] secretKey = decryptKey(privateKey, decodedKey);

            int cekLength = header.getCEKLength();
            byte[] cek = generateCEK(secretKey, cekLength);

            // Deal with IV
            String iv;
            try {
                iv = header.getDelegate().getString("iv");
            } catch (JSONException e) {
                throw PicketBoxJSONMessages.MESSAGES.ignorableError(e);
            }

            IvParameterSpec ivParameter = new IvParameterSpec(iv.getBytes());

            byte[] decodedText = Base64.decode(encodedValue);
            byte[] plainText = EncUtil.decryptUsingAES_CBC(decodedText, cek, ivParameter);

            int cikLength = header.getCIKLength();
            byte[] cik = generateCIK(secretKey, cikLength);

            StringBuilder builder = new StringBuilder(PicketBoxJSONUtil.b64Encode(header.toString()));
            builder.append(PERIOD).append(encodedKey).append(PERIOD).append(encodedValue);

            byte[] integrityValue = performMac(cik, builder.toString().getBytes());
            String encodedIntegrityValue = PicketBoxJSONUtil.b64Encode(integrityValue);

            if (byteEquals(encodedIntegrityValue.getBytes(), encodedIntegrity.getBytes())) {
                return new String(plainText);
            } else {
                throw new RuntimeException("Integrity Checks Failed");
            }
        }

        Cipher textCipher = header.getCipherBasedOnAlg();
        textCipher.init(Cipher.DECRYPT_MODE, privateKey);

        byte[] decodedText = Base64.decode(encodedValue);
        byte[] plainText = textCipher.doFinal(decodedText);

        return new String(plainText);
    } catch (Exception e) {
        throw PicketBoxJSONMessages.MESSAGES.processingException(e);
    }
}

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

public void encrypt(InputStream in, OutputStream out)
        throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException,
        BadPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(jcrypto.getAlgorithm());
    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 ava2s .  c o m
        cipher.init(Cipher.ENCRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()));
    }

    CipherOutputStream cos = new CipherOutputStream(out, cipher);

    byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        cos.write(buffer, 0, bytesRead);
        cos.flush();
    }
    cos.close();

    java.util.Arrays.fill(buffer, (byte) 0);
}

From source file:Networking.Client.java

public void decryptMessage(String received, int len) {
    try {//from  w  ww  .ja  va2s . co  m
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println("received time: " + timestamp);
        Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
        loadIVAndMsg(len);
        SecretKeySpec myKey = new SecretKeySpec(this.node.getSessionKey(), "AES");
        this.node.setIv(iv);
        IvParameterSpec iv = new IvParameterSpec(this.node.getIv());
        c.init(Cipher.DECRYPT_MODE, myKey, iv);
        byte[] recoveredText = c.doFinal(msg);
        writer.write(new String(recoveredText));
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchPaddingException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.parelon.pskc.CryptManager.java

/**
 * Returns the ciphered HMAC-SHA1 Key./*w  w  w  .j  a  v  a 2  s.  com*/
 *
 * @return Ciphered HMAC-SHA1 key: to be Base64-encoded
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException
 */
public byte[] getAesCipheredMacKey() throws InvalidKeyException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException, Base64DecodingException, NoSuchAlgorithmException {
    byte[] Iv = new byte[16];
    randomize.nextBytes(Iv);
    this.cipherParamSpec = new IvParameterSpec(Iv);
    this.aesCipher.init(Cipher.ENCRYPT_MODE, this.aesKey, cipherParamSpec);
    byte[] encryptedMacKey = this.aesCipher.doFinal(this.macKey.getEncoded());
    return concatByteArrays(Iv, encryptedMacKey);
}