use of com.github.zhenwei.core.asn1.x500.X500Name in project modules by assimbly.
the class CertificatesUtil method selfsignCertificate.
/**
* Generates a self signed certificate using the BouncyCastle lib.
*
* @param keyPair used for signing the certificate with PrivateKey
* @param hashAlgorithm Hash function
* @param cn Common Name to be used in the subject dn
* @param days validity period in days of the certificate
*
* @return self-signed X509Certificate
*
* @throws OperatorCreationException on creating a key id
* @throws CertIOException on building JcaContentSignerBuilder
* @throws CertificateException on getting certificate from provider
*/
public static X509Certificate selfsignCertificate(final KeyPair keyPair, final String hashAlgorithm, final String cn, final int days) throws OperatorCreationException, CertificateException, CertIOException {
final Instant now = Instant.now();
final Date notBefore = Date.from(now);
final Date notAfter = Date.from(now.plus(Duration.ofDays(days)));
final ContentSigner contentSigner = new JcaContentSignerBuilder(hashAlgorithm).build(keyPair.getPrivate());
final X500Name x500Name = new X500Name("CN=" + cn);
final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(x500Name, BigInteger.valueOf(now.toEpochMilli()), notBefore, notAfter, x500Name, keyPair.getPublic()).addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(keyPair.getPublic())).addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(keyPair.getPublic())).addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
return new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(certificateBuilder.build(contentSigner));
}
use of com.github.zhenwei.core.asn1.x500.X500Name in project identity-credential by google.
the class DeviceRequestParserTest method testDeviceRequestParserReaderAuthHelper.
void testDeviceRequestParserReaderAuthHelper(String curveName, String algorithm) throws Exception {
byte[] encodedSessionTranscript = Util.cborEncodeBytestring(new byte[] { 0x01, 0x02 });
Map<String, Map<String, Boolean>> mdlItemsToRequest = new HashMap<>();
Map<String, Boolean> mdlNsItems = new HashMap<>();
mdlNsItems.put("family_name", true);
mdlNsItems.put("portrait", false);
mdlItemsToRequest.put(MDL_NAMESPACE, mdlNsItems);
BouncyCastleProvider bcProvider = new BouncyCastleProvider();
KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, bcProvider);
ECGenParameterSpec ecSpec = new ECGenParameterSpec(curveName);
kpg.initialize(ecSpec);
KeyPair readerKeyPair = kpg.generateKeyPair();
kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC);
ecSpec = new ECGenParameterSpec("prime256v1");
kpg.initialize(ecSpec);
KeyPair trustPointKeyPair = kpg.generateKeyPair();
X500Name issuer = new X500Name("CN=Some Reader Authority");
X500Name subject = new X500Name("CN=Some Reader Key");
// Valid from now to five years from now.
Date now = new Date();
final long kMilliSecsInOneYear = 365L * 24 * 60 * 60 * 1000;
Date expirationDate = new Date(now.getTime() + 5 * kMilliSecsInOneYear);
BigInteger serial = new BigInteger("42");
JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, now, expirationDate, subject, readerKeyPair.getPublic());
ContentSigner signer = new JcaContentSignerBuilder("SHA256withECDSA").build(trustPointKeyPair.getPrivate());
byte[] encodedCert = builder.build(signer).getEncoded();
CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(encodedCert);
X509Certificate readerCert = (X509Certificate) cf.generateCertificate(bais);
ArrayList<X509Certificate> readerCertChain = new ArrayList<>();
readerCertChain.add(readerCert);
Map<String, byte[]> mdlRequestInfo = new HashMap<>();
mdlRequestInfo.put("foo", Util.cborEncodeString("bar"));
mdlRequestInfo.put("bar", Util.cborEncodeNumber(42));
Signature signature = Signature.getInstance(algorithm, bcProvider);
signature.initSign(readerKeyPair.getPrivate());
byte[] encodedDeviceRequest = new DeviceRequestGenerator().setSessionTranscript(encodedSessionTranscript).addDocumentRequest(MDL_DOCTYPE, mdlItemsToRequest, mdlRequestInfo, signature, readerCertChain).generate();
DeviceRequestParser.DeviceRequest deviceRequest = new DeviceRequestParser().setSessionTranscript(encodedSessionTranscript).setDeviceRequest(encodedDeviceRequest).parse();
Assert.assertEquals("1.0", deviceRequest.getVersion());
List<DeviceRequestParser.DocumentRequest> documentRequests = deviceRequest.getDocumentRequests();
Assert.assertTrue(documentRequests.get(0).getReaderAuthenticated());
}
use of com.github.zhenwei.core.asn1.x500.X500Name in project identity-credential by google.
the class SimpleReaderTrustStore method createCertificationTrustPath.
@Override
public List<X509Certificate> createCertificationTrustPath(List<X509Certificate> chain) {
List<X509Certificate> certificationTrustPath = new LinkedList<>();
// iterate backwards over list to find certificate in trust store
Iterator<X509Certificate> certIterator = chain.listIterator();
X509Certificate trustedCert = null;
while (certIterator.hasNext()) {
X509Certificate currentCert = certIterator.next();
certificationTrustPath.add(currentCert);
X500Name x500Name = new X500Name(currentCert.getIssuerX500Principal().getName());
trustedCert = trustedCertMap.get(x500Name);
if (trustedCert != null) {
certificationTrustPath.add(trustedCert);
break;
}
}
if (trustedCert != null) {
return certificationTrustPath;
}
return null;
}
use of com.github.zhenwei.core.asn1.x500.X500Name in project identity-credential by google.
the class SimpleIssuerTrustStore method createCertificationTrustPath.
@Override
public List<X509Certificate> createCertificationTrustPath(List<X509Certificate> chain) {
List<X509Certificate> certificationTrustPath = new LinkedList<>();
// iterate backwards over list to find certificate in trust store
Iterator<X509Certificate> certIterator = chain.listIterator();
X509Certificate trustedCert = null;
while (certIterator.hasNext()) {
X509Certificate currentCert = certIterator.next();
certificationTrustPath.add(currentCert);
X500Name x500Name = new X500Name(currentCert.getIssuerX500Principal().getName());
trustedCert = trustedCertMap.get(x500Name);
if (trustedCert != null) {
certificationTrustPath.add(trustedCert);
break;
}
}
if (trustedCert != null) {
return certificationTrustPath;
}
return null;
}
use of com.github.zhenwei.core.asn1.x500.X500Name 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));
}
Aggregations