Search in sources :

Example 1 with CertProviderException

use of de.carne.certmgr.certs.CertProviderException 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(de.carne.check.Nullable)

Example 2 with CertProviderException

use of de.carne.certmgr.certs.CertProviderException in project certmgr by hdecarne.

the class PKCS12CertReaderWriter method writeEncryptedBinary.

@Override
public void writeEncryptedBinary(IOResource<OutputStream> out, CertObjectStore certObjects, PasswordCallback newPassword) throws IOException {
    char[] passwordChars = newPassword.queryPassword(out.resource());
    if (passwordChars == null) {
        throw new PasswordRequiredException(out.resource());
    }
    try {
        List<PKCS12SafeBagBuilder> safeBagBuilders = new ArrayList<>(certObjects.size());
        for (CertObjectStore.Entry certObject : certObjects) {
            switch(certObject.type()) {
                case CRT:
                    safeBagBuilders.add(createCRTSafeBagBuilder(certObject.alias(), certObject.getCRT(), safeBagBuilders.isEmpty()));
                    break;
                case KEY:
                    safeBagBuilders.add(createKeySafeBagBuilder(certObject.alias(), certObject.getKey(), passwordChars));
                    break;
                case CSR:
                    break;
                case CRL:
                    break;
            }
        }
        PKCS12PfxPduBuilder pkcs12Builder = new PKCS12PfxPduBuilder();
        for (PKCS12SafeBagBuilder safeBagBuilder : safeBagBuilders) {
            pkcs12Builder.addData(safeBagBuilder.build());
        }
        PKCS12PfxPdu pkcs12 = pkcs12Builder.build(new BcPKCS12MacCalculatorBuilder(), passwordChars);
        out.io().write(pkcs12.getEncoded());
    } catch (GeneralSecurityException | PKCSException e) {
        throw new CertProviderException(e);
    }
}
Also used : PKCS12SafeBagBuilder(org.bouncycastle.pkcs.PKCS12SafeBagBuilder) JcaPKCS12SafeBagBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS12SafeBagBuilder) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) PasswordRequiredException(de.carne.certmgr.certs.PasswordRequiredException) PKCSException(org.bouncycastle.pkcs.PKCSException) CertProviderException(de.carne.certmgr.certs.CertProviderException) CertObjectStore(de.carne.certmgr.certs.CertObjectStore) BcPKCS12MacCalculatorBuilder(org.bouncycastle.pkcs.bc.BcPKCS12MacCalculatorBuilder) PKCS12PfxPdu(org.bouncycastle.pkcs.PKCS12PfxPdu) PKCS12PfxPduBuilder(org.bouncycastle.pkcs.PKCS12PfxPduBuilder)

Example 3 with CertProviderException

use of de.carne.certmgr.certs.CertProviderException in project certmgr by hdecarne.

the class PKCS12CertReaderWriter method writeBinary.

@Override
public void writeBinary(IOResource<OutputStream> out, CertObjectStore certObjects) throws IOException, UnsupportedOperationException {
    try {
        List<PKCS12SafeBagBuilder> safeBagBuilders = new ArrayList<>(certObjects.size());
        for (CertObjectStore.Entry certObject : certObjects) {
            switch(certObject.type()) {
                case CRT:
                    safeBagBuilders.add(createCRTSafeBagBuilder(certObject.alias(), certObject.getCRT(), safeBagBuilders.isEmpty()));
                    break;
                case KEY:
                    safeBagBuilders.add(createKeySafeBagBuilder(certObject.alias(), certObject.getKey()));
                    break;
                case CSR:
                    break;
                case CRL:
                    break;
            }
        }
        PKCS12PfxPduBuilder pkcs12Builder = new PKCS12PfxPduBuilder();
        for (PKCS12SafeBagBuilder safeBagBuilder : safeBagBuilders) {
            pkcs12Builder.addData(safeBagBuilder.build());
        }
        PKCS12PfxPdu pkcs12 = pkcs12Builder.build(null, null);
        out.io().write(pkcs12.getEncoded());
    } catch (GeneralSecurityException | PKCSException e) {
        throw new CertProviderException(e);
    }
}
Also used : PKCS12SafeBagBuilder(org.bouncycastle.pkcs.PKCS12SafeBagBuilder) JcaPKCS12SafeBagBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS12SafeBagBuilder) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) CertObjectStore(de.carne.certmgr.certs.CertObjectStore) PKCS12PfxPdu(org.bouncycastle.pkcs.PKCS12PfxPdu) PKCSException(org.bouncycastle.pkcs.PKCSException) CertProviderException(de.carne.certmgr.certs.CertProviderException) PKCS12PfxPduBuilder(org.bouncycastle.pkcs.PKCS12PfxPduBuilder)

