Search in sources :

Example 1 with PBKDF2Params

use of com.github.zhenwei.core.asn1.pkcs.PBKDF2Params in project hedera-sdk-java by hashgraph.

the class Pem method decryptPrivateKey.

private static PrivateKeyInfo decryptPrivateKey(byte[] encodedStruct, String passphrase) throws IOException {
    var encryptedPrivateKeyInfo = EncryptedPrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(encodedStruct));
    AlgorithmIdentifier encryptAlg = encryptedPrivateKeyInfo.getEncryptionAlgorithm();
    if (!encryptAlg.getAlgorithm().equals(PKCSObjectIdentifiers.id_PBES2)) {
        throw new BadKeyException("unsupported PEM key encryption: " + encryptAlg);
    }
    PBES2Parameters params = PBES2Parameters.getInstance(encryptAlg.getParameters());
    KeyDerivationFunc kdf = params.getKeyDerivationFunc();
    EncryptionScheme encScheme = params.getEncryptionScheme();
    if (!kdf.getAlgorithm().equals(PKCSObjectIdentifiers.id_PBKDF2)) {
        throw new BadKeyException("unsupported KDF: " + kdf.getAlgorithm());
    }
    if (!encScheme.getAlgorithm().equals(NISTObjectIdentifiers.id_aes128_CBC)) {
        throw new BadKeyException("unsupported encryption: " + encScheme.getAlgorithm());
    }
    PBKDF2Params kdfParams = PBKDF2Params.getInstance(kdf.getParameters());
    if (!kdfParams.getPrf().getAlgorithm().equals(PKCSObjectIdentifiers.id_hmacWithSHA256)) {
        throw new BadKeyException("unsupported PRF: " + kdfParams.getPrf());
    }
    int keyLength = kdfParams.getKeyLength() != null ? kdfParams.getKeyLength().intValue() : Crypto.CBC_DK_LEN;
    KeyParameter derivedKey = Crypto.deriveKeySha256(passphrase, kdfParams.getSalt(), kdfParams.getIterationCount().intValue(), keyLength);
    AlgorithmParameters aesParams;
    try {
        aesParams = AlgorithmParameters.getInstance("AES");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    aesParams.init(encScheme.getParameters().toASN1Primitive().getEncoded());
    Cipher cipher = Crypto.initAesCbc128Decrypt(derivedKey, aesParams);
    byte[] decrypted = Crypto.runCipher(cipher, encryptedPrivateKeyInfo.getEncryptedData());
    // we need to parse our input data as the cipher may add padding
    ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(decrypted));
    return PrivateKeyInfo.getInstance(inputStream.readObject());
}
Also used : PBES2Parameters(org.bouncycastle.asn1.pkcs.PBES2Parameters) EncryptionScheme(org.bouncycastle.asn1.pkcs.EncryptionScheme) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) ByteArrayInputStream(java.io.ByteArrayInputStream) KeyDerivationFunc(org.bouncycastle.asn1.pkcs.KeyDerivationFunc) PBKDF2Params(org.bouncycastle.asn1.pkcs.PBKDF2Params) Cipher(javax.crypto.Cipher) AlgorithmParameters(java.security.AlgorithmParameters)

Example 2 with PBKDF2Params

use of com.github.zhenwei.core.asn1.pkcs.PBKDF2Params in project hedera-sdk-java by hashgraph.

the class Pem method writeEncryptedPrivateKey.

/*
     * For some reason, this generates PEM encodings that we ourselves can import, but OpenSSL
     * doesn't like. We decided to punt on generating encrypted PEMs for now but saving
     * the code for when we get back to it and/or any demand arises.
     */
