Search in sources :

Example 6 with PBES2Parameters

use of com.github.zhenwei.core.asn1.pkcs.PBES2Parameters in project xipki by xipki.

the class PbmMacCmpCaClient method decrypt.

private byte[] decrypt(EncryptedValue ev) throws Exception {
    AlgorithmIdentifier symmAlg = ev.getSymmAlg();
    if (!PKCSObjectIdentifiers.id_PBES2.equals(symmAlg.getAlgorithm())) {
        throw new Exception("unsupported symmAlg " + symmAlg.getAlgorithm().getId());
    }
    PBES2Parameters alg = PBES2Parameters.getInstance(symmAlg.getParameters());
    PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
    AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
    ASN1ObjectIdentifier encSchemaAlgOid = encScheme.getAlgorithm();
    int keysizeInBit;
    if (NISTObjectIdentifiers.id_aes128_GCM.equals(encSchemaAlgOid)) {
        keysizeInBit = 128;
    } else if (NISTObjectIdentifiers.id_aes192_GCM.equals(encSchemaAlgOid)) {
        keysizeInBit = 192;
    } else if (NISTObjectIdentifiers.id_aes256_GCM.equals(encSchemaAlgOid)) {
        keysizeInBit = 256;
    } else {
        throw new Exception("unsupported encryption scheme " + encSchemaAlgOid.getId());
    }
    SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId());
    SecretKey key;
    int iterations = func.getIterationCount().intValue();
    key = keyFact.generateSecret(new PBKDF2KeySpec(password, func.getSalt(), iterations, keysizeInBit, func.getPrf()));
    key = new SecretKeySpec(key.getEncoded(), "AES");
    String cipherAlgOid = alg.getEncryptionScheme().getAlgorithm().getId();
    Cipher cipher = Cipher.getInstance(cipherAlgOid);
    ASN1Encodable encParams = alg.getEncryptionScheme().getParameters();
    GCMParameters gcmParameters = GCMParameters.getInstance(encParams);
    GCMParameterSpec gcmParamSpec = new GCMParameterSpec(gcmParameters.getIcvLen() * 8, gcmParameters.getNonce());
    cipher.init(Cipher.DECRYPT_MODE, key, gcmParamSpec);
    return cipher.doFinal(ev.getEncValue().getOctets());
}
Also used : PBES2Parameters(org.bouncycastle.asn1.pkcs.PBES2Parameters) GCMParameterSpec(javax.crypto.spec.GCMParameterSpec) PBKDF2KeySpec(org.bouncycastle.jcajce.spec.PBKDF2KeySpec) CMPException(org.bouncycastle.cert.cmp.CMPException) CRMFException(org.bouncycastle.cert.crmf.CRMFException) InvalidKeyException(java.security.InvalidKeyException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) SecretKey(javax.crypto.SecretKey) GCMParameters(org.bouncycastle.asn1.cms.GCMParameters) SecretKeySpec(javax.crypto.spec.SecretKeySpec) PBKDF2Params(org.bouncycastle.asn1.pkcs.PBKDF2Params) Cipher(javax.crypto.Cipher) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) SecretKeyFactory(javax.crypto.SecretKeyFactory) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 7 with PBES2Parameters

use of com.github.zhenwei.core.asn1.pkcs.PBES2Parameters in project LinLong-Java by zhenwei1108.

the class BcFKSKeyStoreSpi method engineSetKeyEntry.

