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.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

private static byte[] aes(byte[] data, byte[] bKey, Mode mode, boolean ecbMode) throws McbpCryptoException {
    final SecretKey secretKey = new SecretKeySpec(bKey, "AES");
    try {//from w  w w  .jav a2  s  .  c om
        byte[] iV = new byte[16];
        String blockType = "CBC";
        if (ecbMode) {
            blockType = "ECB";
        }
        Cipher cipher = Cipher.getInstance("AES/" + blockType + "/NoPadding");
        if (mode == Mode.ENCRYPT) {
            // Encrypt the data
            if (ecbMode) {
                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            } else {
                cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iV));
            }
        } else {
            // Decrypt the data
            if (ecbMode) {
                cipher.init(Cipher.DECRYPT_MODE, secretKey);
            } else {
                cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iV));
            }
        }
        return cipher.doFinal(data);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException
            | IllegalBlockSizeException | InvalidAlgorithmParameterException e) {
        throw new McbpCryptoException(e.toString());
    }
}

From source file:pt.lunacloud.services.storage.internal.crypto.EncryptionUtils.java

/**
 * Creates a symmetric cipher in the specified mode from the given symmetric key and IV.  The given
 * crypto provider will provide the encryption implementation.  If the crypto provider is null, then
 * the default JCE crypto provider will be used.
 *//* w  w w. j av a 2s  .com*/
public static Cipher createSymmetricCipher(SecretKey symmetricCryptoKey, int encryptMode,
        Provider cryptoProvider, byte[] initVector) {
    try {
        Cipher cipher;
        if (cryptoProvider != null) {
            cipher = Cipher.getInstance(JceEncryptionConstants.SYMMETRIC_CIPHER_METHOD, cryptoProvider);
        } else {
            cipher = Cipher.getInstance(JceEncryptionConstants.SYMMETRIC_CIPHER_METHOD);
        }
        if (initVector != null) {
            cipher.init(encryptMode, symmetricCryptoKey, new IvParameterSpec(initVector));
        } else {
            cipher.init(encryptMode, symmetricCryptoKey);
        }
        return cipher;
    } catch (Exception e) {
        throw new LunacloudClientException(
                "Unable to build cipher with the provided algorithm and padding: " + e.getMessage(), e);
    }
}

From source file:org.cesecore.keys.token.BaseCryptoToken.java

/**
 * This method extracts a PrivateKey from the keystore and wraps it, using a symmetric encryption key
 *
 * @param privKeyTransform - transformation algorithm
 * @param encryptionKeyAlias - alias of the symmetric key that will encrypt the private key
 * @param privateKeyAlias - alias for the PrivateKey to be extracted
 * @return byte[] with the encrypted extracted key
 * @throws NoSuchAlgorithmException if privKeyTransform is null, empty, in an invalid format, or if no Provider supports a CipherSpi
 *             implementation for the specified algorithm.
 * @throws NoSuchPaddingException if privKeyTransform contains a padding scheme that is not available.
 * @throws NoSuchProviderException if BouncyCastle is not registered in the security provider list.
 * @throws InvalidKeyException if the encryption key derived from encryptionKeyAlias was invalid.
 * @throws IllegalBlockSizeException if the Cipher created using privKeyTransform is a block cipher, no padding has been requested, and the length
 *             of the encoding of the key to be wrapped is not a multiple of the block size.
 * @throws CryptoTokenOfflineException if Crypto Token is not available or connected, or key with alias does not exist.
 * @throws InvalidAlgorithmParameterException if using CBC mode and the IV 0x0000000000000000 is not accepted.
 *///from www. j  a  v  a 2  s.com
