Search in sources :

Example 61 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project jmulticard by ctt-gob-es.

the class BCSphincs256PrivateKey method getEncoded.

public byte[] getEncoded() {
    try {
        PrivateKeyInfo pki;
        if (params.getTreeDigest() != null) {
            pki = PrivateKeyInfoFactory.createPrivateKeyInfo(params, attributes);
        } else {
            AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.sphincs256, new SPHINCS256KeyParams(new AlgorithmIdentifier(treeDigest)));
            pki = new PrivateKeyInfo(algorithmIdentifier, new DEROctetString(params.getKeyData()), attributes);
        }
        return pki.getEncoded();
    } catch (IOException e) {
        return null;
    }
}
Also used : SPHINCS256KeyParams(org.bouncycastle.pqc.asn1.SPHINCS256KeyParams) IOException(java.io.IOException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 62 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project jmulticard by ctt-gob-es.

the class BCRainbowPrivateKey method getEncoded.

public byte[] getEncoded() {
    RainbowPrivateKey privateKey = new RainbowPrivateKey(A1inv, b1, A2inv, b2, vi, layers);
    PrivateKeyInfo pki;
    try {
        AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PQCObjectIdentifiers.rainbow, DERNull.INSTANCE);
        pki = new PrivateKeyInfo(algorithmIdentifier, privateKey);
    } catch (IOException e) {
        return null;
    }
    try {
        byte[] encoded = pki.getEncoded();
        return encoded;
    } catch (IOException e) {
        return null;
    }
}
Also used : RainbowPrivateKey(org.bouncycastle.pqc.asn1.RainbowPrivateKey) IOException(java.io.IOException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 63 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project karaf by apache.

the class KeyPairLoader method getKeyPair.

public static KeyPair getKeyPair(InputStream is, String password) throws GeneralSecurityException, IOException {
    try (PEMParser parser = new PEMParser(new InputStreamReader(is))) {
        Object o = parser.readObject();
        JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        if (o instanceof PEMEncryptedKeyPair) {
            if (password == null) {
                throw new GeneralSecurityException("A password must be supplied to read an encrypted key pair");
            }
            JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder();
            PEMDecryptorProvider pemDecryptor = decryptorBuilder.build(password.toCharArray());
            o = pemConverter.getKeyPair(((PEMEncryptedKeyPair) o).decryptKeyPair(pemDecryptor));
        } else if (o instanceof PKCS8EncryptedPrivateKeyInfo) {
            if (password == null) {
                throw new GeneralSecurityException("A password must be supplied to read an encrypted key pair");
            }
            JceOpenSSLPKCS8DecryptorProviderBuilder jce = new JceOpenSSLPKCS8DecryptorProviderBuilder();
            try {
                InputDecryptorProvider decProv = jce.build(password.toCharArray());
                o = ((PKCS8EncryptedPrivateKeyInfo) o).decryptPrivateKeyInfo(decProv);
            } catch (OperatorCreationException | PKCSException ex) {
                LOGGER.debug("Error decrypting key pair", ex);
                throw new GeneralSecurityException("Error decrypting key pair", ex);
            }
        }
        if (o instanceof PEMKeyPair) {
            return pemConverter.getKeyPair((PEMKeyPair) o);
        } else if (o instanceof KeyPair) {
            return (KeyPair) o;
        } else if (o instanceof PrivateKeyInfo) {
            PrivateKey privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) o);
            PublicKey publicKey = convertPrivateToPublicKey(privateKey);
            if (publicKey != null) {
                return new KeyPair(publicKey, privateKey);
            }
        }
    }
    throw new GeneralSecurityException("Failed to parse input stream");
}
Also used : KeyPair(java.security.KeyPair) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) JceOpenSSLPKCS8DecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)

Example 64 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project pri-fidoiot by secure-device-onboard.

the class InteropVoucher method doPost.