public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException {
    Date creationDate = new Date();
    Date lastEditDate = creationDate;
    ObjectData entry = (ObjectData) entries.get(alias);
    if (entry != null) {
        creationDate = extractCreationDate(entry, creationDate);
    }
    privateKeyCache.remove(alias);
    if (key instanceof PrivateKey) {
        if (chain == null) {
            throw new KeyStoreException("BCFKS KeyStore requires a certificate chain for private key storage.");
        }
        try {
            // check that the key pair and the certificate public are consistent
            // TODO: new ConsistentKeyPair(chain[0].getPublicKey(), (PrivateKey)key);
            byte[] encodedKey = key.getEncoded();
            KeyDerivationFunc pbkdAlgId = generatePkbdAlgorithmIdentifier(PKCSObjectIdentifiers.id_PBKDF2, 256 / 8);
            byte[] keyBytes = generateKey(pbkdAlgId, "PRIVATE_KEY_ENCRYPTION", ((password != null) ? password : new char[0]), 32);
            EncryptedPrivateKeyInfo keyInfo;
            if (storeEncryptionAlgorithm.equals(NISTObjectIdentifiers.id_aes256_CCM)) {
                Cipher c = createCipher("AES/CCM/NoPadding", keyBytes);
                byte[] encryptedKey = c.doFinal(encodedKey);
                AlgorithmParameters algParams = c.getParameters();
                PBES2Parameters pbeParams = new PBES2Parameters(pbkdAlgId, new EncryptionScheme(NISTObjectIdentifiers.id_aes256_CCM, CCMParameters.getInstance(algParams.getEncoded())));
                keyInfo = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, pbeParams), encryptedKey);
            } else {
                Cipher c = createCipher("AESKWP", keyBytes);
                byte[] encryptedKey = c.doFinal(encodedKey);
                PBES2Parameters pbeParams = new PBES2Parameters(pbkdAlgId, new EncryptionScheme(NISTObjectIdentifiers.id_aes256_wrap_pad));
                keyInfo = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, pbeParams), encryptedKey);
            }
            EncryptedPrivateKeyData keySeq = createPrivateKeySequence(keyInfo, chain);
            entries.put(alias, new ObjectData(PRIVATE_KEY, alias, creationDate, lastEditDate, keySeq.getEncoded(), null));
        } catch (Exception e) {
            throw new ExtKeyStoreException("BCFKS KeyStore exception storing private key: " + e.toString(), e);
        }
    } else if (key instanceof SecretKey) {
        if (chain != null) {
            throw new KeyStoreException("BCFKS KeyStore cannot store certificate chain with secret key.");
        }
        try {
            byte[] encodedKey = key.getEncoded();
            KeyDerivationFunc pbkdAlgId = generatePkbdAlgorithmIdentifier(PKCSObjectIdentifiers.id_PBKDF2, 256 / 8);
            byte[] keyBytes = generateKey(pbkdAlgId, "SECRET_KEY_ENCRYPTION", ((password != null) ? password : new char[0]), 32);
            String keyAlg = Strings.toUpperCase(key.getAlgorithm());
            SecretKeyData secKeyData;
            if (keyAlg.indexOf("AES") > -1) {
                secKeyData = new SecretKeyData(NISTObjectIdentifiers.aes, encodedKey);
            } else {
                ASN1ObjectIdentifier algOid = (ASN1ObjectIdentifier) oidMap.get(keyAlg);
                if (algOid != null) {
                    secKeyData = new SecretKeyData(algOid, encodedKey);
                } else {
                    algOid = (ASN1ObjectIdentifier) oidMap.get(keyAlg + "." + (encodedKey.length * 8));
                    if (algOid != null) {
                        secKeyData = new SecretKeyData(algOid, encodedKey);
                    } else {
                        throw new KeyStoreException("BCFKS KeyStore cannot recognize secret key (" + keyAlg + ") for storage.");
                    }
                }
            }
            EncryptedSecretKeyData keyData;
            if (storeEncryptionAlgorithm.equals(NISTObjectIdentifiers.id_aes256_CCM)) {
                Cipher c = createCipher("AES/CCM/NoPadding", keyBytes);
                byte[] encryptedKey = c.doFinal(secKeyData.getEncoded());
                AlgorithmParameters algParams = c.getParameters();
                PBES2Parameters pbeParams = new PBES2Parameters(pbkdAlgId, new EncryptionScheme(NISTObjectIdentifiers.id_aes256_CCM, CCMParameters.getInstance(algParams.getEncoded())));
                keyData = new EncryptedSecretKeyData(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, pbeParams), encryptedKey);
            } else {
                Cipher c = createCipher("AESKWP", keyBytes);
                byte[] encryptedKey = c.doFinal(secKeyData.getEncoded());
                PBES2Parameters pbeParams = new PBES2Parameters(pbkdAlgId, new EncryptionScheme(NISTObjectIdentifiers.id_aes256_wrap_pad));
                keyData = new EncryptedSecretKeyData(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, pbeParams), encryptedKey);
            }
            entries.put(alias, new ObjectData(SECRET_KEY, alias, creationDate, lastEditDate, keyData.getEncoded(), null));
        } catch (Exception e) {
            throw new ExtKeyStoreException("BCFKS KeyStore exception storing private key: " + e.toString(), e);
        }
    } else {
        throw new KeyStoreException("BCFKS KeyStore unable to recognize key.");
    }
    lastModifiedDate = lastEditDate;
}
Also used : PBES2Parameters(com.github.zhenwei.core.asn1.pkcs.PBES2Parameters) EncryptionScheme(com.github.zhenwei.core.asn1.pkcs.EncryptionScheme) PrivateKey(java.security.PrivateKey) ObjectData(com.github.zhenwei.core.asn1.bc.ObjectData) KeyStoreException(java.security.KeyStoreException) SecretKeyData(com.github.zhenwei.core.asn1.bc.SecretKeyData) EncryptedSecretKeyData(com.github.zhenwei.core.asn1.bc.EncryptedSecretKeyData) Date(java.util.Date) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ParseException(java.text.ParseException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) SecretKey(javax.crypto.SecretKey) EncryptedSecretKeyData(com.github.zhenwei.core.asn1.bc.EncryptedSecretKeyData) KeyDerivationFunc(com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc) EncryptedPrivateKeyInfo(com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) EncryptedPrivateKeyData(com.github.zhenwei.core.asn1.bc.EncryptedPrivateKeyData) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) AlgorithmParameters(java.security.AlgorithmParameters)

