Search in sources :

Example 6 with KeyDerivationFunc

use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc 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 7 with KeyDerivationFunc

use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc 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 8 with KeyDerivationFunc

use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc 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 9 with KeyDerivationFunc

use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc in project LinLong-Java by zhenwei1108.

the class BcFKSKeyStoreSpi method generatePkbdAlgorithmIdentifier.

private KeyDerivationFunc generatePkbdAlgorithmIdentifier(PBKDFConfig pbkdfConfig, int keySizeInBytes) {
    if (MiscObjectIdentifiers.id_scrypt.equals(pbkdfConfig.getAlgorithm())) {
        ScryptConfig scryptConfig = (ScryptConfig) pbkdfConfig;
        byte[] pbkdSalt = new byte[scryptConfig.getSaltLength()];
        getDefaultSecureRandom().nextBytes(pbkdSalt);
        ScryptParams params = new ScryptParams(pbkdSalt, scryptConfig.getCostParameter(), scryptConfig.getBlockSize(), scryptConfig.getParallelizationParameter(), keySizeInBytes);
        return new KeyDerivationFunc(MiscObjectIdentifiers.id_scrypt, params);
    } else {
        PBKDF2Config pbkdf2Config = (PBKDF2Config) pbkdfConfig;
        byte[] pbkdSalt = new byte[pbkdf2Config.getSaltLength()];
        getDefaultSecureRandom().nextBytes(pbkdSalt);
        return new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(pbkdSalt, pbkdf2Config.getIterationCount(), keySizeInBytes, pbkdf2Config.getPRF()));
    }
}
Also used : PBKDF2Config(com.github.zhenwei.core.crypto.util.PBKDF2Config) KeyDerivationFunc(com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc) PBKDF2Params(com.github.zhenwei.core.asn1.pkcs.PBKDF2Params) ScryptConfig(com.github.zhenwei.core.crypto.util.ScryptConfig) ScryptParams(com.github.zhenwei.core.asn1.misc.ScryptParams)

Example 10 with KeyDerivationFunc

use of org.bouncycastle.asn1.pkcs.KeyDerivationFunc in project LinLong-Java by zhenwei1108.

the class BcFKSKeyStoreSpi method generatePkbdAlgorithmIdentifier.

private KeyDerivationFunc generatePkbdAlgorithmIdentifier(KeyDerivationFunc baseAlg, int keySizeInBytes) {
    if (MiscObjectIdentifiers.id_scrypt.equals(baseAlg.getAlgorithm())) {
        ScryptParams oldParams = ScryptParams.getInstance(baseAlg.getParameters());
        byte[] pbkdSalt = new byte[oldParams.getSalt().length];
        getDefaultSecureRandom().nextBytes(pbkdSalt);
        ScryptParams params = new ScryptParams(pbkdSalt, oldParams.getCostParameter(), oldParams.getBlockSize(), oldParams.getParallelizationParameter(), BigInteger.valueOf(keySizeInBytes));
        return new KeyDerivationFunc(MiscObjectIdentifiers.id_scrypt, params);
    } else {
        PBKDF2Params oldParams = PBKDF2Params.getInstance(baseAlg.getParameters());
        byte[] pbkdSalt = new byte[oldParams.getSalt().length];
        getDefaultSecureRandom().nextBytes(pbkdSalt);
        PBKDF2Params params = new PBKDF2Params(pbkdSalt, oldParams.getIterationCount().intValue(), keySizeInBytes, oldParams.getPrf());
        return new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, params);
    }
}
Also used : KeyDerivationFunc(com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc) PBKDF2Params(com.github.zhenwei.core.asn1.pkcs.PBKDF2Params) ScryptParams(com.github.zhenwei.core.asn1.misc.ScryptParams)

Aggregations

KeyDerivationFunc (com.github.zhenwei.core.asn1.pkcs.KeyDerivationFunc)8 PBKDF2Params (com.github.zhenwei.core.asn1.pkcs.PBKDF2Params)6 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)6 Cipher (javax.crypto.Cipher)6 KeyDerivationFunc (org.bouncycastle.asn1.pkcs.KeyDerivationFunc)6 EncryptionScheme (com.github.zhenwei.core.asn1.pkcs.EncryptionScheme)5 AlgorithmParameters (java.security.AlgorithmParameters)5 PBES2Parameters (com.github.zhenwei.core.asn1.pkcs.PBES2Parameters)4 IOException (java.io.IOException)4 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)4 ScryptParams (com.github.zhenwei.core.asn1.misc.ScryptParams)3 OperatorCreationException (com.github.zhenwei.pkix.operator.OperatorCreationException)3 PKCS12KeyWithParameters (com.github.zhenwei.provider.jcajce.PKCS12KeyWithParameters)3 GeneralSecurityException (java.security.GeneralSecurityException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 EncryptionScheme (org.bouncycastle.asn1.pkcs.EncryptionScheme)3 ObjectData (com.github.zhenwei.core.asn1.bc.ObjectData)2 PKCS12PBEParams (com.github.zhenwei.core.asn1.pkcs.PKCS12PBEParams)2 PBKDF2Config (com.github.zhenwei.core.crypto.util.PBKDF2Config)2 ScryptConfig (com.github.zhenwei.core.crypto.util.ScryptConfig)2