Search in sources :

Example 41 with X500Name

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

the class CertificatesUtil method selfsignCertificate.

/**
 * Generates a self signed certificate using the BouncyCastle lib.
 *
 * @param keyPair used for signing the certificate with PrivateKey
 * @param hashAlgorithm Hash function
 * @param cn Common Name to be used in the subject dn
 * @param days validity period in days of the certificate
 *
 * @return self-signed X509Certificate
 *
 * @throws OperatorCreationException on creating a key id
 * @throws CertIOException on building JcaContentSignerBuilder
 * @throws CertificateException on getting certificate from provider
 */
public static X509Certificate selfsignCertificate(final KeyPair keyPair, final String hashAlgorithm, final String cn, final int days) throws OperatorCreationException, CertificateException, CertIOException {
    final Instant now = Instant.now();
    final Date notBefore = Date.from(now);
    final Date notAfter = Date.from(now.plus(Duration.ofDays(days)));
    final ContentSigner contentSigner = new JcaContentSignerBuilder(hashAlgorithm).build(keyPair.getPrivate());
    final X500Name x500Name = new X500Name("CN=" + cn);
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(x500Name, BigInteger.valueOf(now.toEpochMilli()), notBefore, notAfter, x500Name, keyPair.getPublic()).addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(keyPair.getPublic())).addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(keyPair.getPublic())).addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    return new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(certificateBuilder.build(contentSigner));
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) Instant(java.time.Instant) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) Date(java.util.Date) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 42 with X500Name

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

the class DeviceRequestParserTest method testDeviceRequestParserReaderAuthHelper.

void testDeviceRequestParserReaderAuthHelper(String curveName, String algorithm) throws Exception {
    byte[] encodedSessionTranscript = Util.cborEncodeBytestring(new byte[] { 0x01, 0x02 });
    Map<String, Map<String, Boolean>> mdlItemsToRequest = new HashMap<>();
    Map<String, Boolean> mdlNsItems = new HashMap<>();
    mdlNsItems.put("family_name", true);
    mdlNsItems.put("portrait", false);
    mdlItemsToRequest.put(MDL_NAMESPACE, mdlNsItems);
    BouncyCastleProvider bcProvider = new BouncyCastleProvider();
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, bcProvider);
    ECGenParameterSpec ecSpec = new ECGenParameterSpec(curveName);
    kpg.initialize(ecSpec);
    KeyPair readerKeyPair = kpg.generateKeyPair();
    kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC);
    ecSpec = new ECGenParameterSpec("prime256v1");
    kpg.initialize(ecSpec);
    KeyPair trustPointKeyPair = kpg.generateKeyPair();
    X500Name issuer = new X500Name("CN=Some Reader Authority");
    X500Name subject = new X500Name("CN=Some Reader Key");
    // Valid from now to five years from now.
    Date now = new Date();
    final long kMilliSecsInOneYear = 365L * 24 * 60 * 60 * 1000;
    Date expirationDate = new Date(now.getTime() + 5 * kMilliSecsInOneYear);
    BigInteger serial = new BigInteger("42");
    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, now, expirationDate, subject, readerKeyPair.getPublic());
    ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA").build(trustPointKeyPair.getPrivate());
    byte[] encodedCert = builder.build(signer).getEncoded();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(encodedCert);
    X509Certificate readerCert = (X509Certificate) cf.generateCertificate(bais);
    ArrayList<X509Certificate> readerCertChain = new ArrayList<>();
    readerCertChain.add(readerCert);
    Map<String, byte[]> mdlRequestInfo = new HashMap<>();
    mdlRequestInfo.put("foo", Util.cborEncodeString("bar"));
    mdlRequestInfo.put("bar", Util.cborEncodeNumber(42));
    Signature signature = Signature.getInstance(algorithm, bcProvider);
    signature.initSign(readerKeyPair.getPrivate());
    byte[] encodedDeviceRequest = new DeviceRequestGenerator().setSessionTranscript(encodedSessionTranscript).addDocumentRequest(MDL_DOCTYPE, mdlItemsToRequest, mdlRequestInfo, signature, readerCertChain).generate();
    DeviceRequestParser.DeviceRequest deviceRequest = new DeviceRequestParser().setSessionTranscript(encodedSessionTranscript).setDeviceRequest(encodedDeviceRequest).parse();
    Assert.assertEquals("1.0", deviceRequest.getVersion());
    List<DeviceRequestParser.DocumentRequest> documentRequests = deviceRequest.getDocumentRequests();
    Assert.assertTrue(documentRequests.get(0).getReaderAuthenticated());
}
Also used : HashMap(java.util.HashMap) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) ArrayList(java.util.ArrayList) X500Name(org.bouncycastle.asn1.x500.X500Name) CertificateFactory(java.security.cert.CertificateFactory) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) KeyPair(java.security.KeyPair) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyPairGenerator(java.security.KeyPairGenerator) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) BigInteger(java.math.BigInteger) HashMap(java.util.HashMap) Map(java.util.Map)

Example 43 with X500Name

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

the class SimpleReaderTrustStore method createCertificationTrustPath.

@Override
public List<X509Certificate> createCertificationTrustPath(List<X509Certificate> chain) {
    List<X509Certificate> certificationTrustPath = new LinkedList<>();
    // iterate backwards over list to find certificate in trust store
    Iterator<X509Certificate> certIterator = chain.listIterator();
    X509Certificate trustedCert = null;
    while (certIterator.hasNext()) {
        X509Certificate currentCert = certIterator.next();
        certificationTrustPath.add(currentCert);
        X500Name x500Name = new X500Name(currentCert.getIssuerX500Principal().getName());
        trustedCert = trustedCertMap.get(x500Name);
        if (trustedCert != null) {
            certificationTrustPath.add(trustedCert);
            break;
        }
    }
    if (trustedCert != null) {
        return certificationTrustPath;
    }
    return null;
}
Also used : X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList)

Example 44 with X500Name

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

the class SimpleIssuerTrustStore method createCertificationTrustPath.

@Override
public List<X509Certificate> createCertificationTrustPath(List<X509Certificate> chain) {
    List<X509Certificate> certificationTrustPath = new LinkedList<>();
    // iterate backwards over list to find certificate in trust store
    Iterator<X509Certificate> certIterator = chain.listIterator();
    X509Certificate trustedCert = null;
    while (certIterator.hasNext()) {
        X509Certificate currentCert = certIterator.next();
        certificationTrustPath.add(currentCert);
        X500Name x500Name = new X500Name(currentCert.getIssuerX500Principal().getName());
        trustedCert = trustedCertMap.get(x500Name);
        if (trustedCert != null) {
            certificationTrustPath.add(trustedCert);
            break;
        }
    }
    if (trustedCert != null) {
        return certificationTrustPath;
    }
    return null;
}
Also used : X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList)

Example 45 with X500Name

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

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)510 X509Certificate (java.security.cert.X509Certificate)183 BigInteger (java.math.BigInteger)175 Date (java.util.Date)169 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)158 ContentSigner (org.bouncycastle.operator.ContentSigner)149 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)145 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)127 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)127 IOException (java.io.IOException)108 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)100 RDN (org.bouncycastle.asn1.x500.RDN)94 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)93 KeyPair (java.security.KeyPair)79 X500Name (sun.security.x509.X500Name)68 PrivateKey (java.security.PrivateKey)64 CertificateException (java.security.cert.CertificateException)64 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)59 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)55 GeneralName (org.bouncycastle.asn1.x509.GeneralName)55