Example usage for javax.crypto Cipher getIV

List of usage examples for javax.crypto Cipher getIV

Introduction

In this page you can find the example usage for javax.crypto Cipher getIV.

Prototype

public final byte[] getIV() 

Source Link

Document

Returns the initialization vector (IV) in a new buffer.

Usage

From source file:com.microsoft.azure.storage.queue.QueueEncryptionPolicy.java

/**
 * Return an encrypted base64 encoded message along with encryption related metadata given a plain text message.
 * /*from ww w  .  ja  v a 2s.c  o m*/
 * @param inputMessage
 *            The input message in bytes.
 * @return The encrypted message that will be uploaded to the service.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
String encryptMessage(byte[] inputMessage) throws StorageException {
    Utility.assertNotNull("inputMessage", inputMessage);

    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

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

    try {
        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()));

        encryptedMessage.setEncryptedMessageContents(
                new String(Base64.encode(myAes.doFinal(inputMessage, 0, inputMessage.length))));

        encryptionData.setContentEncryptionIV(myAes.getIV());
        encryptedMessage.setEncryptionData(encryptionData);
        return encryptedMessage.serialize();
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

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

/**
 * Return an encrypted entity. This method is used for encrypting entity properties.
 *//*  w ww.java2 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:com.tremolosecurity.proxy.SessionManagerImpl.java

private HttpSession createSession(ApplicationType app, HttpServletRequest req, HttpServletResponse resp,
        ServletContext ctx, SecretKey encKey) throws Exception {

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);//  w ww . j ava2s. co  m

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    // HttpSession session = req.getSession(true);
    TremoloHttpSession tsession = new TremoloHttpSession(id);
    tsession.setAppName(app.getName());
    tsession.refresh(this.ctx, this);
    tsession.setOpen(false);
    this.anonMech.createSession(tsession, this.anonChainType);

    AuthController actl = (AuthController) tsession.getAttribute(ProxyConstants.AUTH_CTL);

    AuthInfo auInfo = actl.getAuthInfo();
    auInfo.setAuthComplete(true);

    // session.setAttribute(app.getCookieConfig().getSessionCookieName(),
    // tsession);

    tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id);
    tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout());

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, encKey);

    byte[] encSessionKey = cipher.doFinal(id.getBytes("UTF-8"));
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encSessionKey));

    Token token = new Token();
    token.setEncryptedRequest(base64d);
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

    Gson gson = new Gson();

    String cookie = gson.toJson(token);

    byte[] btoken = cookie.getBytes("UTF-8");
    String encCookie = new String(org.bouncycastle.util.encoders.Base64.encode(btoken));

    Cookie sessionCookie;

    sessionCookie = new Cookie(app.getCookieConfig().getSessionCookieName(), encCookie);

    // logger.debug("session size : " +
    // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length);
    String domain = ProxyTools.getInstance().getCookieDomain(app.getCookieConfig(), req);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(-1);
    sessionCookie.setSecure(app.getCookieConfig().isSecure());
    sessionCookie.setHttpOnly(app.getCookieConfig().isHttpOnly() != null && app.getCookieConfig().isHttpOnly());
    resp.addCookie(sessionCookie);

    // delete the opensession if it exists
    if (cfg.getCfg().getApplications().getOpenSessionCookieName() != null
            && !cfg.getCfg().getApplications().getOpenSessionCookieName().isEmpty()) {
        Cookie openSessionCookie = new Cookie(cfg.getCfg().getApplications().getOpenSessionCookieName(), id);

        openSessionCookie.setPath("/");
        openSessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure());
        openSessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly());
        openSessionCookie.setMaxAge(0);
        resp.addCookie(openSessionCookie);
    }

    sessions.put(id, tsession);

    return tsession;
}

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

/**
 * Set up the encryption context required for encrypting blobs.
 * @param metadata/*from ww w .  jav  a  2s .  com*/
 *          Reference to blob metadata object that is used to set the encryption materials.
 * @param noPadding
 *          Value indicating if the padding mode should be set or not.
 * @return The Cipher to use to decrypt the blob.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