@Override
protected void doPost() throws Exception {
    try {
        String pemString = getStringBody();
        OwnershipVoucher voucher = null;
        UUID guid = null;
        PrivateKey signKey = null;
        try (StringReader reader = new StringReader(pemString);
            PEMParser parser = new PEMParser(reader)) {
            for (; ; ) {
                Object obj = parser.readPemObject();
                if (obj == null) {
                    break;
                }
                if (obj instanceof PemObject) {
                    PemObject pemObj = (PemObject) obj;
                    if (pemObj.getType().equals("OWNERSHIP VOUCHER")) {
                        voucher = Mapper.INSTANCE.readValue(pemObj.getContent(), OwnershipVoucher.class);
                        OwnershipVoucherHeader header = Mapper.INSTANCE.readValue(voucher.getHeader(), OwnershipVoucherHeader.class);
                        guid = header.getGuid().toUuid();
                        logger.info("voucher guid: " + guid.toString());
                    } else if (pemObj.getType().equals("EC PRIVATE KEY")) {
                        ASN1Sequence seq = ASN1Sequence.getInstance(pemObj.getContent());
                        // PrivateKeyInfo info = PrivateKeyInfo.getInstance(seq);
                        // signKey = new JcaPEMKeyConverter().getPrivateKey(info);
                        ECPrivateKey ecpKey = ECPrivateKey.getInstance(seq);
                        AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, ecpKey.getParameters());
                        byte[] serverPkcs8 = new PrivateKeyInfo(algId, ecpKey).getEncoded();
                        KeyFactory fact = KeyFactory.getInstance("EC", "BC");
                        signKey = fact.generatePrivate(new PKCS8EncodedKeySpec(serverPkcs8));
                    } else if (pemObj.getType().equals("RSA PRIVATE KEY")) {
                        ASN1Sequence seq = ASN1Sequence.getInstance(pemObj.getContent());
                        PrivateKeyInfo info = PrivateKeyInfo.getInstance(seq);
                        signKey = new JcaPEMKeyConverter().getPrivateKey(info);
                    }
                }
            }
        }
        // we should have voucher and private key
        if (voucher != null) {
            logger.info("decoded voucher from pem");
        } else {
            logger.warn("unable to decode voucher from pem");
            getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        if (signKey != null) {
            logger.info("decoded private key from pem");
        } else {
            logger.warn("unable to decode private key from pem");
        }
        CryptoService cs = Config.getWorker(CryptoService.class);
        KeyResolver resolver = Config.getWorker(OwnerKeySupplier.class).get();
        OwnerPublicKey prevKey = VoucherUtils.getLastOwner(voucher);
        String alias = KeyResolver.getAlias(prevKey.getType(), new AlgorithmFinder().getKeySizeType(cs.decodeKey(prevKey)));
        Certificate[] certs = resolver.getCertificateChain(alias);
        extend(voucher, signKey, certs);
        getTransaction();
        OnboardingVoucher dbVoucher = getSession().get(OnboardingVoucher.class, guid.toString());
        if (dbVoucher == null) {
            dbVoucher = new OnboardingVoucher();
            dbVoucher.setGuid(guid.toString());
            dbVoucher.setData(Mapper.INSTANCE.writeValue(voucher));
            dbVoucher.setCreatedOn(new Date(System.currentTimeMillis()));
            getSession().save(dbVoucher);
        } else {
            dbVoucher.setData(Mapper.INSTANCE.writeValue(voucher));
            getSession().update(dbVoucher);
        }
        // save the voucher
        // todo: need to do TO0 manually
        // write the guid response
        byte[] guidResponse = guid.toString().getBytes(StandardCharsets.UTF_8);
        getResponse().setContentLength(guidResponse.length);
        getResponse().getOutputStream().write(guidResponse);
    } catch (Exception e) {
        logger.warn("Request failed because of internal server error.");
        getResponse().setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : ECPrivateKey(org.bouncycastle.asn1.sec.ECPrivateKey) RSAPrivateKey(org.bouncycastle.asn1.pkcs.RSAPrivateKey) PrivateKey(java.security.PrivateKey) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) PEMParser(org.bouncycastle.openssl.PEMParser) CryptoService(org.fidoalliance.fdo.protocol.dispatch.CryptoService) StringReader(java.io.StringReader) UUID(java.util.UUID) OwnerKeySupplier(org.fidoalliance.fdo.protocol.dispatch.OwnerKeySupplier) KeyFactory(java.security.KeyFactory) ECPrivateKey(org.bouncycastle.asn1.sec.ECPrivateKey) OwnershipVoucherHeader(org.fidoalliance.fdo.protocol.message.OwnershipVoucherHeader) OnboardingVoucher(org.fidoalliance.fdo.protocol.entity.OnboardingVoucher) OwnerPublicKey(org.fidoalliance.fdo.protocol.message.OwnerPublicKey) Date(java.util.Date) SignatureException(java.security.SignatureException) PemObject(org.bouncycastle.util.io.pem.PemObject) KeyResolver(org.fidoalliance.fdo.protocol.KeyResolver) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) PemObject(org.bouncycastle.util.io.pem.PemObject) OwnershipVoucher(org.fidoalliance.fdo.protocol.message.OwnershipVoucher) AlgorithmFinder(org.fidoalliance.fdo.protocol.AlgorithmFinder) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) Certificate(java.security.cert.Certificate)

