Search in sources :

Example 41 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project ca3sCore by kuehne-trustable-de.

the class CertificateUtil method getCertificatePolicies.

public List<String> getCertificatePolicies(X509Certificate x509Cert) {
    ArrayList<String> certificatePolicyIds = new ArrayList<>();
    byte[] extVal = x509Cert.getExtensionValue(Extension.certificatePolicies.getId());
    if (extVal == null) {
        return certificatePolicyIds;
    }
    try {
        org.bouncycastle.asn1.x509.CertificatePolicies cf = org.bouncycastle.asn1.x509.CertificatePolicies.getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
        PolicyInformation[] information = cf.getPolicyInformation();
        for (PolicyInformation p : information) {
            ASN1ObjectIdentifier aIdentifier = p.getPolicyIdentifier();
            certificatePolicyIds.add(aIdentifier.getId());
        }
    } catch (IOException ex) {
        LOG.error("Failed to get OCSP URL for certificate '" + x509Cert.getSubjectX500Principal().getName() + "'", ex);
    }
    return certificatePolicyIds;
}
Also used : org.bouncycastle.asn1.x509(org.bouncycastle.asn1.x509) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) IOException(java.io.IOException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 42 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project ca3sCore by kuehne-trustable-de.

the class CertificateUtil method getSANList.

public Set<GeneralName> getSANList(Pkcs10RequestHolder p10ReqHolder) {
    Set<GeneralName> generalNameSet = new HashSet<>();
    for (Attribute attr : p10ReqHolder.getReqAttributes()) {
        if (PKCSObjectIdentifiers.pkcs_9_at_extensionRequest.equals(attr.getAttrType())) {
            ASN1Set valueSet = attr.getAttrValues();
            LOG.debug("ExtensionRequest / AttrValues has {} elements", valueSet.size());
            for (ASN1Encodable asn1Enc : valueSet) {
                DERSequence derSeq = (DERSequence) asn1Enc;
                LOG.debug("ExtensionRequest / DERSequence has {} elements", derSeq.size());
                LOG.debug("ExtensionRequest / DERSequence[0] is a  {}", derSeq.getObjectAt(0).getClass().getName());
                DERSequence derSeq2 = (DERSequence) derSeq.getObjectAt(0);
                LOG.debug("ExtensionRequest / DERSequence2 has {} elements", derSeq2.size());
                LOG.debug("ExtensionRequest / DERSequence2[0] is a  {}", derSeq2.getObjectAt(0).getClass().getName());
                ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) (derSeq2.getObjectAt(0));
                if (Extension.subjectAlternativeName.equals(objId)) {
                    DEROctetString derStr = (DEROctetString) derSeq2.getObjectAt(1);
                    GeneralNames names = GeneralNames.getInstance(derStr.getOctets());
                    LOG.debug("Attribute value SAN" + names);
                    LOG.debug("SAN values #" + names.getNames().length);
                    for (GeneralName gnSAN : names.getNames()) {
                        LOG.debug("GN " + gnSAN.toString());
                        generalNameSet.add(gnSAN);
                    }
                } else {
                    LOG.info("Unexpected Extensions Attribute value " + objId.getId());
                }
            }
        }
    }
    return generalNameSet;
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) Attribute(org.bouncycastle.asn1.pkcs.Attribute) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 43 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project modules by assimbly.

the class CertificatesUtil method selfsignCertificate2.

public static Certificate selfsignCertificate2(KeyPair keyPair, String subjectDN) throws OperatorCreationException, CertificateException, IOException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    long now = System.currentTimeMillis();
    Date startDate = new Date(now);
    X500Name dnName = new X500Name("CN=" + subjectDN);
    // <-- Using the current timestamp as the certificate serial number
    BigInteger certSerialNumber = new BigInteger(Long.toString(now));
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    // <-- 2 Yr validity
    calendar.add(Calendar.YEAR, 2);
    Date endDate = calendar.getTime();
    // <-- Use appropriate signature algorithm based on your keyPair algorithm.
    String signatureAlgorithm = "SHA256WithRSA";
    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic());
    // Extensions --------------------------
    // Basic Constraints
    // <-- true for CA, false for EndEntity
    BasicConstraints basicConstraints = new BasicConstraints(true);
    // Basic Constraints is usually marked as critical.
    certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);
    return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) Calendar(java.util.Calendar) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) Provider(java.security.Provider) BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 44 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project identity-credential by google.

the class CertificateGenerator method generateCertificate.

