Search in sources :

Example 1 with PBES2Parameters

use of com.github.zhenwei.core.asn1.pkcs.PBES2Parameters 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 PBES2Parameters

use of com.github.zhenwei.core.asn1.pkcs.PBES2Parameters 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 PBES2Parameters

use of com.github.zhenwei.core.asn1.pkcs.PBES2Parameters 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 PBES2Parameters

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

the class PEMInputOutput method derivePrivateKeyPBES2.

private static PrivateKey derivePrivateKeyPBES2(EncryptedPrivateKeyInfo eIn, AlgorithmIdentifier algId, char[] password) throws GeneralSecurityException, InvalidCipherTextException {
    PBES2Parameters pbeParams = PBES2Parameters.getInstance((ASN1Sequence) algId.getParameters());
    CipherParameters cipherParams = extractPBES2CipherParams(password, pbeParams);
    EncryptionScheme scheme = pbeParams.getEncryptionScheme();
    BufferedBlockCipher cipher;
    if (scheme.getAlgorithm().equals(PKCSObjectIdentifiers.RC2_CBC)) {
        RC2CBCParameter rc2Params = RC2CBCParameter.getInstance(scheme);
        byte[] iv = rc2Params.getIV();
        CipherParameters param = new ParametersWithIV(cipherParams, iv);
        cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC2Engine()));
        cipher.init(false, param);
    } else {
        byte[] iv = ASN1OctetString.getInstance(scheme.getParameters()).getOctets();
        CipherParameters param = new ParametersWithIV(cipherParams, iv);
        cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));
        cipher.init(false, param);
    }
    byte[] data = eIn.getEncryptedData();
    byte[] out = new byte[cipher.getOutputSize(data.length)];
    int len = cipher.processBytes(data, 0, data.length, out, 0);
    len += cipher.doFinal(out, len);
    byte[] pkcs8 = new byte[len];
    System.arraycopy(out, 0, pkcs8, 0, len);
    // It seems to work for both RSA and DSA.
    KeyFactory fact = SecurityHelper.getKeyFactory("RSA");
    return fact.generatePrivate(new PKCS8EncodedKeySpec(pkcs8));
}
Also used : PBES2Parameters(org.bouncycastle.asn1.pkcs.PBES2Parameters) EncryptionScheme(org.bouncycastle.asn1.pkcs.EncryptionScheme) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) RC2Engine(org.bouncycastle.crypto.engines.RC2Engine) RC2CBCParameter(org.bouncycastle.asn1.pkcs.RC2CBCParameter) CipherParameters(org.bouncycastle.crypto.CipherParameters) ParametersWithIV(org.bouncycastle.crypto.params.ParametersWithIV) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) CBCBlockCipher(org.bouncycastle.crypto.modes.CBCBlockCipher) DESedeEngine(org.bouncycastle.crypto.engines.DESedeEngine) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory)

Example 5 with PBES2Parameters

use of com.github.zhenwei.core.asn1.pkcs.PBES2Parameters 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

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