Search in sources :

Example 1 with EncryptedPrivateKeyInfo

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

use of com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo in project certmgr by hdecarne.

the class DERCertReaderWriter method tryDecodeKey.

@Nullable
private static KeyPair tryDecodeKey(ASN1Primitive asn1Object, String resource, PasswordCallback password) throws IOException {
    PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = null;
    try {
        encryptedPrivateKeyInfo = new PKCS8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.getInstance(asn1Object));
    } catch (Exception e) {
        Exceptions.ignore(e);
    }
    PrivateKeyInfo privateKeyInfo = null;
    if (encryptedPrivateKeyInfo != null) {
        Throwable passwordException = null;
        while (privateKeyInfo == null) {
            char[] passwordChars = password.queryPassword(resource);
            if (passwordChars == null) {
                throw new PasswordRequiredException(resource, passwordException);
            }
            InputDecryptorProvider inputDecryptorProvider = INPUT_DECRYPTOR_BUILDER.build(passwordChars);
            try {
                privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
            } catch (PKCSException e) {
                passwordException = e;
            }
        }
    }
    try {
        privateKeyInfo = PrivateKeyInfo.getInstance(asn1Object);
    } catch (Exception e) {
        Exceptions.ignore(e);
    }
    KeyPair key = null;
    if (privateKeyInfo != null) {
        PrivateKey privateKey;
        try {
            String algorithmId = privateKeyInfo.getPrivateKeyAlgorithm().getAlgorithm().getId();
            KeyFactory keyFactory = JCA_JCE_HELPER.createKeyFactory(algorithmId);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyInfo.getEncoded());
            privateKey = keyFactory.generatePrivate(keySpec);
        } catch (GeneralSecurityException e) {
            throw new CertProviderException(e);
        }
        key = KeyHelper.rebuildKeyPair(privateKey);
    }
    return key;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) GeneralSecurityException(java.security.GeneralSecurityException) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PasswordRequiredException(de.carne.certmgr.certs.PasswordRequiredException) PKCSException(org.bouncycastle.pkcs.PKCSException) CertProviderException(de.carne.certmgr.certs.CertProviderException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertProviderException(de.carne.certmgr.certs.CertProviderException) GeneralSecurityException(java.security.GeneralSecurityException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) PasswordRequiredException(de.carne.certmgr.certs.PasswordRequiredException) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo) KeyFactory(java.security.KeyFactory) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 3 with EncryptedPrivateKeyInfo

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

the class PEMInputOutput method derivePrivateKeyPBES1.

private static PrivateKey derivePrivateKeyPBES1(EncryptedPrivateKeyInfo eIn, AlgorithmIdentifier algId, char[] password) throws GeneralSecurityException, IOException {
    // From BC's PEMReader
    PKCS12PBEParams pkcs12Params = PKCS12PBEParams.getInstance(algId.getParameters());
    PBEKeySpec pbeSpec = new PBEKeySpec(password);
    PBEParameterSpec pbeParams = new PBEParameterSpec(pkcs12Params.getIV(), pkcs12Params.getIterations().intValue());
    String algorithm = ASN1Registry.o2a(algId.getAlgorithm());
    algorithm = (algorithm.split("-"))[0];
    SecretKeyFactory secKeyFactory = SecurityHelper.getSecretKeyFactory(algorithm);
    Cipher cipher = SecurityHelper.getCipher(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, secKeyFactory.generateSecret(pbeSpec), pbeParams);
    PrivateKeyInfo pInfo = PrivateKeyInfo.getInstance(ASN1Primitive.fromByteArray(cipher.doFinal(eIn.getEncryptedData())));
    KeyFactory keyFactory = getKeyFactory(pInfo.getPrivateKeyAlgorithm());
    return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(pInfo.getEncoded()));
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) PKCS12PBEParams(org.bouncycastle.asn1.pkcs.PKCS12PBEParams) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DEROctetString(org.bouncycastle.asn1.DEROctetString) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) CBCBlockCipher(org.bouncycastle.crypto.modes.CBCBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) Cipher(javax.crypto.Cipher) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) EncryptedPrivateKeyInfo(org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory)

Example 4 with EncryptedPrivateKeyInfo

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

the class EncryptedPrivateKeyData method toASN1Primitive.

public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(2);
    v.add(encryptedPrivateKeyInfo);
    v.add(new DERSequence(certificateChain));
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector)

Example 5 with EncryptedPrivateKeyInfo

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

Aggregations

IOException (java.io.IOException)8 EncryptedPrivateKeyInfo (com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo)5 GeneralSecurityException (java.security.GeneralSecurityException)5 InvalidKeyException (java.security.InvalidKeyException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 PrivateKey (java.security.PrivateKey)4 CertificateEncodingException (java.security.cert.CertificateEncodingException)4 CertificateException (java.security.cert.CertificateException)4 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)4 EncryptedPrivateKeyInfo (org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo)4 ObjectData (com.github.zhenwei.core.asn1.bc.ObjectData)3 KeyFactory (java.security.KeyFactory)3 KeyStoreException (java.security.KeyStoreException)3 NoSuchProviderException (java.security.NoSuchProviderException)3 UnrecoverableKeyException (java.security.UnrecoverableKeyException)3 ParseException (java.text.ParseException)3 BadPaddingException (javax.crypto.BadPaddingException)3 Cipher (javax.crypto.Cipher)3 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)3 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)3