List of usage examples for org.bouncycastle.asn1.x509 GeneralName dNSName
int dNSName
To view the source code for org.bouncycastle.asn1.x509 GeneralName dNSName.
Click Source Link
From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateTool.java
License:Open Source License
private static GeneralNames getSubjectAlternativeNamesValue(List<String> ipAddresses, List<String> dnsNames, List<String> commonNames) { Set<GeneralName> generalNameList = new HashSet<>(); for (String ip : ipAddresses) { generalNameList.add(new GeneralName(GeneralName.iPAddress, ip)); }// w w w. j ava 2s . c o m for (String dns : dnsNames) { generalNameList.add(new GeneralName(GeneralName.dNSName, dns)); } for (String cn : commonNames) { generalNameList.add(CertGenUtils.createCommonName(cn)); } if (generalNameList.isEmpty()) { return null; } return new GeneralNames(generalNameList.toArray(new GeneralName[0])); }
From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateToolTests.java
License:Open Source License
private void assertSubjAltNames(GeneralNames subjAltNames, CertificateInformation certInfo) throws Exception { final int expectedCount = certInfo.ipAddresses.size() + certInfo.dnsNames.size() + certInfo.commonNames.size(); assertEquals(expectedCount, subjAltNames.getNames().length); Collections.sort(certInfo.dnsNames); Collections.sort(certInfo.ipAddresses); for (GeneralName generalName : subjAltNames.getNames()) { if (generalName.getTagNo() == GeneralName.dNSName) { String dns = ((ASN1String) generalName.getName()).getString(); assertTrue(certInfo.dnsNames.stream().anyMatch(dns::equals)); } else if (generalName.getTagNo() == GeneralName.iPAddress) { byte[] ipBytes = DEROctetString.getInstance(generalName.getName()).getOctets(); String ip = NetworkAddress.format(InetAddress.getByAddress(ipBytes)); assertTrue(certInfo.ipAddresses.stream().anyMatch(ip::equals)); } else if (generalName.getTagNo() == GeneralName.otherName) { ASN1Sequence seq = ASN1Sequence.getInstance(generalName.getName()); assertThat(seq.size(), equalTo(2)); assertThat(seq.getObjectAt(0), instanceOf(ASN1ObjectIdentifier.class)); assertThat(seq.getObjectAt(0).toString(), equalTo(CN_OID)); assertThat(seq.getObjectAt(1), instanceOf(DERTaggedObject.class)); DERTaggedObject taggedName = (DERTaggedObject) seq.getObjectAt(1); assertThat(taggedName.getTagNo(), equalTo(0)); assertThat(taggedName.getObject(), instanceOf(ASN1String.class)); assertThat(taggedName.getObject().toString(), Matchers.isIn(certInfo.commonNames)); } else {/*from w w w. j av a2 s . com*/ fail("unknown general name with tag " + generalName.getTagNo()); } } }
From source file:org.elasticsearch.xpack.core.ssl.CertificateToolTests.java
License:Open Source License
private void assertSubjAltNames(GeneralNames subjAltNames, CertificateInformation certInfo) throws Exception { final int expectedCount = certInfo.ipAddresses.size() + certInfo.dnsNames.size() + certInfo.commonNames.size(); assertEquals(expectedCount, subjAltNames.getNames().length); Collections.sort(certInfo.dnsNames); Collections.sort(certInfo.ipAddresses); for (GeneralName generalName : subjAltNames.getNames()) { if (generalName.getTagNo() == GeneralName.dNSName) { String dns = ((ASN1String) generalName.getName()).getString(); assertTrue(certInfo.dnsNames.stream().anyMatch(dns::equals)); } else if (generalName.getTagNo() == GeneralName.iPAddress) { byte[] ipBytes = DEROctetString.getInstance(generalName.getName()).getOctets(); String ip = NetworkAddress.format(InetAddress.getByAddress(ipBytes)); assertTrue(certInfo.ipAddresses.stream().anyMatch(ip::equals)); } else if (generalName.getTagNo() == GeneralName.otherName) { ASN1Sequence seq = ASN1Sequence.getInstance(generalName.getName()); assertThat(seq.size(), equalTo(2)); assertThat(seq.getObjectAt(0), instanceOf(ASN1ObjectIdentifier.class)); assertThat(seq.getObjectAt(0).toString(), equalTo(CN_OID)); assertThat(seq.getObjectAt(1), instanceOf(ASN1TaggedObject.class)); ASN1TaggedObject tagged = (ASN1TaggedObject) seq.getObjectAt(1); assertThat(tagged.getObject(), instanceOf(ASN1String.class)); assertThat(tagged.getObject().toString(), Matchers.isIn(certInfo.commonNames)); } else {//from www . j av a 2 s . c o m fail("unknown general name with tag " + generalName.getTagNo()); } } }
From source file:org.glite.security.util.HostNameChecker.java
License:Apache License
/** * Checks whether the hostname is allowed by the certificate. Checks the certificate altnames and subject DN * according to the RFC 2818. Wildcard '*' is supported both in dnsName altName and in the DN. Service prefix in DN * CN format "[service name]/[hostname]" is recognized, but ignored. Localhost defined as "localhost", "127.0.0.1" * or "::1" bypasses the check./*from www . java2 s. c o m*/ * * @param inHostname * The hostname to check against the certificate. Can be a DNS name, IP address or an URL. * @param cert * The certificate the hostname is checked against. * @return True in case the hostname is allowed by the certificate. * @throws CertificateParsingException * Thrown in case the certificate parsing fails. */ public static boolean checkHostName(String inHostname, X509Certificate cert) throws CertificateParsingException { // Dig the hostname if the given string is an URL. String hostname = null; // check whether an URL is given (contains a slash). if (inHostname.indexOf('/') < 0) { // Not an URL, assume it's a hostname hostname = inHostname.trim().toLowerCase(); } else { // if not, assume an URL try { URL url = new URL(inHostname.trim()); hostname = url.getHost().toLowerCase(); } catch (MalformedURLException e) { throw new IllegalArgumentException( "Illegal URL given for the certificate host check: " + inHostname); } } // check if the input is ip address. boolean ipAsHostname = false; if (ipPattern.matcher(hostname).matches()) { ipAsHostname = true; } // Check if localhost. If yes, accept automatically. if (ipAsHostname) { byte[] hostnameIPBytes = IPAddressComparator.parseIP(hostname); if (hostnameIPBytes.length < 6) { if (IPAddressComparator.compare(hostnameIPBytes, localhostIPv4)) { LOGGER.debug("Localhost IPv4 address given, bypassing hostname - certificate matching."); return true; } } else { if (IPAddressComparator.compare(hostnameIPBytes, localhostIPv6)) { LOGGER.debug("Localhost IPv6 address given, bypassing hostname - certificate matching."); return true; } } } else { if (hostname.equals("localhost")) { LOGGER.debug("Localhost address given, bypassing hostname - certificate matching."); return true; } } // If there are subject alternative names, check the hostname against // them first. Collection<List<?>> collection = cert.getSubjectAlternativeNames(); if (collection != null) { // If there are, go through them and check for matches. Iterator<List<?>> collIter = collection.iterator(); while (collIter.hasNext()) { List<?> item = collIter.next(); int type = ((Integer) item.get(0)).intValue(); if (type == GeneralName.dNSName) { // check against DNS name if (!ipAsHostname) { // only if the hostname was not given // as IP address String dnsName = (String) item.get(1); if (checkDNS(hostname, dnsName)) { return true; } else { LOGGER.debug("Hostname \"" + hostname + "\" does not match \"" + dnsName + "\"."); } } } else { if (type == GeneralName.iPAddress) { // Check against IP // address if (ipAsHostname) { // only if hostname was given as IP // address String ipString = (String) item.get(1); if (checkIP(hostname, ipString)) { return true; } else { LOGGER.debug("Hostname \"" + hostname + "\" does not match \"" + ipString + "\"."); } } } } } } // If no match was found in subjectAltName, or they were not present, // check against the DN. if (checkBasedOnDN(hostname, cert)) { return true; } else { LOGGER.debug("Hostname \"" + hostname + "\" does not match DN \"" + DNHandler.getSubject(cert).getRFCDN() + "\"."); } return false; }
From source file:org.glite.slcs.pki.CertificateExtensionFactory.java
License:eu-egee.org license
/** * //from ww w. ja va2s. c o m * @param prefixedAltNames * @param values * @return */ static protected CertificateExtension createSubjectAltNameExtension(Vector prefixedAltNames, String values) { ASN1EncodableVector altNames = new ASN1EncodableVector(); Enumeration typeAndNames = prefixedAltNames.elements(); while (typeAndNames.hasMoreElements()) { String typeAndName = (String) typeAndNames.nextElement(); typeAndName = typeAndName.trim(); if (typeAndName.startsWith("email:")) { String emailAddress = typeAndName.substring("email:".length()); GeneralName altName = new GeneralName(GeneralName.rfc822Name, emailAddress); altNames.add(altName); } else if (typeAndName.startsWith("dns:")) { String hostname = typeAndName.substring("dns:".length()); GeneralName altName = new GeneralName(GeneralName.dNSName, hostname); altNames.add(altName); } else { LOG.error("Unsupported subjectAltName: " + typeAndName); } } DERSequence subjectAltNames = new DERSequence(altNames); GeneralNames generalNames = new GeneralNames(subjectAltNames); X509Extension subjectAltNameExtension = new X509Extension(false, new DEROctetString(generalNames)); return new CertificateExtension(X509Extensions.SubjectAlternativeName, "SubjectAltName", subjectAltNameExtension, values); }
From source file:org.hyperledger.fabric.sdk.security.certgen.TLSCertificateBuilder.java
License:Open Source License
private void addSAN(X509v3CertificateBuilder certBuilder, String san) throws CertIOException { ASN1Encodable[] subjectAlternativeNames = new ASN1Encodable[] { new GeneralName(GeneralName.dNSName, san) }; certBuilder.addExtension(Extension.subjectAlternativeName, false, new DERSequence(subjectAlternativeNames)); }
From source file:org.iotivity.cloud.accountserver.resources.credprov.cert.CertificateResource.java
License:Open Source License
/** * Handles post requests to Certificate Resource. * Request should be with specified format * POST /oic/credprov/cert/* w w w. ja v a2 s . c o m*/ * { * di? : 11-22-xx?, * csr? : { * encoding? : oic.sec.encoding.base64?, * data? : <Base64 encoded CSR Binary>? * } * } * Method checks encoding, and decodes data by specified encoding if needed. * * Method issus a certificate including User UUID in extension field, * stores issuing information (serial number, validity, device uuid, user uuid) for management (e.g. re-issue). * Response should be in next format for example: * 2.04 CHANGED * { * di? : 1111-22-xx?, * cert? : { * encoding? : oic.sec.encoding.base64?, * data? : <Base64 encoded Cert. Binary>? * }, * certchain? : { * encoding? : oic.sec.encoding.base64?, * data? : <Base64 encoded CA Cert. chain>? * } * } * or returns BAD_REQUEST: 4.0.1 if any exceptions occured. * * @param request request with payload information. * @throws ServerException */ private IResponse handlePostRequest(IRequest request) throws ServerException { byte[] requestPayload = request.getPayload(); IResponse response = MessageBuilder.createResponse(request, ResponseStatus.BAD_REQUEST); if (requestPayload != null) { Map<String, Object> payloadData = MAP_CBOR.parsePayloadFromCbor(requestPayload, HashMap.class); if (payloadData != null) { Object csr = payloadData.get(Constants.REQ_CSR); if (csr != null && csr instanceof Map) { Object encoding = ((Map<String, Object>) csr).get(ENCODING); Object data = ((Map<String, Object>) csr).get(DATA); if (encoding != null && encoding instanceof String && data != null && data instanceof byte[]) { byte[] csrData = (byte[]) data; if (encoding.equals(BASE_64)) { csrData = Base64.decode(csrData); } try { CSRParser parser = new CSRParser(csrData); String commonName = parser.getCommonName(); String pattern = "^uuid:(.*)$"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(commonName); String deviceId = (String) payloadData.get(RESP_DEVICE_ID); if (m.find() && m.group(1).equals(deviceId) && parser.isSignatureValid()) { CertificateManager certificateManager = new CertificateManager(deviceId); CertificateTable certificateTable = certificateManager.getCertificate(); if (certificateTable != null) { try { CrlManager.CRL_MANAGER.revoke(certificateTable.getSerialNumber()); } catch (CRLException | OperatorCreationException e) { Log.e(e.getMessage() + e.getClass()); } certificateManager.update(certificateTable, true); } PublicKey publicKey = parser.getPublicKey(); if (publicKey != null) { CertificateExtension extension = new CertificateExtension( Extension.subjectAlternativeName, false, new DERSequence(new ASN1Encodable[] { new GeneralName(GeneralName.dNSName, Constants.KEYFIELD_USERID + ":" + Utility.getUserID(deviceId)) })); CertificateBuilder certBuilder = new CertificateBuilder(parser.getSubject(), publicKey, extension); try { X509Certificate personal = certBuilder.build(); byte[] encodedCert = personal.getEncoded(); byte[] encodedCa = CertificateStorage.ROOT_CERTIFICATE.getEncoded(); if (encoding.equals(CertificateConstants.BASE_64)) { encodedCert = Base64.encode(encodedCert); encodedCa = Base64.encode(encodedCa); } certificateManager.put(Constants.RESP_DEVICE_ID, deviceId); certificateManager.put(Constants.CERT, new CSR(encoding.toString(), encodedCert)); certificateManager.put(Constants.CERT_CHAIN, new CSR(encoding.toString(), encodedCa)); certificateManager.save(personal.getSerialNumber(), personal.getNotAfter(), personal.getNotBefore()); response = MessageBuilder.createResponse(request, ResponseStatus.CHANGED, ContentFormat.APPLICATION_CBOR, MAP_CBOR.encodingPayloadToCbor(certificateManager.getPayLoad())); } catch (GeneralSecurityException | OperatorCreationException | CertIOException e) { Log.e(e.getMessage()); } } } } catch (IOException e) { Log.e(e.getMessage()); } } } } } return response; }
From source file:org.jruby.ext.openssl.X509Extension.java
License:LGPL
@SuppressWarnings("unchecked") private static boolean formatGeneralName(final GeneralName name, final ByteList out, final boolean slashed) { final ASN1Encodable obj = name.getName(); String val; boolean tagged = false; switch (name.getTagNo()) { case GeneralName.rfc822Name: if (!tagged) out.append('e').append('m').append('a').append('i').append('l').append(':'); tagged = true;//from www . j a v a 2s . com case GeneralName.dNSName: if (!tagged) out.append('D').append('N').append('S').append(':'); tagged = true; case GeneralName.uniformResourceIdentifier: if (!tagged) out.append('U').append('R').append('I').append(':'); val = DERIA5String.getInstance(obj).getString(); out.append(ByteList.plain(val)); break; case GeneralName.directoryName: out.append('D').append('i').append('r').append('N').append('a').append('m').append('e').append(':'); final X500Name dirName = X500Name.getInstance(obj); if (slashed) { final RDN[] rdns = dirName.getRDNs(); final Hashtable defaultSymbols = getDefaultSymbols(); for (int i = 0; i < rdns.length; i++) { appendRDN(out.append('/'), rdns[i], defaultSymbols); } } else { out.append(ByteList.plain(dirName.toString())); } break; case GeneralName.iPAddress: out.append('I').append('P').append(':'); final byte[] ip = ((ASN1OctetString) name.getName()).getOctets(); int len = ip.length; boolean ip4 = len == 4; for (int i = 0; i < ip.length; i++) { out.append(ConvertBytes.intToCharBytes(((int) ip[i]) & 0xff)); if (i != len - 1) { if (ip4) out.append('.'); else out.append(':').append(':'); } } break; case GeneralName.otherName: out.append('o').append('t').append('h').append('e').append('r').append('N').append('a').append('m') .append('e').append(':'); out.append(ByteList.plain(obj.toString())); return true; //tagged = true; case GeneralName.registeredID: out.append('R').append('I').append('D').append(':'); //tagged = true; default: out.append(ByteList.plain(obj.toString())); } return false; }
From source file:org.jruby.ext.openssl.X509ExtensionFactory.java
License:LGPL
private static ASN1Encodable parseSubjectAltName(final String valuex) throws IOException { if (valuex.startsWith(DNS_)) { final String dns = valuex.substring(DNS_.length()); return new GeneralName(GeneralName.dNSName, dns); }/*w ww .j ava2 s . c o m*/ if (valuex.startsWith(DNS_Name_)) { final String dns = valuex.substring(DNS_Name_.length()); return new GeneralName(GeneralName.dNSName, dns); } if (valuex.startsWith(URI_)) { final String uri = valuex.substring(URI_.length()); return new GeneralName(GeneralName.uniformResourceIdentifier, uri); } if (valuex.startsWith(RID_)) { final String rid = valuex.substring(RID_.length()); return new GeneralName(GeneralName.registeredID, rid); } if (valuex.startsWith(email_)) { final String mail = valuex.substring(email_.length()); return new GeneralName(GeneralName.rfc822Name, mail); } if (valuex.startsWith("IP:") || valuex.startsWith("IP Address:")) { final int idx = valuex.charAt(2) == ':' ? 3 : 11; String[] vals = valuex.substring(idx).split("\\.|::"); final byte[] ip = new byte[vals.length]; for (int i = 0; i < vals.length; i++) { ip[i] = (byte) (Integer.parseInt(vals[i]) & 0xff); } return new GeneralName(GeneralName.iPAddress, new DEROctetString(ip)); } if (valuex.startsWith("other")) { // otherName || othername final String other = valuex.substring(otherName_.length()); return new GeneralName(GeneralName.otherName, other); } if (valuex.startsWith("dir")) { // dirName || dirname final String dir = valuex.substring(dirName_.length()); return new GeneralName(GeneralName.directoryName, dir); } throw new IOException("could not parse SubjectAltName: " + valuex); }
From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java
License:Apache License
protected List<ASN1Encodable> extractAlternativeNames(String prefix) { List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>(); for (Object key : componentProperties.keySet()) { final String attributeKey = String.valueOf(key); if (attributeKey.startsWith(prefix)) { String nameTypeString = attributeKey.substring(attributeKey.lastIndexOf(".") + 1); String nameValue = getProperty(attributeKey); int nameType = 0; switch (nameTypeString) { case NAME_DNS: nameType = GeneralName.dNSName; break; case NAME_DIRECTORY: nameType = GeneralName.directoryName; break; case NAME_IP: nameType = GeneralName.iPAddress; break; case NAME_OTHER: nameType = GeneralName.otherName; break; default: throw new IllegalArgumentException( String.format("Alternative name '%s' not supported.", nameTypeString)); }/*from w w w .ja va 2s .c o m*/ if (StringUtils.isNotBlank(nameValue)) { subjectAlternativeNames.add(new GeneralName(nameType, nameValue)); } } } return subjectAlternativeNames; }