Search in sources :

Example 6 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions 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 7 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project carapaceproxy by diennea.

the class OcspRequestBuilder method build.

/**
 * ATTENTION: The returned {@link OCSPReq} is not re-usable/cacheable! It contains a one-time nonce and CA's will (should) reject subsequent requests that have the same nonce value.
 */
public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException {
    SecureRandom generator = checkNotNull(this.generator, "generator");
    DigestCalculator calculator = checkNotNull(this.calculator, "calculator");
    X509Certificate certificate = checkNotNull(this.certificate, "certificate");
    X509Certificate issuer = checkNotNull(this.issuer, "issuer");
    BigInteger serial = certificate.getSerialNumber();
    CertificateID certId = new CertificateID(calculator, new X509CertificateHolder(issuer.getEncoded()), serial);
    OCSPReqBuilder builder = new OCSPReqBuilder();
    builder.addRequest(certId);
    byte[] nonce = new byte[8];
    generator.nextBytes(nonce);
    Extension[] extensions = new Extension[] { new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)) };
    builder.setRequestExtensions(new Extensions(extensions));
    return builder.build();
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) SecureRandom(java.security.SecureRandom) BigInteger(java.math.BigInteger) Extensions(org.bouncycastle.asn1.x509.Extensions) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) X509Certificate(java.security.cert.X509Certificate) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 8 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project itext2 by albfernandez.

the class OcspClientBouncyCastle method generateOCSPRequest.

/**
 * Generates an OCSP request using BouncyCastle.
 * @param issuerCert	certificate of the issues
 * @param serialNumber	serial number
 * @return	an OCSP request
 * @throws OCSPException
 * @throws IOException
 */
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException, OperatorException, CertificateEncodingException {
    // Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder();
    DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build();
    DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1);
    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(digestCalculator, new JcaX509CertificateHolder(issuerCert), serialNumber);
    // basic request generation with nonce
    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(id);
    // create details for nonce extension
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()));
    gen.setRequestExtensions(new Extensions(new Extension[] { ext }));
    return gen.build();
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) DigestCalculator(org.bouncycastle.operator.DigestCalculator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) Extensions(org.bouncycastle.asn1.x509.Extensions) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 9 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project attestation by TokenScript.

the class HelperTest method makeUnsignedx509Att.