Example 4 with CertProviderException

use of de.carne.certmgr.certs.CertProviderException in project certmgr by hdecarne.

the class X509CertificateHelper method generateCRT.

/**
 * Generate a CRT object.
 *
 * @param dn The CRT's Distinguished Name (DN).
 * @param key The CRT's key pair
 * @param serial The CRT's serial.
 * @param notBefore The CRT's validity start.
 * @param notAfter The CRT's validity end.
 * @param extensions The CRT's extension objects.
 * @param issuerDN The issuer's Distinguished Name (DN).
 * @param issuerKey The issuer's key pair.
 * @param signatureAlgorithm The signature algorithm to use.
 * @return The generated CRT object.
 * @throws IOException if an error occurs during generation.
 */
public static X509Certificate generateCRT(X500Principal dn, KeyPair key, BigInteger serial, Date notBefore, Date notAfter, List<X509ExtensionData> extensions, X500Principal issuerDN, KeyPair issuerKey, SignatureAlgorithm signatureAlgorithm) throws IOException {
    LOG.info("CRT generation ''{0}'' started...", dn);
    // Initialize CRT builder
    X509v3CertificateBuilder crtBuilder = new JcaX509v3CertificateBuilder(issuerDN, serial, notBefore, notAfter, dn, key.getPublic());
    // Add custom extension objects
    for (X509ExtensionData extensionData : extensions) {
        String oid = extensionData.oid();
        if (!oid.equals(Extension.subjectKeyIdentifier) && !oid.equals(Extension.authorityKeyIdentifier)) {
            boolean critical = extensionData.getCritical();
            crtBuilder.addExtension(new ASN1ObjectIdentifier(oid), critical, extensionData.encode());
        } else {
            LOG.warning("Ignoring key identifier extension");
        }
    }
    X509Certificate crt;
    try {
        // Add standard extensions based upon the CRT's purpose
        JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
        for (X509ExtensionData extensionData : extensions) {
            if (extensionData instanceof BasicConstraintsExtensionData) {
                BasicConstraintsExtensionData basicConstraintsExtension = (BasicConstraintsExtensionData) extensionData;
                if (basicConstraintsExtension.getCA()) {
                    // CRT is CA --> record it's key's identifier
                    crtBuilder.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(key.getPublic()));
                }
            }
        }
        if (!key.equals(issuerKey)) {
            // CRT is not self-signed --> record issuer key's identifier
            crtBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(issuerKey.getPublic()));
        }
        // Sign CRT
        ContentSigner crtSigner = new JcaContentSignerBuilder(signatureAlgorithm.algorithm()).build(issuerKey.getPrivate());
        crt = new JcaX509CertificateConverter().getCertificate(crtBuilder.build(crtSigner));
    } catch (OperatorCreationException | GeneralSecurityException e) {
        throw new CertProviderException(e);
    }
    LOG.info("CRT generation ''{0}'' done", dn);
    return crt;
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) CertProviderException(de.carne.certmgr.certs.CertProviderException) X509Certificate(java.security.cert.X509Certificate) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 5 with CertProviderException

use of de.carne.certmgr.certs.CertProviderException in project certmgr by hdecarne.