Cipher createAndSetEncryptionContext(Map<String, String> metadata, boolean noPadding) throws StorageException {
    Utility.assertNotNull("metadata", metadata);

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

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

        Cipher myAes;
        if (noPadding) {
            myAes = Cipher.getInstance("AES/CBC/NoPadding");
        } else {
            myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        }

        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

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

        // 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());

        metadata.put(Constants.EncryptionConstants.BLOB_ENCRYPTION_DATA, encryptionData.serialize());
        return myAes;
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:com.joyent.manta.http.EncryptionHttpHelper.java

/**
 * Adds headers related directly to the encrypted object being stored.
 *
 * @param metadata Manta metadata object
 * @param cipher cipher used to encrypt the object and metadata
 * @throws IOException thrown when unable to append metadata
 *///from   www. jav  a2  s.  co  m
public void attachEncryptedEntityHeaders(final MantaMetadata metadata, final Cipher cipher) throws IOException {
    Validate.notNull(metadata, "Metadata object must not be null");
    Validate.notNull(cipher, "Cipher object must not be null");

    // IV Used to Encrypt
    byte[] iv = cipher.getIV();
    Validate.notNull(iv, "Cipher IV must not be null");

    String ivBase64 = Base64.getEncoder().encodeToString(iv);
    metadata.put(MantaHttpHeaders.ENCRYPTION_IV, ivBase64);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("IV: {}", Hex.encodeHexString(cipher.getIV()));
    }

    // AEAD Tag Length if AEAD Cipher
    if (cipherDetails.isAEADCipher()) {
        metadata.put(MantaHttpHeaders.ENCRYPTION_AEAD_TAG_LENGTH,
                String.valueOf(cipherDetails.getAuthenticationTagOrHmacLengthInBytes()));
        LOGGER.debug("AEAD tag length: {}", cipherDetails.getAuthenticationTagOrHmacLengthInBytes());
        // HMAC Type because we are doing MtE
    } else {
        HMac hmac = cipherDetails.getAuthenticationHmac();
        final String hmacName = SupportedHmacsLookupMap.hmacNameFromInstance(hmac);
        metadata.put(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE, hmacName);
        LOGGER.debug("HMAC algorithm: {}", hmacName);
    }
}

From source file:com.joyent.manta.http.EncryptionHttpHelper.java

/**
 * Attaches encrypted metadata (with e-* values) to the object.
 *
 * @param metadata metadata to append additional values to
 * @throws IOException thrown when there is a problem attaching metadata
 *//*from ww  w. j av  a2  s  .  co  m*/
public void attachEncryptedMetadata(final MantaMetadata metadata) throws IOException {

    // Create and add encrypted metadata
    Cipher metadataCipher = buildMetadataEncryptCipher();

    metadata.put(MantaHttpHeaders.ENCRYPTION_CIPHER, cipherDetails.getCipherId());

    String metadataIvBase64 = Base64.getEncoder().encodeToString(metadataCipher.getIV());
    metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA_IV, metadataIvBase64);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Encrypted metadata IV: {}", Hex.encodeHexString(metadataCipher.getIV()));
    }

    String metadataPlainTextString = EncryptedMetadataUtils.encryptedMetadataAsString(metadata);
    LOGGER.debug("Encrypted metadata plaintext:\n{}", metadataPlainTextString);
    LOGGER.debug("Encrypted metadata ciphertext: {}", metadataIvBase64);

    byte[] metadataCipherText = encryptMetadata(metadataPlainTextString, metadataCipher);
    String metadataCipherTextBase64 = Base64.getEncoder().encodeToString(metadataCipherText);

    if (metadataCipherTextBase64.length() > MAX_METADATA_CIPHERTEXT_BASE64_SIZE) {
        String msg = "Encrypted metadata exceeded the maximum size allowed";
        MantaClientEncryptionException e = new MantaClientEncryptionException(msg);
        e.setContextValue("max_size", MAX_METADATA_CIPHERTEXT_BASE64_SIZE);
        e.setContextValue("actual_size", metadataCipherTextBase64.length());
        throw e;
    }

    metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA, metadataCipherTextBase64);

    if (!this.cipherDetails.isAEADCipher()) {
        final HMac hmac = this.cipherDetails.getAuthenticationHmac();
        initHmac(this.secretKey, hmac);

        hmac.update(metadataCipherText, 0, metadataCipherText.length);

        byte[] checksum = new byte[hmac.getMacSize()];
        hmac.doFinal(checksum, 0);

        String checksumBase64 = Base64.getEncoder().encodeToString(checksum);
        metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA_HMAC, checksumBase64);

        LOGGER.debug("Encrypted metadata HMAC: {}", checksumBase64);
    } else {
        metadata.put(MantaHttpHeaders.ENCRYPTION_METADATA_AEAD_TAG_LENGTH,
                String.valueOf(this.cipherDetails.getAuthenticationTagOrHmacLengthInBytes()));
    }
}

