public X509Certificate generate(String dn, KeyPair keyPair) throws CertificateException { try { Security.addProvider(new BouncyCastleProvider()); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); X500Name name = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + days * 86400000L); BigInteger sn = new BigInteger(64, new SecureRandom()); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(name, sn, from, to, name, subPubKeyInfo); if (subjectAltName != null) v3CertGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName); X509CertificateHolder certificateHolder = v3CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); } catch (CertificateException ce) { throw ce; } catch (Exception e) { throw new CertificateException(e); } }
/** * 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(); }
public byte[] getExtensionValue(String oid) { Extensions extensions = cert.getAcinfo().getExtensions(); if (extensions != null) { Extension ext = extensions.getExtension(new ASN1ObjectIdentifier(oid)); if (ext != null) { try { return ext.getExtnValue().getEncoded(ASN1Encoding.DER); } catch (Exception e) { throw new RuntimeException("error encoding " + e.toString()); } } } return null; }
private Set getExtensionOIDs( boolean critical) { Extensions extensions = cert.getAcinfo().getExtensions(); if (extensions != null) { Set set = new HashSet(); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); Extension ext = extensions.getExtension(oid); if (ext.isCritical() == critical) { set.add(oid.getId()); } } return set; } return null; }
/** * Add a given extension field for the standard extensions tag (tag 3) * copying the extension value from another certificate. * * @param oid the OID defining the extension type. * @param isCritical true if the copied extension is to be marked as critical, false otherwise. * @param certHolder the holder for the certificate that the extension is to be copied from. * @return this builder object. */ public X509v3CertificateBuilder copyAndAddExtension( ASN1ObjectIdentifier oid, boolean isCritical, X509CertificateHolder certHolder) { Certificate cert = certHolder.toASN1Structure(); Extension extension = cert.getTBSCertificate().getExtensions().getExtension(oid); if (extension == null) { throw new NullPointerException("extension " + oid + " not present"); } extGenerator.addExtension(oid, isCritical, extension.getExtnValue().getOctets()); return this; }
public X509CRLEntryHolder getRevokedCertificate(BigInteger serialNumber) { GeneralNames currentCA = issuerName; for (Enumeration en = x509CRL.getRevokedCertificateEnumeration(); en.hasMoreElements();) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)en.nextElement(); if (entry.getUserCertificate().getValue().equals(serialNumber)) { return new X509CRLEntryHolder(entry, isIndirect, currentCA); } if (isIndirect && entry.hasExtensions()) { Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); if (currentCaName != null) { currentCA = GeneralNames.getInstance(currentCaName.getParsedValue()); } } } return null; }
public byte[] getExtensionValue(String oid) { Extensions exts = c.getTBSCertificate().getExtensions(); if (exts != null) { Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); if (ext != null) { try { return ext.getExtnValue().getEncoded(); } catch (Exception e) { throw new IllegalStateException("error parsing " + e.toString()); } } } return null; }
public byte[] getExtensionValue(String oid) { Extensions exts = c.getTBSCertList().getExtensions(); if (exts != null) { Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); if (ext != null) { try { return ext.getExtnValue().getEncoded(); } catch (Exception e) { throw new IllegalStateException("error parsing " + e.toString()); } } } return null; }
private Set loadCRLEntries() { Set entrySet = new HashSet(); Enumeration certs = c.getRevokedCertificateEnumeration(); X500Name previousCertificateIssuer = null; // the issuer while (certs.hasMoreElements()) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); entrySet.add(crlEntry); if (isIndirect && entry.hasExtensions()) { Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); if (currentCaName != null) { previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); } } } return entrySet; }
private Set getExtensionOIDs(boolean critical) { Extensions extensions = c.getExtensions(); if (extensions != null) { Set set = new HashSet(); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); Extension ext = extensions.getExtension(oid); if (critical == ext.isCritical()) { set.add(oid.getId()); } } return set; } return null; }
public byte[] getExtensionValue(String oid) { Extension ext = getExtension(new ASN1ObjectIdentifier(oid)); if (ext != null) { try { return ext.getExtnValue().getEncoded(); } catch (Exception e) { throw new RuntimeException("error encoding " + e.toString()); } } return null; }
public static CertEtcToken getInstance(Object obj) { if (obj instanceof CertEtcToken) { return (CertEtcToken)obj; } else if (obj instanceof ASN1TaggedObject) { return new CertEtcToken((ASN1TaggedObject)obj); } else if (obj != null) { return new CertEtcToken(Extension.getInstance(obj)); } return null; }
public byte[] getExtensionValue(String oid) { Extensions exts = req.getExtensions(); if (exts != null) { Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); if (ext != null) { try { return ext.getExtnValue().getEncoded(); } catch (Exception e) { throw new RuntimeException("error encoding " + e.toString()); } } } return null; }
static void setCertificateExtensions(X509Certificate certificate) throws IOException, ParseException { String cpsUri = CertificateHelper.getCertificatePoliciesExtension(certificate); if (!cpsUri.isEmpty()) { access.setCritical(CERTIFICATE_POLICIES_ID, CertificateHelper.isExtensionCritical(Extension.certificatePolicies, certificate.getCriticalExtensionOIDs())); access.setAnyPolicy(true); access.setCpsUri(cpsUri); } String skipCerts = CertificateHelper.getInhabitAnyPolicyExtension(certificate); if (!skipCerts.isEmpty()) { access.setCritical(INHABIT_ANY_POLICY_ID, CertificateHelper.isExtensionCritical(Extension.inhibitAnyPolicy, certificate.getCriticalExtensionOIDs())); access.setInhibitAnyPolicy(true); access.setSkipCerts(skipCerts); } String[] subjectDirectoryData = CertificateHelper.getSubjectDirectoryExtension(certificate); if (subjectDirectoryData != null) { access.setCritical(SUBJECT_DIRECTORY_ATTRIBUTES_ID, CertificateHelper.isExtensionCritical(Extension.subjectDirectoryAttributes, certificate.getCriticalExtensionOIDs())); access.setDateOfBirth(subjectDirectoryData[0]); access.setSubjectDirectoryAttribute(COUNTRY_OF_CITIZENSHIP_ID, subjectDirectoryData[1]); access.setSubjectDirectoryAttribute(PLACE_OF_BIRTH_ID, subjectDirectoryData[2]); access.setGender(subjectDirectoryData[3]); } }
public static byte[] extractSki(org.bouncycastle.asn1.x509.Certificate cert) throws CertificateEncodingException { ParamUtil.requireNonNull("cert", cert); Extension encodedSkiValue = cert.getTBSCertificate().getExtensions().getExtension( Extension.subjectKeyIdentifier); if (encodedSkiValue == null) { return null; } try { return ASN1OctetString.getInstance(encodedSkiValue.getParsedValue()).getOctets(); } catch (IllegalArgumentException ex) { throw new CertificateEncodingException("invalid extension SubjectKeyIdentifier: " + ex.getMessage()); } }
public static Extension createExtnSubjectInfoAccess(List<String> accessMethodAndLocations, boolean critical) throws BadInputException { if (CollectionUtil.isEmpty(accessMethodAndLocations)) { return null; } ASN1EncodableVector vector = new ASN1EncodableVector(); for (String accessMethodAndLocation : accessMethodAndLocations) { vector.add(createAccessDescription(accessMethodAndLocation)); } ASN1Sequence seq = new DERSequence(vector); try { return new Extension(Extension.subjectInfoAccess, critical, seq.getEncoded()); } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
@Override protected Object execute0() throws Exception { CertificateList crl = CertificateList.getInstance(IoUtil.read(inFile)); if (crlNumber != null && crlNumber) { ASN1Encodable asn1 = crl.getTBSCertList().getExtensions().getExtensionParsedValue( Extension.cRLNumber); if (asn1 == null) { return "null"; } return getNumber(ASN1Integer.getInstance(asn1).getPositiveValue()); } else if (issuer != null && issuer) { return crl.getIssuer().toString(); } else if (thisUpdate != null && thisUpdate) { return toUtcTimeyyyyMMddhhmmssZ(crl.getThisUpdate().getDate()); } else if (nextUpdate != null && nextUpdate) { return crl.getNextUpdate() == null ? "null" : toUtcTimeyyyyMMddhhmmssZ(crl.getNextUpdate().getDate()); } return null; }
public CRLDistributionPointsImpl(X509Certificate cert) throws CertificateException, IOException { URINames = new ArrayList<>(); byte[] extVal = cert.getExtensionValue(Extension.cRLDistributionPoints.getId()); if (extVal == null) return; CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(X509ExtensionUtil.fromExtensionValue(extVal)); DistributionPoint[] points = crlDistPoint.getDistributionPoints(); for (DistributionPoint p : points) { GeneralNames tmp = p.getCRLIssuer(); if (tmp != null) { GeneralName[] crlIssers = tmp.getNames(); for (int i = 0; i < crlIssers.length; i++) { if (crlIssers[i].getTagNo() == GeneralName.uniformResourceIdentifier) { String issuerUrl = crlIssers[i].toString(); URINames.add(issuerUrl); } } } } }
public static X500PrivateCredential generateServerCertificate(KeyPair caKeyPair) throws NoSuchAlgorithmException, CertificateException, OperatorCreationException, CertIOException { X500Name issuerName = new X500Name("CN=bouncrca"); X500Name subjectName = new X500Name("CN=bouncr"); BigInteger serial = BigInteger.valueOf(2); long t1 = System.currentTimeMillis(); KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048, SecureRandom.getInstance("NativePRNGNonBlocking")); KeyPair kp = rsa.generateKeyPair(); System.out.println(System.currentTimeMillis() - t1); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, kp.getPublic()); DERSequence subjectAlternativeNames = new DERSequence(new ASN1Encodable[] { new GeneralName(GeneralName.dNSName, "localhost"), new GeneralName(GeneralName.dNSName, "127.0.0.1") }); builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNames); X509Certificate cert = signCertificate(builder, caKeyPair.getPrivate()); return new X500PrivateCredential(cert, kp.getPrivate()); }
private byte[] getSubjectKeyIdentifier(X509CertificateHolder certHolder) { if (certHolder.getVersionNumber() != 3) { return calculateIdentifier(certHolder.getSubjectPublicKeyInfo()); } else { Extension ext = certHolder.getExtension(Extension.subjectKeyIdentifier); if (ext != null) { return ASN1OctetString.getInstance(ext.getParsedValue()).getOctets(); } else { return calculateIdentifier(certHolder.getSubjectPublicKeyInfo()); } } }
public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) { List<String> ipAddresses = new ArrayList<>(); Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); for (Attribute attribute : attributes) { for (ASN1Encodable value : attribute.getAttributeValues()) { Extensions extensions = Extensions.getInstance(value); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); for (GeneralName name : gns.getNames()) { if (name.getTagNo() == GeneralName.iPAddress) { try { InetAddress addr = InetAddress.getByAddress(((DEROctetString) name.getName()).getOctets()); ipAddresses.add(addr.getHostAddress()); } catch (UnknownHostException e) { } } } } } return ipAddresses; }
public void validate(CertPathValidationContext context, X509CertificateHolder certificate) throws CertPathValidationException { context.addHandledExtension(Extension.keyUsage); if (!context.isEndEntity()) { KeyUsage usage = KeyUsage.fromExtensions(certificate.getExtensions()); if (usage != null) { if (!usage.hasUsages(KeyUsage.keyCertSign)) { throw new CertPathValidationException("Issuer certificate KeyUsage extension does not permit key signing"); } } else { if (isMandatory) { throw new CertPathValidationException("KeyUsage extension not present in CA certificate"); } } } }
/** * Returns the AuthorityInfoAccess extension value on list format.<br> * Otherwise, returns <b>list empty</b>.<br> * @return List Authority info access list */ public List<String> getAuthorityInfoAccess() { List<String> address = new ArrayList<String>(); try { byte[] authorityInfoAccess = certificate.getExtensionValue(Extension.authorityInfoAccess.getId()); if (authorityInfoAccess != null && authorityInfoAccess.length > 0) { AuthorityInformationAccess infoAccess = AuthorityInformationAccess.getInstance(X509ExtensionUtil .fromExtensionValue(authorityInfoAccess)); for (AccessDescription desc : infoAccess.getAccessDescriptions()) if (desc.getAccessLocation().getTagNo() == GeneralName.uniformResourceIdentifier) address.add(((DERIA5String) desc.getAccessLocation().getName()).getString()); } return address; } catch (IOException error) { logger.info(error.getMessage()); return address; } }
public static List<String> extractX509CSRDnsNames(PKCS10CertificationRequest certReq) { List<String> dnsNames = new ArrayList<>(); Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); for (Attribute attribute : attributes) { for (ASN1Encodable value : attribute.getAttributeValues()) { Extensions extensions = Extensions.getInstance(value); GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); for (GeneralName name : gns.getNames()) { if (name.getTagNo() == GeneralName.dNSName) { dnsNames.add(((DERIA5String) name.getName()).getString()); } } } } return dnsNames; }
private List<Extension> getExtensionsWithoutPoison( Extensions extensions, Extension replacementX509authorityKeyIdentifier) { ASN1ObjectIdentifier[] extensionsOidsArray = extensions.getExtensionOIDs(); Iterator<ASN1ObjectIdentifier> extensionsOids = Arrays.asList(extensionsOidsArray).iterator(); // Order is important, which is why a list is used. ArrayList<Extension> outputExtensions = new ArrayList<Extension>(); while (extensionsOids.hasNext()) { ASN1ObjectIdentifier extn = extensionsOids.next(); String extnId = extn.getId(); if (extnId.equals(CTConstants.POISON_EXTENSION_OID)) { // Do nothing - skip copying this extension } else if ((extnId.equals(X509_AUTHORITY_KEY_IDENTIFIER)) && (replacementX509authorityKeyIdentifier != null)) { // Use the real issuer's authority key identifier, since it's present. outputExtensions.add(replacementX509authorityKeyIdentifier); } else { // Copy the extension as-is. outputExtensions.add(extensions.getExtension(extn)); } } return outputExtensions; }
private static X509Certificate createSelfSignedCertificate(KeyPair keyPair, AthenzIdentity identity) throws OperatorCreationException, CertIOException, CertificateException { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").build(keyPair.getPrivate()); X500Name x500Name = new X500Name("CN="+ identity.getFullName()); Instant now = Instant.now(); Date notBefore = Date.from(now); Date notAfter = Date.from(now.plus(Duration.ofDays(30))); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( x500Name, BigInteger.valueOf(now.toEpochMilli()), notBefore, notAfter, x500Name, keyPair.getPublic() ) .addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certificateBuilder.build(contentSigner)); }
@Test public void getSignedByIssuer_setsKeyUsage_ifPresent() throws Exception { X509Certificate generatedCertificate = subject .getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters, certificateAuthorityWithSubjectKeyId, issuerKey.getPrivate()); assertThat(generatedCertificate.getExtensionValue(Extension.keyUsage.getId()), nullValue()); certificateGenerationParameters = parametersContainsExtensions(); generatedCertificate = subject .getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters, certificateAuthorityWithSubjectKeyId, issuerKey.getPrivate()); byte[] actualKeyUsage = generatedCertificate.getExtensionValue(Extension.keyUsage.getId()); assertThat(Arrays.copyOfRange(actualKeyUsage, 5, actualKeyUsage.length), equalTo(certificateGenerationParameters.getKeyUsage().getBytes())); }
@Test public void getSignedByIssuer_setsAlternativeName_ifPresent() throws Exception { X509Certificate generatedCertificate = subject .getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters, certificateAuthorityWithSubjectKeyId, issuerKey.getPrivate()); assertThat(generatedCertificate.getExtensionValue(Extension.subjectAlternativeName.getId()), nullValue()); certificateGenerationParameters = parametersContainsExtensions(); generatedCertificate = subject .getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters, certificateAuthorityWithSubjectKeyId, issuerKey.getPrivate()); byte[] actualSubjectAlternativeName = generatedCertificate.getExtensionValue(Extension.subjectAlternativeName.getId()); byte[] expectedAlternativeName = getExpectedAlternativeNames(); assertThat(Arrays.copyOfRange(actualSubjectAlternativeName, 2, actualSubjectAlternativeName.length), equalTo(expectedAlternativeName)); }