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"));
}
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;
}
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 });
}
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);
}
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);
}
Aggregations