public byte[] extractKey(String privKeyTransform, String encryptionKeyAlias, String privateKeyAlias)
        throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException,
        IllegalBlockSizeException, CryptoTokenOfflineException, PrivateKeyNotExtractableException,
        InvalidAlgorithmParameterException {
    IvParameterSpec ivParam = null;
    if (privKeyTransform.matches(".+\\/CBC\\/.+")) {
        byte[] cbcIv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        ivParam = new IvParameterSpec(cbcIv);
    }
    return extractKey(privKeyTransform, ivParam, encryptionKeyAlias, privateKeyAlias);
}

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

@Override
public void doApproval(int id, String userID, boolean approved, String reason) throws ProvisioningException {

    org.hibernate.Session session = this.sessionFactory.openSession();
    try {/*  w w  w .  j a va 2  s  .  c  om*/

        StringBuffer b = new StringBuffer();

        LDAPSearchResults res = this.cfgMgr.getMyVD().search(this.cfgMgr.getCfg().getLdapRoot(), 2,
                equal(this.userIDAttributeName, userID).toString(), new ArrayList<String>());
        if (!res.hasMore()) {
            throw new ProvisioningException("Could not locate approver '" + userID + "'");
        }

        LDAPEntry approver = res.next();

        AuthInfo auinfo = new AuthInfo();
        auinfo.setUserDN(approver.getDN());
        LDAPAttributeSet attrs = approver.getAttributeSet();
        for (Object obj : attrs) {
            LDAPAttribute attr = (LDAPAttribute) obj;

            Attribute attrib = new Attribute(attr.getName());
            String[] vals = attr.getStringValueArray();
            for (String val : vals) {
                attrib.getValues().add(val);
            }

            auinfo.getAttribs().put(attrib.getName(), attrib);
        }

        while (res.hasMore())
            res.next();

        Query query = session.createQuery("FROM Approvers WHERE userKey = :user_key");
        query.setParameter("user_key", userID);
        List<Approvers> approvers = query.list();
        Approvers approverObj = null;

        if (logger.isDebugEnabled()) {
            logger.debug("Approver UserID : " + userID);
        }

        int approverID;

        if (approvers.size() == 0) {

            approverObj = new Approvers();
            approverObj.setUserKey(userID);
            session.save(approverObj);

            approverID = approverObj.getId();
        } else {
            approverObj = approvers.get(0);
            approverID = approverObj.getId();
        }

        session.beginTransaction();

        boolean changed = false;

        for (String attrName : this.getApproverAttributes()) {

            boolean found = false;

            for (ApproverAttributes appAttr : approverObj.getApproverAttributeses()) {
                if (attrName.equalsIgnoreCase(appAttr.getName())) {
                    found = true;
                    LDAPAttribute approverAttr = approver.getAttribute(attrName);
                    if (approverAttr != null) {
                        if (!approverAttr.getStringValue().equals(appAttr.getValue())) {
                            appAttr.setValue(approverAttr.getStringValue());
                            session.save(appAttr);
                        }
                    }

                }
            }

            if (!found) {
                ApproverAttributes attr = new ApproverAttributes();
                attr.setName(attrName);
                LDAPAttribute approverAttr = approver.getAttribute(attrName);
                if (approverAttr != null) {
                    attr.setValue(approverAttr.getStringValue());
                }
                attr.setApprovers(approverObj);
                approverObj.getApproverAttributeses().add(attr);
                session.save(attr);
                changed = true;
            }

        }

        Approvals approvals = session.load(Approvals.class, id);

        if (approvals == null) {
            throw new ProvisioningException("Approval not found");
        }

        Gson gson = new Gson();
        String json = approvals.getWorkflowObj();
        Token token = gson.fromJson(json, Token.class);

        byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());

        IvParameterSpec spec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, this.cfgMgr
                .getSecretKey(this.cfgMgr.getCfg().getProvisioning().getApprovalDB().getEncryptionKey()), spec);

        byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());

        String jsonDecr = new String(cipher.doFinal(encBytes));

        Workflow wf = (Workflow) JsonReader.jsonToJava(jsonDecr);

        Approval approval = (Approval) wf.findCurrentApprovalTask();

        if (approval == null) {
            throw new ProvisioningException("Could not locate approval step");
        }

        AzSys az = new AzSys();

        for (AzRule rule : approval.getAzRules()) {
            if (rule.getCustomAuthorization() != null) {
                rule.getCustomAuthorization().loadConfigManager(cfgMgr);
                rule.getCustomAuthorization().setWorkflow(wf);
            }
        }

        if (!az.checkRules(auinfo, this.cfgMgr, approval.getAzRules(), wf.getRequest())) {
            throw new ProvisioningException("Az of approval failed");
        }

        DateTime now = new DateTime();

        approvals.setWorkflowObj(null);
        approvals.setApprovedTs(new Timestamp(now.getMillis()));
        approvals.setApprovers(approverObj);
        approvals.setApproved(approved ? 1 : 0);
        approvals.setReason(reason);

        session.save(approvals);

        wf.getRequest().put(Approval.APPROVAL_RESULT, new Boolean(approved));

        approval.markComplete(approved);

        if (approved) {
            wf.reInit(cfgMgr);
            wf.restart();
        } else {

            if (wf.getUserNum() != wf.getRequesterNum()) {
                wf.getRequester().getAttribs().put("reason", new Attribute("reason", reason));

                if (!wf.getRequester().getAttribs().containsKey(approval.getMailAttr())) {
                    logger.warn("Can not send failure notification to " + wf.getRequester().getUserID()
                            + ", no mail found");
                } else {
                    this.sendNotification(
                            wf.getRequester().getAttribs().get(approval.getMailAttr()).getValues().get(0),
                            approval.getFailureEmailMsg(), approval.getFailureEmailSubject(),
                            wf.getRequester());
                }
            }

            wf.getUser().getAttribs().put("reason", new Attribute("reason", reason));

            if (!wf.getUser().getAttribs().containsKey(approval.getMailAttr())) {
                logger.warn(
                        "Can not send failure notification to " + wf.getUser().getUserID() + ", no mail found");
            } else {
                this.sendNotification(wf.getUser().getAttribs().get(approval.getMailAttr()).getValues().get(0),
                        approval.getFailureEmailMsg(), approval.getFailureEmailSubject(), wf.getUser());
            }

            wf.reInit(cfgMgr);
            wf.restart();

        }

        session.getTransaction().commit();

    } catch (LDAPException e) {
        throw new ProvisioningException("Could not load approver", e);
    } catch (SQLException e) {
        throw new ProvisioningException("Could not load saved workflow", e);
    } catch (IOException e) {
        throw new ProvisioningException("Could not load saved workflow", e);
    } catch (ClassNotFoundException e) {
        throw new ProvisioningException("Could not load saved workflow", e);
    } catch (NoSuchAlgorithmException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (NoSuchPaddingException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (InvalidKeyException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (IllegalBlockSizeException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (BadPaddingException e) {
        throw new ProvisioningException("Could not decrypt workflow object", e);
    } catch (ProvisioningException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Exception running workflow", e);
        throw new ProvisioningException("Exception running workflow", e);
    } finally {
        if (session != null) {

            session.close();
        }
    }
}

From source file:com.borhan.client.BorhanClientBase.java

private byte[] aesEncrypt(String secretForSigning, byte[] text)
        throws GeneralSecurityException, UnsupportedEncodingException {
    // Key/*w w  w . j  a  va2 s.  co  m*/
    byte[] hashedKey = signInfoWithSHA1(secretForSigning);
    byte[] keyBytes = new byte[BLOCK_SIZE];
    System.arraycopy(hashedKey, 0, keyBytes, 0, BLOCK_SIZE);
    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");

    // IV
    byte[] ivBytes = new byte[BLOCK_SIZE];
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    // Text
    int textSize = ((text.length + BLOCK_SIZE - 1) / BLOCK_SIZE) * BLOCK_SIZE;
    byte[] textAsBytes = new byte[textSize];
    Arrays.fill(textAsBytes, (byte) 0);
    System.arraycopy(text, 0, textAsBytes, 0, text.length);

    // Encrypt
    Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    return cipher.doFinal(textAsBytes);
}

From source file:com.skplanet.syruppay.token.SyrupPayTokenBuilderTest.java

    _ERROR() throws Exception {
    final String keyFactorySalt = "65594821073030071593";
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
    SecretKeySpec secretKeySpec;/*w  w  w. jav  a2 s  .  c  o  m*/
    try {
        KeySpec spec = new PBEKeySpec("7244798e1fab1a9175f752a8a7e12beafe2cd27b208f9f2f7ab43173358153fc5eae2499afa66f7386d74cb8cf4765133c513ae2e6acd521acde4f80d747".toCharArray(), keyFactorySalt.getBytes(), 1, 256);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        SecretKey secretKey = secretKeyFactory.generateSecret(spec);
        secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
    } catch (Exception e) {
        throw e;
    }
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
    System.out.println(new String(cipher.doFinal(Base64.decodeBase64("yMvtcFwlhwBg22GF-biF4A".getBytes())), "UTF-8"));
}

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

private String decryptToken(String codeTokenKeyName, Gson gson, String encrypted) throws Exception {
    String inflated = this.inflate(encrypted);
    Token token = gson.fromJson(inflated, Token.class);

    byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());
    IvParameterSpec spec = new IvParameterSpec(iv);

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

    byte[] decBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());

    return new String(cipher.doFinal(decBytes));
}

From source file:org.opendedup.sdfs.filestore.cloud.BatchAwsS3ChunkStore.java

private String[] getStrings(S3Object sobj) throws IOException {
    this.s3clientLock.readLock().lock();
    try {/* www. ja v  a 2s . com*/
        boolean encrypt = false;
        boolean compress = false;
        boolean lz4compress = false;

        int cl = (int) sobj.getObjectMetadata().getContentLength();

        byte[] data = new byte[cl];
        DataInputStream in = null;
        try {
            in = new DataInputStream(sobj.getObjectContent());
            in.readFully(data);

        } catch (Exception e) {
            throw new IOException(e);
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
        Map<String, String> mp = this.getUserMetaData(sobj.getObjectMetadata());
        if (mp.containsKey("md5sum")) {
            try {
                byte[] shash = BaseEncoding.base64().decode(mp.get("md5sum"));
                byte[] chash;
                chash = ServiceUtils.computeMD5Hash(data);
                if (!Arrays.equals(shash, chash))
                    throw new IOException("download corrupt at " + sobj.getKey());
            } catch (NoSuchAlgorithmException e) {
                throw new IOException(e);
            }
        }
        int size = Integer.parseInt((String) mp.get("size"));
        if (mp.containsKey("encrypt")) {
            encrypt = Boolean.parseBoolean((String) mp.get("encrypt"));
        }
        if (mp.containsKey("compress")) {
            compress = Boolean.parseBoolean((String) mp.get("compress"));
        } else if (mp.containsKey("lz4compress")) {

            lz4compress = Boolean.parseBoolean((String) mp.get("lz4compress"));
        }
        byte[] ivb = null;
        if (mp.containsKey("ivspec"))
            ivb = BaseEncoding.base64().decode(mp.get("ivspec"));
        if (encrypt) {
            if (ivb != null)
                data = EncryptUtils.decryptCBC(data, new IvParameterSpec(ivb));
            else
                data = EncryptUtils.decryptCBC(data);
        }
        if (compress)
            data = CompressionUtils.decompressZLIB(data);
        else if (lz4compress) {
            data = CompressionUtils.decompressLz4(data, size);
        }
        String hast = new String(data);
        SDFSLogger.getLog().debug("reading hashes " + (String) mp.get("hashes") + " from " + sobj.getKey());
        String[] st = hast.split(",");
        return st;
    } finally {
        this.s3clientLock.readLock().unlock();
    }
}

From source file:com.edduarte.protbox.core.registry.PReg.java

public byte[] decrypt(byte[] encryptedData, boolean hasChecksum) throws ProtboxException {
    try {/*from  ww w  .j ava2s  .  co  m*/
        byte[] dataToDecrypt;

        int checksumLength = hasChecksum ? 64 : 0;

        if (pair.getPairAlgorithm().contains("CBC")) {
            byte[] iv = new byte[16];
            System.arraycopy(encryptedData, checksumLength, iv, 0, 16);

            int dataToDecryptLength = encryptedData.length - checksumLength - 16;
            dataToDecrypt = new byte[dataToDecryptLength];
            System.arraycopy(encryptedData, checksumLength + 16, dataToDecrypt, 0, dataToDecryptLength);

            CIPHER.init(Cipher.DECRYPT_MODE, pair.getPairKey(), new IvParameterSpec(iv));

        } else {
            int dataToDecryptLength = encryptedData.length - checksumLength;
            dataToDecrypt = new byte[dataToDecryptLength];
            System.arraycopy(encryptedData, checksumLength, dataToDecrypt, 0, dataToDecryptLength);

            CIPHER.init(Cipher.DECRYPT_MODE, pair.getPairKey());
        }

        byte[] result = CIPHER.doFinal(dataToDecrypt);
        boolean isValid = true;

        if (hasChecksum) {
            byte[] fileCheckSum = new byte[checksumLength];
            System.arraycopy(encryptedData, 0, fileCheckSum, 0, checksumLength);

            Mac mac = Mac.getInstance("HmacSHA512");
            mac.init(pair.getIntegrityKey());
            byte[] integrityControlValue = mac.doFinal(result);

            isValid = Arrays.equals(fileCheckSum, integrityControlValue);
        }

        if (isValid) {
            return result;

        } else {
            throw new ProtboxException("Protected file contains invalid checksum.");
        }

    } catch (GeneralSecurityException ex) {
        throw new ProtboxException(ex);
    }
}

From source file:org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.java

private static byte[] computeHash2B(byte[] input, byte[] password, byte[] userKey) throws IOException {
    try {//from  w  ww.ja  v a2 s. co  m
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] k = md.digest(input);

        byte[] e = null;
        for (int round = 0; round < 64 || ((int) e[e.length - 1] & 0xFF) > round - 32; round++) {
            byte[] k1;
            if (userKey != null && userKey.length >= 48) {
                k1 = new byte[64 * (password.length + k.length + 48)];
            } else {
                k1 = new byte[64 * (password.length + k.length)];
            }

            int pos = 0;
            for (int i = 0; i < 64; i++) {
                System.arraycopy(password, 0, k1, pos, password.length);
                pos += password.length;
                System.arraycopy(k, 0, k1, pos, k.length);
                pos += k.length;
                if (userKey != null && userKey.length >= 48) {
                    System.arraycopy(userKey, 0, k1, pos, 48);
                    pos += 48;
                }
            }

            byte[] kFirst = new byte[16];
            byte[] kSecond = new byte[16];
            System.arraycopy(k, 0, kFirst, 0, 16);
            System.arraycopy(k, 16, kSecond, 0, 16);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(kFirst, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(kSecond);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            e = cipher.doFinal(k1);

            byte[] eFirst = new byte[16];
            System.arraycopy(e, 0, eFirst, 0, 16);
            BigInteger bi = new BigInteger(1, eFirst);
            BigInteger remainder = bi.mod(new BigInteger("3"));
            String nextHash = HASHES_2B[remainder.intValue()];

            md = MessageDigest.getInstance(nextHash);
            k = md.digest(e);
        }

        if (k.length > 32) {
            byte[] kTrunc = new byte[32];
            System.arraycopy(k, 0, kTrunc, 0, 32);
            return kTrunc;
        } else {
            return k;
        }
    } catch (GeneralSecurityException e) {
        logIfStrongEncryptionMissing();
        throw new IOException(e);
    }
}