From source file:pro.hirooka.streaming_server_for_multiple_platforms.Encrypter.java

@SuppressWarnings("resource")
public void run() {

    SingletonForSSFMP info = null;// w  w w  .  j  av a  2 s.c  o  m
    SingletonForSSFMP2 info2 = null;
    SingletonForSSFMP3 info3 = null;

    switch (abs) {
    case 0:
        info = SingletonForSSFMP.getInstance();
        break;
    case 1:
        info2 = SingletonForSSFMP2.getInstance();
        break;
    case 2:
        info3 = SingletonForSSFMP3.getInstance();
        break;
    default:
        //info = SingletonForMyStreamer.getInstance();
        break;
    }

    int seqTsEnc = 0; //info.getSeqTsEnc();
    if (!modeLive.equals("capturedTimeShifted")) {
        if ((abs == 0) && (info != null)) {
            seqTsEnc = info.getSeqTsEnc();
        } else if ((abs == 1) && (info2 != null)) {
            seqTsEnc = info2.getSeqTsEnc();
        } else if ((abs == 2) && (info3 != null)) {
            seqTsEnc = info3.getSeqTsEnc();
        }
    } else if (modeLive.equals("capturedTimeShifted")) {
        if ((abs == 0) && (info != null)) {
            seqTsEnc = info.getSeqTsCapturedTimeShifted();
        } else if ((abs == 1) && (info2 != null)) {
            seqTsEnc = info2.getSeqTsCapturedTimeShifted();
        } else if ((abs == 2) && (info3 != null)) {
            seqTsEnc = info3.getSeqTsCapturedTimeShifted();
        }
    }

    if ((abs == 0) && (info != null) && info.getFlagLastTs()) {
        seqTsEnc = info.getSeqTsLast();
    } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) {
        seqTsEnc = info2.getSeqTsLast();
    } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) {
        seqTsEnc = info3.getSeqTsLast();
    }

    log.debug(MARKER_Encrypter, "{} Begin : Encryption of seqTsEnc : {}",
            Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc);

    Key sKey;
    Cipher c;
    FileOutputStream keyOut;
    FileWriter ivOut;
    FileInputStream fis;
    BufferedInputStream bis;
    FileOutputStream fos;
    CipherOutputStream cos;

    try {

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        sKey = makeKey(128); // Key length is 128bit
        c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        //         log.debug(MARKER_Encrypter, "{} [c.getAlgorithm()] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), c.getAlgorithm());
        c.init(Cipher.ENCRYPT_MODE, sKey);

        // Set Key File Name at random
        String keyPre = RandomStringUtils.randomAlphabetic(10);
        keyOut = new FileOutputStream(streamPath + FILE_SEPARATOR + keyPre + seqTsEnc + ".key");

        if ((abs == 0) && (info != null)) {
            info.addKeyArrayList(keyPre);
        } else if ((abs == 1) && (info2 != null)) {
            info2.addKeyArrayList(keyPre);
        } else if ((abs == 2) && (info3 != null)) {
            info3.addKeyArrayList(keyPre);
        }

        byte[] keyOutByte = sKey.getEncoded();
        keyOut.write(keyOutByte);
        keyOut.close();

        byte[] iv = c.getIV();
        //         log.debug(MARKER_Encrypter, "{} [iv.length] {} [byte]", Thread.currentThread().getStackTrace()[1].getMethodName(), iv.length);

        String ivHex = "";
        for (int i = 0; i < iv.length; i++) {
            String ivHexTmp = String.format("%02x", iv[i]).toUpperCase();
            ivHex = ivHex + ivHexTmp;
        }

        String ivPre = RandomStringUtils.randomAlphabetic(10);
        ivOut = new FileWriter(streamPath + FILE_SEPARATOR + ivPre + seqTsEnc + ".iv");
        ivOut.write(ivHex);
        ivOut.close();

        //         log.debug(MARKER_Encrypter, "{} [iv] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), ivHex);

        if ((abs == 0) && (info != null)) {
            info.addIvArrayList(ivHex);
        } else if ((abs == 1) && (info2 != null)) {
            info2.addIvArrayList(ivHex);
        } else if ((abs == 2) && (info3 != null)) {
            info3.addIvArrayList(ivHex);
        }

        fis = new FileInputStream(TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequence" + seqTsEnc + ".ts");
        bis = new BufferedInputStream(fis);
        fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts");
        cos = new CipherOutputStream(fos, c);
        if (modeLive.equals("capturedTimeShifted")) {
            fis = new FileInputStream(
                    TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequenceEncoded" + seqTsEnc + ".ts");
            bis = new BufferedInputStream(fis);
            fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts");
            cos = new CipherOutputStream(fos, c);
        }

        byte[] buf = new byte[TS_PACKET_LENGTH];

        int ch;
        while ((ch = bis.read(buf)) != -1) {
            cos.write(buf, 0, ch);
        }
        cos.close();
        fos.close();
        bis.close();
        fis.close();

        log.debug(MARKER_Encrypter, "{} End : Encryption of seqTsEnc : {}",
                Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc);

        if ((abs == 0) && (info != null) && info.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        }

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } // try
}

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

private String encryptToken(String codeTokenKeyName, Gson gson, UUID refreshToken)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
    byte[] bjson = refreshToken.toString().getBytes("UTF-8");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE,
            GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(codeTokenKeyName));

    byte[] encJson = cipher.doFinal(bjson);
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson));

    Token token = new Token();
    token.setEncryptedRequest(base64d);//from   w w  w . j  ava 2 s .  c o  m
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

    byte[] bxml = gson.toJson(token).getBytes("UTF-8");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
            new Deflater(Deflater.BEST_COMPRESSION, true));

    compressor.write(bxml);
    compressor.flush();
    compressor.close();

    String b64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray()));
    return b64;
}

