Refine search
public void createSelfSignedCertificate( File certificatePath, File privateKeyPath, String hostName ) throws GeneralSecurityException, IOException, OperatorCreationException { installCleanupHook( certificatePath, privateKeyPath ); KeyPairGenerator keyGen = KeyPairGenerator.getInstance( DEFAULT_ENCRYPTION ); keyGen.initialize( 2048, random ); KeyPair keypair = keyGen.generateKeyPair(); // Prepare the information required for generating an X.509 certificate. X500Name owner = new X500Name( "CN=" + hostName ); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( owner, new BigInteger( 64, random ), NOT_BEFORE, NOT_AFTER, owner, keypair.getPublic() ); // Subject alternative name (part of SNI extension, used for hostname verification) GeneralNames subjectAlternativeName = new GeneralNames( new GeneralName( GeneralName.dNSName, hostName ) ); builder.addExtension( Extension.subjectAlternativeName, false, subjectAlternativeName ); PrivateKey privateKey = keypair.getPrivate(); ContentSigner signer = new JcaContentSignerBuilder( "SHA512WithRSAEncryption" ).build( privateKey ); X509CertificateHolder certHolder = builder.build( signer ); X509Certificate cert = new JcaX509CertificateConverter().setProvider( PROVIDER ).getCertificate( certHolder ); //check so that cert is valid cert.verify( keypair.getPublic() ); //write to disk writePem( "CERTIFICATE", cert.getEncoded(), certificatePath ); writePem( "PRIVATE KEY", privateKey.getEncoded(), privateKeyPath ); // Mark as done so we don't clean up certificates cleanupRequired = false; }
private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCertificateIssuer) { if (!isIndirect) { return null; } Extension ext = getExtension(Extension.certificateIssuer); if (ext == null) { return previousCertificateIssuer; } try { GeneralName[] names = GeneralNames.getInstance(ext.getParsedValue()).getNames(); for (int i = 0; i < names.length; i++) { if (names[i].getTagNo() == GeneralName.directoryName) { return X500Name.getInstance(names[i].getName()); } } return null; } catch (Exception e) { return null; } }
private GeneralNames( ASN1Sequence seq) { this.names = new GeneralName[seq.size()]; for (int i = 0; i != seq.size(); i++) { names[i] = GeneralName.getInstance(seq.getObjectAt(i)); } }
throws IOException byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId()); if (crldpExt == null) for (GeneralName genName : GeneralNames.getInstance(dpn.getName()).getNames()) if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) String url = DERIA5String.getInstance(genName.getName()).getString(); crlUrls.add(url);
@Override public Attribute getValue() throws SignerException { try { X509Certificate cert = (X509Certificate) certificates[0]; Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_256); byte[] certHash = digest.digest(cert.getEncoded()); X500Name dirName = new X500Name(cert.getSubjectDN().getName()); GeneralName name = new GeneralName(dirName); GeneralNames issuer = new GeneralNames(name); ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber()); IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber); AlgorithmIdentifier algId = new AlgorithmIdentifier(new ASN1ObjectIdentifier("2.16.840.1.101.3.4.2.1"));//SHA-256 ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(algId, certHash, issuerSerial); return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[]{new DERSequence(essCertIDv2), new DERSequence(DERNull.INSTANCE)}))); } catch (CertificateEncodingException ex) { throw new SignerException(ex.getMessage()); } } }
public static Extensions createDomainAlternativeNamesExtensions(String domainAlternativeNames, String requestedDn) throws IOException { List<GeneralName> namesList = new ArrayList<>(); try { final String cn = IETFUtils.valueToString(new X500Name(requestedDn).getRDNs(BCStyle.CN)[0].getFirst().getValue()); namesList.add(new GeneralName(GeneralName.dNSName, cn)); } catch (Exception e) { throw new IOException("Failed to extract CN from request DN: " + requestedDn, e); } if (StringUtils.isNotBlank(domainAlternativeNames)) { for (String alternativeName : domainAlternativeNames.split(",")) { namesList.add(new GeneralName(GeneralName.dNSName, alternativeName)); } } GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[]{})); ExtensionsGenerator extGen = new ExtensionsGenerator(); extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); return extGen.generate(); }
private SemanticsInformation(ASN1Sequence seq) Enumeration e = seq.getObjects(); if (seq.size() < 1) if (object instanceof ASN1ObjectIdentifier) semanticsIdentifier = ASN1ObjectIdentifier.getInstance(object); if (e.hasMoreElements()) ASN1Sequence generalNameSeq = ASN1Sequence.getInstance(object); nameRegistrationAuthorities = new GeneralName[generalNameSeq.size()]; for (int i= 0; i < generalNameSeq.size(); i++) nameRegistrationAuthorities[i] = GeneralName.getInstance(generalNameSeq.getObjectAt(i));
/** * Converts a list of domain name Subject Alternative Names into ASN1Encodable GeneralNames objects, for use with * the Bouncy Castle certificate builder. * * @param subjectAlternativeNames domain name SANs to convert * @return a GeneralNames instance that includes the specifie dsubjectAlternativeNames as DNS name fields */ private static GeneralNames getDomainNameSANsAsASN1Encodable(List<String> subjectAlternativeNames) { List<GeneralName> encodedSANs = new ArrayList<>(subjectAlternativeNames.size()); for (String subjectAlternativeName : subjectAlternativeNames) { // IP addresses use the IP Address tag instead of the DNS Name tag in the SAN list boolean isIpAddress = InetAddresses.isInetAddress(subjectAlternativeName); GeneralName generalName = new GeneralName(isIpAddress ? GeneralName.iPAddress : GeneralName.dNSName, subjectAlternativeName); encodedSANs.add(generalName); } return new GeneralNames(encodedSANs.toArray(new GeneralName[encodedSANs.size()])); }
public static List<String> extractOcspUrls(AuthorityInformationAccess aia) throws CertificateEncodingException { AccessDescription[] accessDescriptions = aia.getAccessDescriptions(); List<AccessDescription> ocspAccessDescriptions = new LinkedList<>(); for (AccessDescription accessDescription : accessDescriptions) { if (accessDescription.getAccessMethod().equals(X509ObjectIdentifiers.id_ad_ocsp)) { ocspAccessDescriptions.add(accessDescription); } } final int n = ocspAccessDescriptions.size(); List<String> ocspUris = new ArrayList<>(n); for (int i = 0; i < n; i++) { GeneralName accessLocation = ocspAccessDescriptions.get(i).getAccessLocation(); if (accessLocation.getTagNo() == GeneralName.uniformResourceIdentifier) { String ocspUri = ((ASN1String) accessLocation.getName()).getString(); ocspUris.add(ocspUri); } } return ocspUris; }
private URL getOcspUrlFromCertificate(X509Certificate certificate) { byte[] octetBytes = certificate.getExtensionValue(org.bouncycastle.asn1.x509.Extension.authorityInfoAccess.getId()); if (null != octetBytes) { try { byte[] encoded = X509ExtensionUtil.fromExtensionValue(octetBytes).getEncoded(); ASN1Sequence seq = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(encoded)); AuthorityInformationAccess access = AuthorityInformationAccess.getInstance(seq); for (AccessDescription accessDescription : access.getAccessDescriptions()){ if (accessDescription.getAccessMethod().equals(AccessDescription.id_ad_ocsp)){ url = new URL(accessDescription.getAccessLocation().getName().toString()); break; } } } catch (IOException ignore) { } } return url; }
private String getSubjectAlternativeNames(final X509Certificate certificate, final int index, final int type) { final byte[] extVal = certificate.getExtensionValue(Extension.issuerAlternativeName.getId()); if (extVal == null) { return null; } try { final Enumeration<?> it = DERSequence.getInstance(X509ExtensionUtil.fromExtensionValue(extVal)).getObjects(); int i = index; while (it.hasMoreElements()) { if (index == i++) { final GeneralName genName = GeneralName.getInstance(it.nextElement()); if (genName.getTagNo() == type) { return ASN1String.class.cast(genName.getName()).getString(); } } } } catch (final IOException e) { // no-op } return null; }
final String subject = request.getSubject().toString(); for (final Attribute attribute : request.getAttributes()) { if (attribute == null) { continue; if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { final Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0)); final GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); if (gns != null && gns.getNames() != null && gns.getNames().length > 0) { for (final GeneralName name : gns.getNames()) { if (name.getTagNo() == GeneralName.dNSName) { dnsNames.add(name.getName().toString()); if (name.getTagNo() == GeneralName.iPAddress) { final InetAddress address = InetAddress.getByAddress(DatatypeConverter.parseHexBinary(name.getName().toString().substring(1))); ipAddresses.add(address.toString().replace("/", ""));
private AccessDescription( ASN1Sequence seq) { if (seq.size() != 2) { throw new IllegalArgumentException("wrong number of elements in sequence"); } accessMethod = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0)); accessLocation = GeneralName.getInstance(seq.getObjectAt(1)); }
public static String getCACertificateURL(X509Certificate certificate) throws IOException { byte[] bOctets = ((ASN1OctetString) ASN1Primitive.fromByteArray(certificate.getExtensionValue(Extension.authorityInfoAccess.getId()))).getOctets(); AuthorityInformationAccess access = AuthorityInformationAccess.getInstance(ASN1Sequence.fromByteArray(bOctets)); for (AccessDescription ad:access.getAccessDescriptions()){ if (ad.getAccessMethod().equals(X509ObjectIdentifiers.id_ad_caIssuers)){ return ad.getAccessLocation().getName().toString(); } } return null; } }
for (RDN emails : subject.getRDNs(BCStyle.EmailAddress)) { for (AttributeTypeAndValue emailAttr: emails.getTypesAndValues()) { if (log.isDebugEnabled()) { .getExtension(Extension.subjectAlternativeName); if (subjectAlternativeNames != null) { for (GeneralName name : GeneralNames.getInstance( subjectAlternativeNames.getParsedValue()).getNames()) { if (name.getTagNo() == GeneralName.rfc822Name) { String email = IETFUtils.valueToString(name.getName()); log.debug("Add email from subjectAlternativeName: {}", email); res.add(email);
/** * Parse UPN/otherName * * @param generalName otherName object * @return UPN as string */ public static String parseUPN(GeneralName generalName) { // OtherName ::= SEQUENCE { // type-id OBJECT IDENTIFIER, // value [0] EXPLICIT ANY DEFINED BY type-id } ASN1Sequence otherName = (ASN1Sequence) generalName.getName(); ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) otherName.getObjectAt(0); if (UPN_OID.equals(oid.getId())) { DERTaggedObject derTaggedObject = (DERTaggedObject) otherName.getObjectAt(1); DERUTF8String upn = DERUTF8String.getInstance(derTaggedObject.getObject()); return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), "UPN", upn.getString()); } // fallback to generic handling ASN1Encodable value = otherName.getObjectAt(1); try { return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), ObjectIdUtil.toString(oid), HexUtil.getHexString(value.toASN1Primitive().getEncoded(ASN1Encoding.DER))); } catch (IOException e) { return MessageFormat.format(res.getString("GeneralNameUtil.OtherGeneralName"), ObjectIdUtil.toString(oid), ""); } }
public CertificateBuilder sanDnsName(String hostName) throws IOException { subjectAltName = new GeneralNames(new GeneralName(GeneralName.dNSName, hostName)).getEncoded(); return this; }
@SuppressWarnings({ "deprecation", "resource" }) private String getOCSPUrl(X509Certificate certificate) throws IOException { ASN1Primitive obj; try { obj = getExtensionValue(certificate, Extension.authorityInfoAccess.getId()); } catch (IOException ex) { log.error("Failed to get OCSP URL", ex); return null; } if (obj == null) { return null; } AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess.getInstance(obj); AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions(); for (AccessDescription accessDescription : accessDescriptions) { boolean correctAccessMethod = accessDescription.getAccessMethod().equals(X509ObjectIdentifiers.ocspAccessMethod); if (!correctAccessMethod) { continue; } GeneralName name = accessDescription.getAccessLocation(); if (name.getTagNo() != GeneralName.uniformResourceIdentifier) { continue; } DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false); return derStr.getString(); } return null; }
X500Name subject = new X500Name("CN=" + domain + ", O=MockServer, L=London, ST=England, C=UK"); subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, domain)); for (String subjectAlternativeNameDomain : subjectAlternativeNameDomains) { subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, subjectAlternativeNameDomain)); || IPAddress.isValidIPv4WithNetmask(subjectAlternativeNameIp) || IPAddress.isValidIPv4(subjectAlternativeNameIp)) { subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, subjectAlternativeNameIp));