Example 65 with PrivateKeyInfo

use of com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo in project pri-fidoiot by secure-device-onboard.

the class PemLoader method loadPrivateKey.

/**
 * Loads a private key from a PEM formatted String.
 *
 * @param pemString A String containing PEM information.
 * @param password  A Pem password or null.
 * @return The PrivateKey found in the PEM String.
 */
public static PrivateKey loadPrivateKey(String pemString, String password) {
    try {
        PEMParser parser = new PEMParser(new StringReader(pemString));
        for (; ; ) {
            Object obj = parser.readObject();
            if (obj == null) {
                break;
            }
            if (obj instanceof PKCS8EncryptedPrivateKeyInfo) {
                PKCS8EncryptedPrivateKeyInfo epki = (PKCS8EncryptedPrivateKeyInfo) obj;
                JcePKCSPBEInputDecryptorProviderBuilder builder = new JcePKCSPBEInputDecryptorProviderBuilder().setProvider(new BouncyCastleProvider());
                InputDecryptorProvider idp = builder.build(password.toCharArray());
                PrivateKeyInfo pki = epki.decryptPrivateKeyInfo(idp);
                return new JcaPEMKeyConverter().getPrivateKey(pki);
            } else if (obj instanceof PEMKeyPair) {
                PEMKeyPair kp = (PEMKeyPair) obj;
                return new JcaPEMKeyConverter().getPrivateKey(kp.getPrivateKeyInfo());
            } else if (obj instanceof PrivateKeyInfo) {
                return new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) obj);
            }
        }
    } catch (IOException | PKCSException e) {
        throw new RuntimeException(e);
    }
    throw new RuntimeException(new CertStoreException());
}
Also used : CertStoreException(java.security.cert.CertStoreException) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) IOException(java.io.IOException) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMParser(org.bouncycastle.openssl.PEMParser) InputDecryptorProvider(org.bouncycastle.operator.InputDecryptorProvider) StringReader(java.io.StringReader) PemObject(org.bouncycastle.util.io.pem.PemObject) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) JcePKCSPBEInputDecryptorProviderBuilder(org.bouncycastle.pkcs.jcajce.JcePKCSPBEInputDecryptorProviderBuilder) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)138 IOException (java.io.IOException)95 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)66 PEMParser (org.bouncycastle.openssl.PEMParser)62 PrivateKey (java.security.PrivateKey)48 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)41 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)35 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)35 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)33 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)27 PrivateKeyInfo (com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo)26 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)26 KeyFactory (java.security.KeyFactory)23 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)21 StringReader (java.io.StringReader)20 BigInteger (java.math.BigInteger)20 KeyPair (java.security.KeyPair)20 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)18 ByteArrayInputStream (java.io.ByteArrayInputStream)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18