the class PKCS10CertificateRequest method fromPKCS10.

/**
 * Construct {@code PKCS10CertificateRequest} from a PKCS#10 object.
 *
 * @param pkcs10 The PCKS#10 object.
 * @return The constructed {@code PKCS10CertificateRequest}.
 * @throws IOException if an I/O error occurs while accessing the PKCS#10 object.
 */
public static PKCS10CertificateRequest fromPKCS10(PKCS10CertificationRequest pkcs10) throws IOException {
    JcaPKCS10CertificationRequest csr;
    X500Principal subject;
    PublicKey publicKey;
    Map<String, byte[]> criticalExtensions = new HashMap<>();
    Map<String, byte[]> nonCriticalExtensions = new HashMap<>();
    try {
        if (pkcs10 instanceof JcaPKCS10CertificationRequest) {
            csr = (JcaPKCS10CertificationRequest) pkcs10;
        } else {
            csr = new JcaPKCS10CertificationRequest(pkcs10);
        }
        subject = new X500Principal(csr.getSubject().getEncoded());
        publicKey = csr.getPublicKey();
        Attribute[] extensionAttributes = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (extensionAttributes != null) {
            for (Attribute extensionAttribute : extensionAttributes) {
                ASN1Encodable[] values = extensionAttribute.getAttributeValues();
                if (values != null) {
                    for (ASN1Encodable value : values) {
                        ASN1Primitive[] extensionPrimitives = decodeSequence(value.toASN1Primitive(), 0, Integer.MAX_VALUE);
                        for (ASN1Primitive extensionPrimitive : extensionPrimitives) {
                            ASN1Primitive[] sequence = decodeSequence(extensionPrimitive, 2, 3);
                            String extensionOID = decodePrimitive(sequence[0], ASN1ObjectIdentifier.class).getId();
                            boolean criticalFlag = true;
                            byte[] extensionData;
                            if (sequence.length == 3) {
                                criticalFlag = decodePrimitive(sequence[1], ASN1Boolean.class).isTrue();
                                extensionData = sequence[2].getEncoded();
                            } else {
                                extensionData = sequence[1].getEncoded();
                            }
                            if (criticalFlag) {
                                criticalExtensions.put(extensionOID, extensionData);
                            } else {
                                nonCriticalExtensions.put(extensionOID, extensionData);
                            }
                        }
                    }
                }
            }
        }
    } catch (GeneralSecurityException e) {
        throw new CertProviderException(e);
    }
    return new PKCS10CertificateRequest(csr, subject, publicKey, criticalExtensions, nonCriticalExtensions);
}
Also used : JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) HashMap(java.util.HashMap) Attribute(org.bouncycastle.asn1.pkcs.Attribute) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) CertProviderException(de.carne.certmgr.certs.CertProviderException) X500Principal(javax.security.auth.x500.X500Principal) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

CertProviderException (de.carne.certmgr.certs.CertProviderException)15 GeneralSecurityException (java.security.GeneralSecurityException)11 CertObjectStore (de.carne.certmgr.certs.CertObjectStore)5 PasswordRequiredException (de.carne.certmgr.certs.PasswordRequiredException)5 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)5 X509Certificate (java.security.cert.X509Certificate)4 Nullable (de.carne.check.Nullable)3 KeyPair (java.security.KeyPair)3 PrivateKey (java.security.PrivateKey)3 ArrayList (java.util.ArrayList)3 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)3 ContentSigner (org.bouncycastle.operator.ContentSigner)3 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)3 PKCSException (org.bouncycastle.pkcs.PKCSException)3 PlatformKeyStore (de.carne.certmgr.certs.security.PlatformKeyStore)2 IOException (java.io.IOException)2 InvalidKeyException (java.security.InvalidKeyException)2 KeyFactory (java.security.KeyFactory)2 KeyStore (java.security.KeyStore)2 SignatureException (java.security.SignatureException)2