static X509Certificate generateCertificate(DataMaterial data, CertificateMaterial certMaterial, KeyMaterial keyMaterial) throws CertIOException, CertificateException, OperatorCreationException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    Optional<X509Certificate> issuerCert = keyMaterial.issuerCertificate();
    X500Name subjectDN = new X500Name(data.subjectDN());
    // doesn't work, get's reordered
    // issuerCert.isPresent() ? new X500Name(issuerCert.get().getSubjectX500Principal().getName()) : subjectDN;
    X500Name issuerDN = new X500Name(data.issuerDN());
    ContentSigner contentSigner = new JcaContentSignerBuilder(keyMaterial.signingAlgorithm()).build(keyMaterial.signingKey());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, certMaterial.serialNumber(), certMaterial.startDate(), certMaterial.endDate(), subjectDN, keyMaterial.publicKey());
    // Extensions --------------------------
    JcaX509ExtensionUtils jcaX509ExtensionUtils;
    try {
        jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    if (issuerCert.isPresent()) {
        try {
            // adds 3 more fields, not present in other cert
            // AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCert.get());
            AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCert.get().getPublicKey());
            certBuilder.addExtension(Extension.authorityKeyIdentifier, NOT_CRITICAL, authorityKeyIdentifier);
        } catch (IOException e) {
            // CertificateEncodingException |
            throw new RuntimeException(e);
        }
    }
    SubjectKeyIdentifier subjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyMaterial.publicKey());
    certBuilder.addExtension(Extension.subjectKeyIdentifier, NOT_CRITICAL, subjectKeyIdentifier);
    KeyUsage keyUsage = new KeyUsage(certMaterial.keyUsage());
    certBuilder.addExtension(Extension.keyUsage, CRITICAL, keyUsage);
    // IssuerAlternativeName
    Optional<String> issuerAlternativeName = data.issuerAlternativeName();
    if (issuerAlternativeName.isPresent()) {
        GeneralNames issuerAltName = new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, issuerAlternativeName.get()));
        certBuilder.addExtension(Extension.issuerAlternativeName, NOT_CRITICAL, issuerAltName);
    }
    // Basic Constraints
    int pathLengthConstraint = certMaterial.pathLengthConstraint();
    if (pathLengthConstraint != CertificateMaterial.PATHLENGTH_NOT_A_CA) {
        // TODO doesn't work for certificate chains != 2 in size
        BasicConstraints basicConstraints = new BasicConstraints(pathLengthConstraint);
        certBuilder.addExtension(Extension.basicConstraints, CRITICAL, basicConstraints);
    }
    Optional<String> extendedKeyUsage = certMaterial.extendedKeyUsage();
    if (extendedKeyUsage.isPresent()) {
        KeyPurposeId keyPurpose = KeyPurposeId.getInstance(new ASN1ObjectIdentifier(extendedKeyUsage.get()));
        ExtendedKeyUsage extKeyUsage = new ExtendedKeyUsage(new KeyPurposeId[] { keyPurpose });
        certBuilder.addExtension(Extension.extendedKeyUsage, CRITICAL, extKeyUsage);
    }
    // DEBUG setProvider(bcProvider) removed before getCertificate
    return new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) ContentSigner(org.bouncycastle.operator.ContentSigner) IOException(java.io.IOException) CertIOException(org.bouncycastle.cert.CertIOException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X509Certificate(java.security.cert.X509Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Provider(java.security.Provider) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 45 with ASN1ObjectIdentifier

use of com.github.zhenwei.core.asn1.ASN1ObjectIdentifier in project identity-credential by google.

the class CredentialData method generateAuthenticationKeyCert.

@NonNull
static X509Certificate generateAuthenticationKeyCert(String authKeyAlias, String credentialKeyAlias, byte[] proofOfProvisioningSha256) {
    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        X509Certificate selfSignedCert = (X509Certificate) ks.getCertificate(authKeyAlias);
        PublicKey publicKey = selfSignedCert.getPublicKey();
        PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) ks.getEntry(credentialKeyAlias, null)).getPrivateKey();
        X500Name issuer = new X500Name("CN=Android Identity Credential Key");
        X500Name subject = new X500Name("CN=Android Identity Credential Authentication Key");
        Date now = new Date();
        final long kMilliSecsInOneYear = 365L * 24 * 60 * 60 * 1000;
        Date expirationDate = new Date(now.getTime() + kMilliSecsInOneYear);
        BigInteger serial = new BigInteger("1");
        JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, now, expirationDate, subject, publicKey);
        if (proofOfProvisioningSha256 != null) {
            byte[] encodedProofOfBinding = Util.cborEncode(new CborBuilder().addArray().add("ProofOfBinding").add(proofOfProvisioningSha256).end().build().get(0));
            builder.addExtension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.1.26"), false, encodedProofOfBinding);
        }
        ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA").build(privateKey);
        byte[] encodedCert = builder.build(signer).getEncoded();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(encodedCert);
        X509Certificate result = (X509Certificate) cf.generateCertificate(bais);
        return result;
    } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException | CertificateException | OperatorCreationException e) {
        throw new IllegalStateException("Error signing public key with private key", e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateFactory(java.security.cert.CertificateFactory) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) UnrecoverableEntryException(java.security.UnrecoverableEntryException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PublicKey(java.security.PublicKey) ContentSigner(org.bouncycastle.operator.ContentSigner) IOException(java.io.IOException) CertIOException(org.bouncycastle.cert.CertIOException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CborBuilder(co.nstant.in.cbor.CborBuilder) NonNull(androidx.annotation.NonNull)

Aggregations

ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)545 IOException (java.io.IOException)161 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)126 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)87 DEROctetString (org.bouncycastle.asn1.DEROctetString)87 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)71 Enumeration (java.util.Enumeration)70 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)70 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)69 ArrayList (java.util.ArrayList)65 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)64 BigInteger (java.math.BigInteger)60 DERSequence (org.bouncycastle.asn1.DERSequence)60 HashSet (java.util.HashSet)57 DERIA5String (org.bouncycastle.asn1.DERIA5String)52 X500Name (org.bouncycastle.asn1.x500.X500Name)52 X509Certificate (java.security.cert.X509Certificate)50 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)47 Extension (org.bouncycastle.asn1.x509.Extension)46