Example 8 with PBES2Parameters

use of com.github.zhenwei.core.asn1.pkcs.PBES2Parameters in project LinLong-Java by zhenwei1108.

the class PKCS12KeyStoreSpi method createCipher.

private Cipher createCipher(int mode, char[] password, AlgorithmIdentifier algId) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchProviderException {
    PBES2Parameters alg = PBES2Parameters.getInstance(algId.getParameters());
    PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
    AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
    SecretKeyFactory keyFact = helper.createSecretKeyFactory(alg.getKeyDerivationFunc().getAlgorithm().getId());
    SecretKey key;
    if (func.isDefaultPrf()) {
        key = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), validateIterationCount(func.getIterationCount()), keySizeProvider.getKeySize(encScheme)));
    } else {
        key = keyFact.generateSecret(new PBKDF2KeySpec(password, func.getSalt(), validateIterationCount(func.getIterationCount()), keySizeProvider.getKeySize(encScheme), func.getPrf()));
    }
    Cipher cipher = helper.createCipher(alg.getEncryptionScheme().getAlgorithm().getId());
    ASN1Encodable encParams = alg.getEncryptionScheme().getParameters();
    if (encParams instanceof ASN1OctetString) {
        cipher.init(mode, key, new IvParameterSpec(ASN1OctetString.getInstance(encParams).getOctets()));
    } else {
        // TODO: at the moment it's just GOST, but...
        GOST28147Parameters gParams = GOST28147Parameters.getInstance(encParams);
        cipher.init(mode, key, new GOST28147ParameterSpec(gParams.getEncryptionParamSet(), gParams.getIV()));
    }
    return cipher;
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) PBES2Parameters(com.github.zhenwei.core.asn1.pkcs.PBES2Parameters) PBEKeySpec(javax.crypto.spec.PBEKeySpec) GOST28147Parameters(com.github.zhenwei.core.asn1.cryptopro.GOST28147Parameters) GOST28147ParameterSpec(com.github.zhenwei.provider.jcajce.spec.GOST28147ParameterSpec) PBKDF2KeySpec(com.github.zhenwei.provider.jcajce.spec.PBKDF2KeySpec) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) SecretKey(javax.crypto.SecretKey) PBKDF2Params(com.github.zhenwei.core.asn1.pkcs.PBKDF2Params) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 9 with PBES2Parameters

use of com.github.zhenwei.core.asn1.pkcs.PBES2Parameters in project LinLong-Java by zhenwei1108.

the class JcePKCSPBEInputDecryptorProviderBuilder method build.