@SuppressWarnings("unused")
static void writeEncryptedPrivateKey(PrivateKeyInfo pkInfo, Writer out, String passphrase) throws IOException {
    byte[] salt = Crypto.randomBytes(Crypto.SALT_LEN);
    KeyParameter derivedKey = Crypto.deriveKeySha256(passphrase, salt, Crypto.ITERATIONS, Crypto.CBC_DK_LEN);
    byte[] iv = Crypto.randomBytes(Crypto.IV_LEN);
    Cipher cipher = Crypto.initAesCbc128Encrypt(derivedKey, iv);
    byte[] encryptedKey = Crypto.runCipher(cipher, pkInfo.getEncoded());
    // I wanted to just do this with BC's PKCS8Generator and KcePKCSPBEOutputEncryptorBuilder
    // but it tries to init AES instance of `Cipher` with a `PBKDF2Key` and the former complains
    // So this is basically a reimplementation of that minus the excess OO
    PBES2Parameters parameters = new PBES2Parameters(new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, Crypto.ITERATIONS, Crypto.CBC_DK_LEN, new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA256))), new EncryptionScheme(NISTObjectIdentifiers.id_aes128_CBC, ASN1Primitive.fromByteArray(cipher.getParameters().getEncoded())));
    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, parameters), encryptedKey);
    PemWriter writer = new PemWriter(out);
    writer.writeObject(new PemObject(TYPE_ENCRYPTED_PRIVATE_KEY, encryptedPrivateKeyInfo.getEncoded()));
    writer.flush();
}
Also used : PBES2Parameters(org.bouncycastle.asn1.pkcs.PBES2Parameters) PemObject(org.bouncycastle.util.io.pem.PemObject) EncryptionScheme(org.bouncycastle.asn1.pkcs.EncryptionScheme) PemWriter(org.bouncycastle.util.io.pem.PemWriter) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) KeyDerivationFunc(org.bouncycastle.asn1.pkcs.KeyDerivationFunc) PBKDF2Params(org.bouncycastle.asn1.pkcs.PBKDF2Params) EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 3 with PBKDF2Params

use of com.github.zhenwei.core.asn1.pkcs.PBKDF2Params in project robovm by robovm.

the class PKCS12KeyStoreSpi method unwrapKey.

protected PrivateKey unwrapKey(AlgorithmIdentifier algId, byte[] data, char[] password, boolean wrongPKCS12Zero) throws IOException {
    ASN1ObjectIdentifier algorithm = algId.getAlgorithm();
    try {
        if (algorithm.on(PKCSObjectIdentifiers.pkcs_12PbeIds)) {
            PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters());
            PBEKeySpec pbeSpec = new PBEKeySpec(password);
            PrivateKey out;
            SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm.getId(), bcProvider);
            PBEParameterSpec defParams = new PBEParameterSpec(pbeParams.getIV(), pbeParams.getIterations().intValue());
            SecretKey k = keyFact.generateSecret(pbeSpec);
            ((BCPBEKey) k).setTryWrongPKCS12Zero(wrongPKCS12Zero);
            Cipher cipher = Cipher.getInstance(algorithm.getId(), bcProvider);
            cipher.init(Cipher.UNWRAP_MODE, k, defParams);
            // we pass "" as the key algorithm type as it is unknown at this point
            return (PrivateKey) cipher.unwrap(data, "", Cipher.PRIVATE_KEY);
        } else if (algorithm.equals(PKCSObjectIdentifiers.id_PBES2)) {
            PBES2Parameters alg = PBES2Parameters.getInstance(algId.getParameters());
            PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
            SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId(), bcProvider);
            SecretKey k = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), func.getIterationCount().intValue(), SecretKeyUtil.getKeySize(alg.getEncryptionScheme().getAlgorithm())));
            Cipher cipher = Cipher.getInstance(alg.getEncryptionScheme().getAlgorithm().getId(), bcProvider);
            cipher.init(Cipher.UNWRAP_MODE, k, new IvParameterSpec(ASN1OctetString.getInstance(alg.getEncryptionScheme().getParameters()).getOctets()));
            // we pass "" as the key algorithm type as it is unknown at this point
            return (PrivateKey) cipher.unwrap(data, "", Cipher.PRIVATE_KEY);
        }
    } catch (Exception e) {
        throw new IOException("exception unwrapping private key - " + e.toString());
    }
    throw new IOException("exception unwrapping private key - cannot recognise: " + algorithm);
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) PBES2Parameters(org.bouncycastle.asn1.pkcs.PBES2Parameters) PrivateKey(java.security.PrivateKey) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SecretKey(javax.crypto.SecretKey) PKCS12PBEParams(org.bouncycastle.asn1.pkcs.PKCS12PBEParams) BCPBEKey(org.bouncycastle.jcajce.provider.symmetric.util.BCPBEKey) PBKDF2Params(org.bouncycastle.asn1.pkcs.PBKDF2Params) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec)

Example 4 with PBKDF2Params

use of com.github.zhenwei.core.asn1.pkcs.PBKDF2Params in project jruby-openssl by jruby.

