Search in sources :

Example 56 with X500Name

use of org.mozilla.jss.netscape.security.x509.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 57 with X500Name

use of org.mozilla.jss.netscape.security.x509.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 58 with X500Name

use of org.mozilla.jss.netscape.security.x509.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)

Example 59 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project security-lib by ncsa.

the class CertUtil method createCertRequest.

/**
 * This is merely public in case you want to use it. Generally use the {@link #createCertRequest(java.security.KeyPair)}
 *
 * @param keypair
 * @param sigAlgName
 * @param provider
 * @param dn
 * @return
 * @throws SignatureException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public static MyPKCS10CertRequest createCertRequest(KeyPair keypair, String sigAlgName, String dn, String provider) throws SignatureException, InvalidKeyException, NoSuchProviderException, NoSuchAlgorithmException, IOException {
    // String sigAlg = "SHA512WithRSA";
    PKCS10 pkcs10 = new PKCS10(keypair.getPublic());
    Signature signature = Signature.getInstance(sigAlgName);
    signature.initSign(keypair.getPrivate());
    try {
        X500Name x500Name = null;
        if (dn == null) {
            x500Name = new X500Name(DEFAULT_PKCS10_DISTINGUISHED_NAME, "OU", "OU", "USA");
        } else {
            x500Name = new X500Name(dn, "OU", "OU", "USA");
        }
        pkcs10.encodeAndSign(x500Name, signature);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bs);
        pkcs10.print(ps);
        byte[] c = bs.toByteArray();
        if (ps != null) {
            ps.close();
        }
        if (bs != null) {
            bs.close();
        }
    } catch (RuntimeException rx) {
        throw rx;
    } catch (Throwable th) {
        throw new GeneralException("Error creating cert request", th);
    }
    return new MySunPKCS_CR(pkcs10);
}
Also used : GeneralException(edu.uiuc.ncsa.security.core.exceptions.GeneralException) X500Name(sun.security.x509.X500Name) PKCS10(sun.security.pkcs10.PKCS10)

Example 60 with X500Name

use of org.mozilla.jss.netscape.security.x509.X500Name in project aws-greengrass-nucleus by aws-greengrass.

the class EncryptionUtilsTest method generateCertificateFile.

public static Pair<Path, KeyPair> generateCertificateFile(int keySize, boolean pem, Path filepath, boolean ec) throws Exception {
    KeyPair keyPair;
    if (ec) {
        keyPair = generateECKeyPair(keySize);
    } else {
        keyPair = generateRSAKeyPair(keySize);
    }
    X500Name name = new X500Name("CN=ROOT");
    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    Date start = new Date();
    Date until = Date.from(LocalDate.now().plus(365, ChronoUnit.DAYS).atStartOfDay().toInstant(ZoneOffset.UTC));
    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(name, new BigInteger(10, new SecureRandom()), start, until, name, subjectPublicKeyInfo);
    String signingAlgo = "SHA256WithRSA";
    if (ec) {
        signingAlgo = "SHA256WITHECDSA";
    }
    ContentSigner signer = new JcaContentSignerBuilder(signingAlgo).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate());
    X509CertificateHolder holder = builder.build(signer);
    X509Certificate certificate = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);
    if (pem) {
        try (PrintWriter out = new PrintWriter(filepath.toFile())) {
            out.println("-----BEGIN CERTIFICATE-----");
            out.println(new String(Base64.encodeBase64(certificate.getEncoded())));
            out.println("-----END CERTIFICATE-----");
        }
    } else {
        try (OutputStream outputStream = Files.newOutputStream(filepath)) {
            outputStream.write(certificate.getEncoded());
        }
    }
    return new Pair<>(filepath, keyPair);
}
Also used : KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) OutputStream(java.io.OutputStream) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) LocalDate(java.time.LocalDate) X509Certificate(java.security.cert.X509Certificate) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) PrintWriter(java.io.PrintWriter) KeyPair(java.security.KeyPair)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)510 X509Certificate (java.security.cert.X509Certificate)182 BigInteger (java.math.BigInteger)175 Date (java.util.Date)168 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)104 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)100 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)93 KeyPair (java.security.KeyPair)79 RDN (org.bouncycastle.asn1.x500.RDN)75 X500Name (sun.security.x509.X500Name)68 PrivateKey (java.security.PrivateKey)64 CertificateException (java.security.cert.CertificateException)64 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)55 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)55 SecureRandom (java.security.SecureRandom)54