public InputDecryptorProvider build(final char[] password) {
    return new InputDecryptorProvider() {

        private Cipher cipher;

        private AlgorithmIdentifier encryptionAlg;

        public InputDecryptor get(final AlgorithmIdentifier algorithmIdentifier) throws OperatorCreationException {
            SecretKey key;
            ASN1ObjectIdentifier algorithm = algorithmIdentifier.getAlgorithm();
            try {
                if (algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds)) {
                    PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algorithmIdentifier.getParameters());
                    cipher = helper.createCipher(algorithm.getId());
                    cipher.init(Cipher.DECRYPT_MODE, new PKCS12KeyWithParameters(password, wrongPKCS12Zero, pbeParams.getIV(), pbeParams.getIterations().intValue()));
                    encryptionAlg = algorithmIdentifier;
                } else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) {
                    PBES2Parameters alg = PBES2Parameters.getInstance(algorithmIdentifier.getParameters());
                    if (MiscObjectIdentifiers.id_scrypt.equals(alg.getKeyDerivationFunc().getAlgorithm())) {
                        ScryptParams params = ScryptParams.getInstance(alg.getKeyDerivationFunc().getParameters());
                        AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
                        SecretKeyFactory keyFact = helper.createSecretKeyFactory("SCRYPT");
                        key = keyFact.generateSecret(new ScryptKeySpec(password, params.getSalt(), params.getCostParameter().intValue(), params.getBlockSize().intValue(), params.getParallelizationParameter().intValue(), keySizeProvider.getKeySize(encScheme)));
                    } else {
                        SecretKeyFactory keyFact = helper.createSecretKeyFactory(alg.getKeyDerivationFunc().getAlgorithm().getId());
                        PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
                        AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
                        if (func.isDefaultPrf()) {
                            key = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), func.getIterationCount().intValue(), keySizeProvider.getKeySize(encScheme)));
                        } else {
                            key = keyFact.generateSecret(new PBKDF2KeySpec(password, func.getSalt(), func.getIterationCount().intValue(), keySizeProvider.getKeySize(encScheme), func.getPrf()));
                        }
                    }
                    cipher = helper.createCipher(alg.getEncryptionScheme().getAlgorithm().getId());
                    encryptionAlg = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
                    ASN1Encodable encParams = alg.getEncryptionScheme().getParameters();
                    if (encParams instanceof ASN1OctetString) {
                        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ASN1OctetString.getInstance(encParams).getOctets()));
                    } else if (encParams instanceof ASN1Sequence && isCCMorGCM(alg.getEncryptionScheme())) {
                        AlgorithmParameters params = AlgorithmParameters.getInstance(alg.getEncryptionScheme().getAlgorithm().getId());
                        params.init(((ASN1Sequence) encParams).getEncoded());
                        cipher.init(Cipher.DECRYPT_MODE, key, params);
                    } else if (// absent parameters
                    encParams == null) {
                        cipher.init(Cipher.DECRYPT_MODE, key);
                    } else {
                        // TODO: at the moment it's just GOST, but...
                        GOST28147Parameters gParams = GOST28147Parameters.getInstance(encParams);
                        cipher.init(Cipher.DECRYPT_MODE, key, new GOST28147ParameterSpec(gParams.getEncryptionParamSet(), gParams.getIV()));
                    }
                } else if (algorithm.equals(PKCSObjectIdentifiers.pbeWithMD5AndDES_CBC) || algorithm.equals(PKCSObjectIdentifiers.pbeWithSHA1AndDES_CBC)) {
                    PBEParameter pbeParams = PBEParameter.getInstance(algorithmIdentifier.getParameters());
                    cipher = helper.createCipher(algorithm.getId());
                    cipher.init(Cipher.DECRYPT_MODE, new PBKDF1Key(password, PasswordConverter.ASCII), new PBEParameterSpec(pbeParams.getSalt(), pbeParams.getIterationCount().intValue()));
                } else {
                    throw new OperatorCreationException("unable to create InputDecryptor: algorithm " + algorithm + " unknown.");
                }
            } catch (Exception e) {
                throw new OperatorCreationException("unable to create InputDecryptor: " + e.getMessage(), e);
            }
            return new InputDecryptor() {

                public AlgorithmIdentifier getAlgorithmIdentifier() {
                    return encryptionAlg;
                }

                public InputStream getInputStream(InputStream input) {
                    return new CipherInputStream(input, cipher);
                }
            };
        }
    };
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) PBEKeySpec(javax.crypto.spec.PBEKeySpec) GOST28147Parameters(com.github.zhenwei.core.asn1.cryptopro.GOST28147Parameters) GOST28147ParameterSpec(com.github.zhenwei.provider.jcajce.spec.GOST28147ParameterSpec) PBKDF2KeySpec(com.github.zhenwei.provider.jcajce.spec.PBKDF2KeySpec) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) PBKDF1Key(com.github.zhenwei.provider.jcajce.PBKDF1Key) PBKDF2Params(com.github.zhenwei.core.asn1.pkcs.PBKDF2Params) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) ScryptParams(com.github.zhenwei.core.asn1.misc.ScryptParams) SecretKeyFactory(javax.crypto.SecretKeyFactory) PKCS12KeyWithParameters(com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) PBEParameter(com.github.zhenwei.core.asn1.pkcs.PBEParameter) PBES2Parameters(com.github.zhenwei.core.asn1.pkcs.PBES2Parameters) CipherInputStream(com.github.zhenwei.provider.jcajce.io.CipherInputStream) InputDecryptor(com.github.zhenwei.pkix.operator.InputDecryptor) CipherInputStream(com.github.zhenwei.provider.jcajce.io.CipherInputStream) InputStream(java.io.InputStream) ScryptKeySpec(com.github.zhenwei.provider.jcajce.spec.ScryptKeySpec) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) SecretKey(javax.crypto.SecretKey) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) InputDecryptorProvider(com.github.zhenwei.pkix.operator.InputDecryptorProvider) PKCS12PBEParams(com.github.zhenwei.core.asn1.pkcs.PKCS12PBEParams) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) AlgorithmParameters(java.security.AlgorithmParameters)