From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

@Override
public EncryptedMessage encryptObject(Object o) throws ProvisioningException {
    SecretKey key = this.cfgMgr
            .getSecretKey(this.cfgMgr.getCfg().getProvisioning().getQueueConfig().getEncryptionKeyName());
    if (key == null) {
        throw new ProvisioningException("Queue message encryption key not found");
    }//from w  w w . j a va  2s . co  m

    try {
        String json = JsonWriter.objectToJson(o);

        EncryptedMessage msg = new EncryptedMessage();

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        msg.setMsg(cipher.doFinal(json.getBytes("UTF-8")));
        msg.setIv(cipher.getIV());
        return msg;
    } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | IllegalBlockSizeException | BadPaddingException e) {
        throw new ProvisioningException("Could not encrypt message", e);
    }

}

From source file:pt.lunacloud.services.storage.AmazonS3EncryptionClient.java

@Override
public InitiateMultipartUploadResult initiateMultipartUpload(
        InitiateMultipartUploadRequest initiateMultipartUploadRequest)
        throws LunacloudClientException, LunacloudServiceException {

    appendUserAgent(initiateMultipartUploadRequest, USER_AGENT);

    // Generate a one-time use symmetric key and initialize a cipher to encrypt object data
    SecretKey envelopeSymmetricKey = EncryptionUtils.generateOneTimeUseSymmetricKey();
    Cipher symmetricCipher = EncryptionUtils.createSymmetricCipher(envelopeSymmetricKey, Cipher.ENCRYPT_MODE,
            cryptoConfig.getCryptoProvider(), null);

    if (cryptoConfig.getStorageMode() == CryptoStorageMode.ObjectMetadata) {
        EncryptionMaterials encryptionMaterials = encryptionMaterialsProvider.getEncryptionMaterials();
        // Encrypt the envelope symmetric key
        byte[] encryptedEnvelopeSymmetricKey = EncryptionUtils.getEncryptedSymmetricKey(envelopeSymmetricKey,
                encryptionMaterials, cryptoConfig.getCryptoProvider());

        // Store encryption info in metadata
        ObjectMetadata metadata = EncryptionUtils.updateMetadataWithEncryptionInfo(
                initiateMultipartUploadRequest, encryptedEnvelopeSymmetricKey, symmetricCipher,
                encryptionMaterials.getMaterialsDescription());

        // Update the request's metadata to the updated metadata
        initiateMultipartUploadRequest.setObjectMetadata(metadata);
    }//ww w .j a  v a2s. c  om

    InitiateMultipartUploadResult result = super.initiateMultipartUpload(initiateMultipartUploadRequest);
    EncryptedUploadContext encryptedUploadContext = new EncryptedUploadContext(
            initiateMultipartUploadRequest.getBucketName(), initiateMultipartUploadRequest.getKey(),
            envelopeSymmetricKey);
    encryptedUploadContext.setNextInitializationVector(symmetricCipher.getIV());
    encryptedUploadContext.setFirstInitializationVector(symmetricCipher.getIV());
    currentMultipartUploadSecretKeys.put(result.getUploadId(), encryptedUploadContext);

    return result;
}