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