Example 10 with PBES2Parameters

use of com.github.zhenwei.core.asn1.pkcs.PBES2Parameters in project LinLong-Java by zhenwei1108.

the class JcePKCSPBEOutputEncryptorBuilder method build.

public OutputEncryptor build(final char[] password) throws OperatorCreationException {
    final Cipher cipher;
    SecretKey key;
    if (random == null) {
        random = new SecureRandom();
    }
    final AlgorithmIdentifier encryptionAlg;
    try {
        if (isPKCS12(algorithm)) {
            byte[] salt = new byte[20];
            random.nextBytes(salt);
            cipher = helper.createCipher(algorithm.getId());
            cipher.init(Cipher.ENCRYPT_MODE, new PKCS12KeyWithParameters(password, salt, iterationCount));
            encryptionAlg = new AlgorithmIdentifier(algorithm, new PKCS12PBEParams(salt, iterationCount));
        } else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) {
            PBKDFConfig pbkDef = (pbkdf == null) ? pbkdfBuilder.build() : pbkdf;
            if (MiscObjectIdentifiers.id_scrypt.equals(pbkDef.getAlgorithm())) {
                ScryptConfig skdf = (ScryptConfig) pbkDef;
                byte[] salt = new byte[skdf.getSaltLength()];
                random.nextBytes(salt);
                ScryptParams params = new ScryptParams(salt, skdf.getCostParameter(), skdf.getBlockSize(), skdf.getParallelizationParameter());
                SecretKeyFactory keyFact = helper.createSecretKeyFactory("SCRYPT");
                key = keyFact.generateSecret(new ScryptKeySpec(password, salt, skdf.getCostParameter(), skdf.getBlockSize(), skdf.getParallelizationParameter(), keySizeProvider.getKeySize(new AlgorithmIdentifier(keyEncAlgorithm))));
                cipher = helper.createCipher(keyEncAlgorithm.getId());
                cipher.init(Cipher.ENCRYPT_MODE, simplifyPbeKey(key), random);
                AlgorithmParameters algP = cipher.getParameters();
                PBES2Parameters algParams;
                if (algP != null) {
                    algParams = new PBES2Parameters(new KeyDerivationFunc(MiscObjectIdentifiers.id_scrypt, params), new EncryptionScheme(keyEncAlgorithm, ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));
                } else {
                    algParams = new PBES2Parameters(new KeyDerivationFunc(MiscObjectIdentifiers.id_scrypt, params), new EncryptionScheme(keyEncAlgorithm));
                }
                encryptionAlg = new AlgorithmIdentifier(algorithm, algParams);
            } else {
                PBKDF2Config pkdf = (PBKDF2Config) pbkDef;
                byte[] salt = new byte[pkdf.getSaltLength()];
                random.nextBytes(salt);
                SecretKeyFactory keyFact = helper.createSecretKeyFactory(JceUtils.getAlgorithm(pkdf.getPRF().getAlgorithm()));
                key = keyFact.generateSecret(new PBEKeySpec(password, salt, pkdf.getIterationCount(), keySizeProvider.getKeySize(new AlgorithmIdentifier(keyEncAlgorithm))));
                cipher = helper.createCipher(keyEncAlgorithm.getId());
                cipher.init(Cipher.ENCRYPT_MODE, simplifyPbeKey(key), random);
                AlgorithmParameters algP = cipher.getParameters();
                PBES2Parameters algParams;
                if (algP != null) {
                    algParams = new PBES2Parameters(new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, pkdf.getIterationCount(), pkdf.getPRF())), new EncryptionScheme(keyEncAlgorithm, ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));
                } else {
                    algParams = new PBES2Parameters(new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, pkdf.getIterationCount(), pkdf.getPRF())), new EncryptionScheme(keyEncAlgorithm));
                }
                encryptionAlg = new AlgorithmIdentifier(algorithm, algParams);
            }
        } else {
            throw new OperatorCreationException("unrecognised algorithm");
        }
        return new OutputEncryptor() {

            public AlgorithmIdentifier getAlgorithmIdentifier() {
                return encryptionAlg;
            }

            public OutputStream getOutputStream(OutputStream out) {
                return new CipherOutputStream(out, cipher);
            }

            public GenericKey getKey() {
                if (isPKCS12(encryptionAlg.getAlgorithm())) {
                    return new GenericKey(encryptionAlg, PKCS12PasswordToBytes(password));
                } else {
                    return new GenericKey(encryptionAlg, PKCS5PasswordToBytes(password));
                }
            }
        };
    } catch (Exception e) {
        throw new OperatorCreationException("unable to create OutputEncryptor: " + e.getMessage(), e);
    }
}
Also used : PBKDF2Config(com.github.zhenwei.core.crypto.util.PBKDF2Config) PBEKeySpec(javax.crypto.spec.PBEKeySpec) EncryptionScheme(com.github.zhenwei.core.asn1.pkcs.EncryptionScheme) CipherOutputStream(com.github.zhenwei.provider.jcajce.io.CipherOutputStream) OutputStream(java.io.OutputStream) CipherOutputStream(com.github.zhenwei.provider.jcajce.io.CipherOutputStream) ScryptConfig(com.github.zhenwei.core.crypto.util.ScryptConfig) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) KeyDerivationFunc(com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc) PBKDF2Params(com.github.zhenwei.core.asn1.pkcs.PBKDF2Params) GenericKey(com.github.zhenwei.pkix.operator.GenericKey) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) ScryptParams(com.github.zhenwei.core.asn1.misc.ScryptParams) SecretKeyFactory(javax.crypto.SecretKeyFactory) PKCS12KeyWithParameters(com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters) PBKDFConfig(com.github.zhenwei.core.crypto.util.PBKDFConfig) PBES2Parameters(com.github.zhenwei.core.asn1.pkcs.PBES2Parameters) SecureRandom(java.security.SecureRandom) ScryptKeySpec(com.github.zhenwei.provider.jcajce.spec.ScryptKeySpec) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) SecretKey(javax.crypto.SecretKey) PKCS12PBEParams(com.github.zhenwei.core.asn1.pkcs.PKCS12PBEParams) Cipher(javax.crypto.Cipher) OutputEncryptor(com.github.zhenwei.pkix.operator.OutputEncryptor) AlgorithmParameters(java.security.AlgorithmParameters)

Aggregations

Cipher (javax.crypto.Cipher)11 PBES2Parameters (com.github.zhenwei.core.asn1.pkcs.PBES2Parameters)7 AlgorithmParameters (java.security.AlgorithmParameters)7 SecretKey (javax.crypto.SecretKey)7 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 PBES2Parameters (org.bouncycastle.asn1.pkcs.PBES2Parameters)6 IOException (java.io.IOException)5 InvalidKeyException (java.security.InvalidKeyException)5 SecretKeyFactory (javax.crypto.SecretKeyFactory)5 PBKDF2Params (org.bouncycastle.asn1.pkcs.PBKDF2Params)5 EncryptionScheme (com.github.zhenwei.core.asn1.pkcs.EncryptionScheme)4 PBKDF2Params (com.github.zhenwei.core.asn1.pkcs.PBKDF2Params)4 KeyDerivationFunc (com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc)3 IvParameterSpec (javax.crypto.spec.IvParameterSpec)3 PBEKeySpec (javax.crypto.spec.PBEKeySpec)3 EncryptionScheme (org.bouncycastle.asn1.pkcs.EncryptionScheme)3 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)3 ASN1Encodable (com.github.zhenwei.core.asn1.ASN1Encodable)2 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)2