Search in sources :

Example 56 with X500Name

use of com.github.zhenwei.core.asn1.x500.X500Name in project fabric-gateway by hyperledger.

the class X509Credentials method generateCertificate.

private X509Certificate generateCertificate(KeyPair keyPair) {
    X500Name dnName = new X500Name("CN=John Doe");
    // Yesterday
    Date validityBeginDate = new Date(System.currentTimeMillis() - 24L * 60 * 60 * 1000);
    // 2 years from now
    Date validityEndDate = new Date(System.currentTimeMillis() + 2L * 365 * 24 * 60 * 60 * 1000);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(dnName, BigInteger.valueOf(System.currentTimeMillis()), validityBeginDate, validityEndDate, Locale.getDefault(), dnName, subPubKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    try {
        ContentSigner contentSigner = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()));
        X509CertificateHolder holder = builder.build(contentSigner);
        return new JcaX509CertificateConverter().getCertificate(holder);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (OperatorCreationException | CertificateException e) {
        throw new RuntimeException(e);
    }
}
Also used : ContentSigner(org.bouncycastle.operator.ContentSigner) UncheckedIOException(java.io.UncheckedIOException) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) Date(java.util.Date) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BcECContentSignerBuilder(org.bouncycastle.operator.bc.BcECContentSignerBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 57 with X500Name

use of com.github.zhenwei.core.asn1.x500.X500Name in project attestation by TokenScript.

the class IdentifierAttestationTest method testOtherSubject.

@Test
public void testOtherSubject() throws Exception {
    IdentifierAttestation initial = HelperTest.makeUnsignedStandardAtt(subjectKeys.getPublic(), BigInteger.ONE, mail);
    Field field = initial.getClass().getSuperclass().getDeclaredField("subject");
    field.setAccessible(true);
    // Change the subject
    field.set(initial, new X500Name("CN=John Doe"));
    // Common Names are allowed
    assertTrue(initial.checkValidity());
}
Also used : Field(java.lang.reflect.Field) X500Name(org.bouncycastle.asn1.x500.X500Name) Test(org.junit.jupiter.api.Test)

Example 58 with X500Name

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

Example 59 with X500Name

use of com.github.zhenwei.core.asn1.x500.X500Name in project attestation by TokenScript.

the class Attestor method constructAttestations.

/**
 * Constructs a list of X509 attestations to each of the relevant DatasourceName lists of elements
 * in the response json.
 *
 * @param request Json request in a Sring - verification request that was sent to Trulioo Global Gateway†
 * @param verifyRecord Json object of the Record in verifyResponse, from Trulioo Global Gateway‡
 * @param signature DER encoded signature of exactly the json request string encoded as UTF-8 using a Secp256k1 key with Keccak
 * @param userPK user's public key (SubjectPublicKeyInfo object)
 * @return List of DER encoded x509 attestations
 *
 * † An example can be found https://developer.trulioo.com/docs/identity-verification-step-6-verify
 * ‡ Observe the "Record" in https://developer.trulioo.com/docs/identity-verification-verify-response
 */
public List<X509CertificateHolder> constructAttestations(String request, JSONObject verifyRecord, byte[] signature, AsymmetricKeyParameter userPK) {
    if (!SignatureUtil.verifySha256(request.getBytes(StandardCharsets.UTF_8), signature, userPK)) {
        throw ExceptionUtil.throwException(logger, new IllegalArgumentException("Request signature verification failed. " + "Make sure that your message is unaltered, signature is created by hashing the message with SHA256" + "and using a key of secp256k1 type."));
    }
    List<X509CertificateHolder> res = new ArrayList<>();
    Parser parser = new Parser(new JSONObject(request), verifyRecord);
    Map<String, X500Name> subjectNames = parser.getX500Names();
    Map<String, Extensions> subjectExtensions = parser.getExtensions();
    for (String currentAttName : subjectNames.keySet()) {
        try {
            long time = System.currentTimeMillis();
            V3TBSCertificateGenerator certBuilder = new V3TBSCertificateGenerator();
            certBuilder.setSignature(serverSigningAlgo);
            certBuilder.setIssuer(serverInfo);
            certBuilder.setSerialNumber(new ASN1Integer(time));
            certBuilder.setStartDate(new Time(new Date(time)));
            certBuilder.setEndDate(new Time(new Date(time + lifeTime)));
            SubjectPublicKeyInfo spki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(userPK);
            // // todo hack to create a valid spki without ECNamedParameters
            // spki = new SubjectPublicKeyInfo(new AlgorithmIdentifier(new ASN1ObjectIdentifier(OID_ECDSA)),
            // spki.getPublicKeyData());
            certBuilder.setSubjectPublicKeyInfo(spki);
            certBuilder.setSubject(subjectNames.get(currentAttName));
            certBuilder.setExtensions(subjectExtensions.get(currentAttName));
            TBSCertificate tbsCert = certBuilder.generateTBSCertificate();
            res.add(new X509CertificateHolder(constructSignedAttestation(tbsCert)));
            // To ensure that we get a new serial number for every cert
            Thread.sleep(1);
        } catch (IOException e) {
            throw ExceptionUtil.makeRuntimeException(logger, "Could not parse server key", e);
        } catch (InterruptedException e) {
            throw ExceptionUtil.makeRuntimeException(logger, "Could not sleep", e);
        }
    }
    return res;
}
Also used : ArrayList(java.util.ArrayList) Time(org.bouncycastle.asn1.x509.Time) DERBitString(org.bouncycastle.asn1.DERBitString) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) JSONObject(org.json.JSONObject) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) V3TBSCertificateGenerator(org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Example 60 with X500Name

use of com.github.zhenwei.core.asn1.x500.X500Name in project attestation by TokenScript.

the class IdentifierAttestation method makeLabeledURI.

/**
 * @param label the label of the URL, similar to what is inside <a>...</a>
 * @param URL the URL itself, similar to what is in <a href="...">, note that
 * it should already be URLencoded therefore not containing space
 */
private X500Name makeLabeledURI(String label, String URL) {
    DERUTF8String labeledURLValue = new DERUTF8String(URL + " " + label);
    RDN rdn = new RDN(LABELED_URI, labeledURLValue);
    return new X500Name(new RDN[] { rdn });
}
Also used : DERUTF8String(org.bouncycastle.asn1.DERUTF8String) X500Name(org.bouncycastle.asn1.x500.X500Name) RDN(org.bouncycastle.asn1.x500.RDN)

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