the class PEMInputOutput method extractPBES2CipherParams.

private static CipherParameters extractPBES2CipherParams(char[] password, PBES2Parameters pbeParams) {
    PBKDF2Params pbkdfParams = PBKDF2Params.getInstance(pbeParams.getKeyDerivationFunc().getParameters());
    int keySize = 192;
    if (pbkdfParams.getKeyLength() != null) {
        keySize = pbkdfParams.getKeyLength().intValue() * 8;
    }
    int iterationCount = pbkdfParams.getIterationCount().intValue();
    byte[] salt = pbkdfParams.getSalt();
    PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToBytes(password), salt, iterationCount);
    return generator.generateDerivedParameters(keySize);
}
Also used : PKCS5S2ParametersGenerator(org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator) PBKDF2Params(org.bouncycastle.asn1.pkcs.PBKDF2Params) OpenSSLPBEParametersGenerator(org.bouncycastle.crypto.generators.OpenSSLPBEParametersGenerator) PBEParametersGenerator(org.bouncycastle.crypto.PBEParametersGenerator)

Example 5 with PBKDF2Params

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

the class CmpAgentUtil method decrypt.

private static byte[] decrypt(EncryptedValue ev, char[] password) throws XiSecurityException {
    AlgorithmIdentifier symmAlg = ev.getSymmAlg();
    if (!PKCSObjectIdentifiers.id_PBES2.equals(symmAlg.getAlgorithm())) {
        throw new XiSecurityException("unsupported symmAlg " + symmAlg.getAlgorithm().getId());
    }
    PBES2Parameters alg = PBES2Parameters.getInstance(symmAlg.getParameters());
    PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters());
    AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme());
    try {
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(alg.getKeyDerivationFunc().getAlgorithm().getId());
        SecretKey key;
        int iterations = func.getIterationCount().intValue();
        key = keyFact.generateSecret(new PBKDF2KeySpec(password, func.getSalt(), iterations, KEYSIZE_PROVIDER.getKeySize(encScheme), 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());
    } catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) {
        throw new XiSecurityException("Error while decrypting the EncryptedValue", ex);
    }
}
Also used : PBES2Parameters(org.bouncycastle.asn1.pkcs.PBES2Parameters) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) GCMParameterSpec(javax.crypto.spec.GCMParameterSpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) PBKDF2KeySpec(org.bouncycastle.jcajce.spec.PBKDF2KeySpec) InvalidKeyException(java.security.InvalidKeyException) GCMParameters(org.bouncycastle.asn1.cms.GCMParameters) SecretKeySpec(javax.crypto.spec.SecretKeySpec) PBKDF2Params(org.bouncycastle.asn1.pkcs.PBKDF2Params) IESCipher(org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher) BlockCipher(org.bouncycastle.crypto.BlockCipher) CBCBlockCipher(org.bouncycastle.crypto.modes.CBCBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Aggregations

PBKDF2Params (com.github.zhenwei.core.asn1.pkcs.PBKDF2Params)15 Cipher (javax.crypto.Cipher)8 ScryptParams (com.github.zhenwei.core.asn1.misc.ScryptParams)7 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)7 SecretKey (javax.crypto.SecretKey)7 KeyDerivationFunc (com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc)6 PBKDF2Params (org.bouncycastle.asn1.pkcs.PBKDF2Params)6 IOException (java.io.IOException)5 SecretKeyFactory (javax.crypto.SecretKeyFactory)5 PBES2Parameters (org.bouncycastle.asn1.pkcs.PBES2Parameters)5 ASN1OctetString (com.github.zhenwei.core.asn1.ASN1OctetString)4 PBES2Parameters (com.github.zhenwei.core.asn1.pkcs.PBES2Parameters)4 OperatorCreationException (com.github.zhenwei.pkix.operator.OperatorCreationException)4 PKCS12KeyWithParameters (com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters)4 AlgorithmParameters (java.security.AlgorithmParameters)4 PBEKeySpec (javax.crypto.spec.PBEKeySpec)4 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)3 PKCS5S2ParametersGenerator (com.github.zhenwei.core.crypto.generators.PKCS5S2ParametersGenerator)3 KeyParameter (com.github.zhenwei.core.crypto.params.KeyParameter)3 CMSException (com.github.zhenwei.pkix.cms.CMSException)3