/* the unsigned x509 attestation will have a subject of "CN=0x2042424242424564648" */
public static Attestation makeUnsignedx509Att(AsymmetricKeyParameter key) throws IOException {
    Attestation att = new Attestation();
    // =v3 since counting starts from 0
    att.setVersion(2);
    att.setSerialNumber(42);
    // ECDSA with SHA256 which is needed for a proper x509
    att.setSigningAlgorithm(SignedIdentifierAttestation.ECDSA_WITH_SHA256);
    att.setIssuer("CN=ALX");
    Date now = new Date();
    att.setNotValidBefore(now);
    att.setNotValidAfter(new Date(System.currentTimeMillis() + VALIDITY));
    att.setSubject("CN=0x2042424242424564648");
    SubjectPublicKeyInfo spki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(key);
    att.setSubjectPublicKeyInfo(spki);
    ASN1EncodableVector extensions = new ASN1EncodableVector();
    extensions.add(Attestation.OID_OCTETSTRING);
    extensions.add(ASN1Boolean.TRUE);
    extensions.add(new DEROctetString("hello world".getBytes()));
    // Double Sequence is needed to be compatible with X509V3
    att.setExtensions(new DERSequence(new DERSequence(extensions)));
    assertTrue(att.isValidX509());
    return att;
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 10 with Extensions

use of com.github.zhenwei.core.asn1.x509.Extensions in project attestation by TokenScript.

the class ParserTest method testSunshine.

@Test
public void testSunshine() throws Exception {
    String request = Files.readString(Path.of("src/test/data/verification_request.json"));
    String response = Files.readString(Path.of("src/test/data/verification_response.json"));
    Parser parser = new Parser(new JSONObject(request), (new JSONObject(response)).getJSONObject("Record"));
    Map<String, X500Name> names = parser.getX500Names();
    Map<String, Extensions> extensions = parser.getExtensions();
    Assertions.assertEquals(names.size(), 2);
    Assertions.assertEquals(extensions.size(), 2);
    Assertions.assertTrue(names.containsKey("National Change of Address"));
    Assertions.assertTrue(names.containsKey("NZ Driver Licence"));
    Assertions.assertTrue(extensions.containsKey("National Change of Address"));
    Assertions.assertTrue(extensions.containsKey("NZ Driver Licence"));
    Set<String> expectedNameFields = new HashSet<String>(Arrays.asList(Parser.OID_COUNTRY_NAME, Parser.OID_GIVEN_NAME, Parser.OID_SUR_NAME, Parser.OID_STATE_OR_PROVINCE_NAME));
    for (X500Name name : names.values()) {
        Set<String> oids = Arrays.stream(name.getAttributeTypes()).map(c -> c.toString()).collect(Collectors.toSet());
        Assertions.assertEquals(oids.size(), expectedNameFields.size());
        Assertions.assertEquals(oids, expectedNameFields);
        Set<String> encs = Arrays.stream(name.getRDNs()).map(c -> c.getTypesAndValues()[0].getValue().toString()).collect(Collectors.toSet());
        Assertions.assertEquals(encs.size(), 4);
        Assertions.assertTrue(encs.contains("NZ"));
        Assertions.assertTrue(encs.contains("JaneKone"));
        Assertions.assertTrue(encs.contains("Doe"));
        Assertions.assertTrue(encs.contains("Queensland"));
    }
    Set<String> expectedDLExtensions = new HashSet<>(Arrays.asList(Parser.OID_STREET_ADDRESS, Parser.OID_SUBURB, Parser.OID_POSTAL_CODE, Parser.OID_DATE_OF_BIRTH));
    Set<String> oids = Arrays.stream(extensions.get("NZ Driver Licence").getExtensionOIDs()).map(c -> c.toString()).collect(Collectors.toSet());
    Assertions.assertEquals(expectedDLExtensions.size(), oids.size());
    Assertions.assertEquals(expectedDLExtensions, oids);
    Set<String> encs = Arrays.stream(extensions.get("NZ Driver Licence").getExtensionOIDs()).map(c -> new String(extensions.get("NZ Driver Licence").getExtension(c).getExtnValue().getOctets())).collect(Collectors.toSet());
    Assertions.assertEquals(encs.size(), 4);
    Assertions.assertTrue(encs.contains("1973111100"));
    Assertions.assertTrue(encs.contains("13 Markeri Street"));
    Assertions.assertTrue(encs.contains("4218"));
    Assertions.assertTrue(encs.contains("Mermaid Beach"));
    Set<String> expectedCAExtensions = new HashSet<>(Arrays.asList(Parser.OID_STREET_ADDRESS, Parser.OID_SUBURB, Parser.OID_POSTAL_CODE));
    Set<String> caOids = Arrays.stream(extensions.get("National Change of Address").getExtensionOIDs()).map(c -> c.toString()).collect(Collectors.toSet());
    Assertions.assertEquals(expectedCAExtensions.size(), caOids.size());
    Assertions.assertEquals(expectedCAExtensions, caOids);
    Set<String> caEncs = Arrays.stream(extensions.get("National Change of Address").getExtensionOIDs()).map(c -> new String(extensions.get("National Change of Address").getExtension(c).getExtnValue().getOctets())).collect(Collectors.toSet());
    Assertions.assertEquals(caEncs.size(), 3);
    Assertions.assertTrue(caEncs.contains("13 Markeri Street"));
    Assertions.assertTrue(caEncs.contains("4218"));
    Assertions.assertTrue(caEncs.contains("Mermaid Beach"));
}
Also used : HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test) Arrays(java.util.Arrays) X500Name(org.bouncycastle.asn1.x500.X500Name) JSONObject(org.json.JSONObject) Files(java.nio.file.Files) Map(java.util.Map) Assertions(org.junit.jupiter.api.Assertions) Set(java.util.Set) Path(java.nio.file.Path) Collectors(java.util.stream.Collectors) Extensions(org.bouncycastle.asn1.x509.Extensions) JSONObject(org.json.JSONObject) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test)

Aggregations

Extensions (org.bouncycastle.asn1.x509.Extensions)113 Extension (org.bouncycastle.asn1.x509.Extension)89 IOException (java.io.IOException)72 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)67 Enumeration (java.util.Enumeration)57 HashSet (java.util.HashSet)49 DEROctetString (org.bouncycastle.asn1.DEROctetString)49 X500Name (org.bouncycastle.asn1.x500.X500Name)46 BigInteger (java.math.BigInteger)45 Set (java.util.Set)36 X509Certificate (java.security.cert.X509Certificate)35 Date (java.util.Date)35 GeneralName (org.bouncycastle.asn1.x509.GeneralName)35 ContentSigner (org.bouncycastle.operator.ContentSigner)32 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)29 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)28 ArrayList (java.util.ArrayList)28 CertificateException (java.security.cert.CertificateException)27 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)27 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)27