List of usage examples for org.bouncycastle.asn1.x509 GeneralName iPAddress
int iPAddress
To view the source code for org.bouncycastle.asn1.x509 GeneralName iPAddress.
Click Source Link
From source file:org.cesecore.certificates.certificate.certextensions.standard.NameConstraint.java
License:Open Source License
/** * Returns the GeneralName data (as a byte array or String) from an encoded string. *//*from w w w . ja v a 2s . co m*/ private static Object getNameConstraintData(String encoded) { int type = getNameConstraintType(encoded); String data = encoded.split(":", 2)[1]; switch (type) { case GeneralName.dNSName: case GeneralName.directoryName: case GeneralName.rfc822Name: return data; case GeneralName.iPAddress: try { return Hex.decodeHex(data.toCharArray()); } catch (DecoderException e) { throw new IllegalStateException("internal name constraint data could not be decoded as hex", e); } default: throw new UnsupportedOperationException("Unsupported name constraint type " + type); } }
From source file:org.cesecore.certificates.certificate.certextensions.standard.NameConstraint.java
License:Open Source License
/** * Formats an encoded name constraint from parseNameConstraintEntry into human-readable form. *///from w w w. j av a 2s . c o m private static String formatNameConstraintEntry(String encoded) { if (encoded == null) { return ""; } int type = getNameConstraintType(encoded); Object data = getNameConstraintData(encoded); switch (type) { case GeneralName.dNSName: case GeneralName.directoryName: return (String) data; // not changed during encoding case GeneralName.iPAddress: byte[] bytes = (byte[]) data; byte[] ip = new byte[bytes.length / 2]; byte[] netmaskBytes = new byte[bytes.length / 2]; System.arraycopy(bytes, 0, ip, 0, ip.length); System.arraycopy(bytes, ip.length, netmaskBytes, 0, netmaskBytes.length); int netmask = 0; for (int i = 0; i < 8 * netmaskBytes.length; i++) { final boolean one = (netmaskBytes[i / 8] >> (7 - i % 8) & 1) == 1; if (one && netmask == i) { netmask++; // leading ones } else if (one) { // trailings ones = error! throw new IllegalArgumentException("Unsupported netmask with mixed ones/zeros"); } } try { return InetAddress.getByAddress(ip).getHostAddress() + "/" + netmask; } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } case GeneralName.rfc822Name: // Prepend @ is it's only the domain part to distinguish from DNS names String str = (String) data; return (str.contains("@") ? str : "@" + str); default: throw new UnsupportedOperationException("Unsupported name constraint type " + type); } }
From source file:org.cesecore.util.CertToolsTest.java
License:Open Source License
/** * Tests the following methods:/*from w ww. jav a2 s .c o m*/ * <ul> * <li>{@link CertTools.checkNameConstraints}</li> * <li>{@link NameConstraint.parseNameConstraintsList}</li> * <li>{@link NameConstraint.toGeneralSubtrees}</li> * </ul> */ @Test public void testNameConstraints() throws Exception { final String permitted = "C=SE,CN=example.com\n" + "example.com\n" + "@mail.example\n" + "user@host.com\n" + "10.0.0.0/8\n" + " C=SE, CN=spacing \n"; final String excluded = "forbidden.example.com\n" + "postmaster@mail.example\n" + "10.1.0.0/16\n" + "::/0"; // IPv6 final List<Extension> extensions = new ArrayList<Extension>(); GeneralSubtree[] permittedSubtrees = NameConstraint .toGeneralSubtrees(NameConstraint.parseNameConstraintsList(permitted)); GeneralSubtree[] excludedSubtrees = NameConstraint .toGeneralSubtrees(NameConstraint.parseNameConstraintsList(excluded)); byte[] extdata = new NameConstraints(permittedSubtrees, excludedSubtrees).toASN1Primitive().getEncoded(); extensions.add(new Extension(Extension.nameConstraints, false, extdata)); final KeyPair testkeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); X509Certificate cacert = CertTools.genSelfCertForPurpose("C=SE,CN=Test Name Constraints CA", 365, null, testkeys.getPrivate(), testkeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign, null, null, "BC", true, extensions); // Allowed subject DNs final X500Name validDN = new X500Name("C=SE,CN=example.com"); // re-used below CertTools.checkNameConstraints(cacert, validDN, null); CertTools.checkNameConstraints(cacert, new X500Name("C=SE,CN=spacing"), null); // Allowed subject alternative names CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.dNSName, "example.com"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.dNSName, "x.sub.example.com"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "someuser@mail.example"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "user@host.com"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("10.0.0.1").getAddress())))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("10.255.255.255").getAddress())))); // Disallowed subject DN checkNCException(cacert, new X500Name("C=DK,CN=example.com"), null, "Disallowed DN (wrong field value) was accepted"); checkNCException(cacert, new X500Name("C=SE,O=Company,CN=example.com"), null, "Disallowed DN (extra field) was accepted"); // Disallowed SAN // The commented out lines are allowed by BouncyCastle but disallowed by the RFC checkNCException(cacert, validDN, new GeneralName(GeneralName.dNSName, "bad.com"), "Disallowed SAN (wrong DNS name) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.dNSName, "forbidden.example.com"), "Disallowed SAN (excluded DNS subdomain) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.rfc822Name, "wronguser@host.com"), "Disallowed SAN (wrong e-mail) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("10.1.0.1").getAddress())), "Disallowed SAN (excluded IPv4 address) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("192.0.2.1").getAddress())), "Disallowed SAN (wrong IPv4 address) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("2001:DB8::").getAddress())), "Disallowed SAN (IPv6 address) was accepted"); }
From source file:org.codice.ddf.security.certificate.generator.CertificateCommandTest.java
License:Open Source License
/** * Expected SAN general name is now a function of the CN, since a SAN representing the CN is now * required./*from w w w. j av a 2s . c om*/ */ private static byte[] expectedSanGeneralName(String alias, boolean withAdditionalSans) { try { GeneralNamesBuilder builder = new GeneralNamesBuilder() .addName(new GeneralName(GeneralName.dNSName, alias)); if (withAdditionalSans) { builder.addName(new GeneralName(GeneralName.iPAddress, IP_FROM_SAN)) .addName(new GeneralName(GeneralName.dNSName, DNS_FROM_SAN)); } return builder.build().getEncoded(ASN1Encoding.DER); } catch (IOException e) { throw new IllegalStateException(e); } }
From source file:org.codice.ddf.security.certificate.generator.CertificateSigningRequestTest.java
License:Open Source License
@Test public void testAddSubjectAlternativeNames() { assertThat("CSR should not have any SAN by default", csr.getSubjectAlternativeNames(), emptyCollectionOf(GeneralName.class)); csr.addSubjectAlternativeNames("IP:1.2.3.4", "DNS:A"); assertThat(csr.getSubjectAlternativeNames(), contains(new GeneralName(GeneralName.iPAddress, "1.2.3.4"), new GeneralName(GeneralName.dNSName, "A"))); csr.addSubjectAlternativeNames("RID:0.2.1.4", "DNS:A"); assertThat(csr.getSubjectAlternativeNames(), contains(new GeneralName(GeneralName.iPAddress, "1.2.3.4"), new GeneralName(GeneralName.dNSName, "A"), new GeneralName(GeneralName.registeredID, "0.2.1.4"))); }
From source file:org.codice.ddf.security.certificate.generator.CertificateSigningRequestTest.java
License:Open Source License
@Test public void testNewCertificateBuilderWithSan() throws Exception { final DateTime start = DateTime.now().minusDays(1); final DateTime end = start.plusYears(100); final KeyPair kp = makeKeyPair(); csr.setSerialNumber(1);//from ww w . ja va2 s . co m csr.setNotBefore(start); csr.setNotAfter(end); csr.setCommonName("A"); csr.setSubjectKeyPair(kp); csr.addSubjectAlternativeNames("IP:1.2.3.4", "DNS:A"); final X509Certificate issuerCert = mock(X509Certificate.class); doReturn(new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US")).when(issuerCert) .getSubjectX500Principal(); final JcaX509v3CertificateBuilder builder = csr.newCertificateBuilder(issuerCert); final X509CertificateHolder holder = builder.build(new DemoCertificateAuthority().getContentSigner()); assertThat(holder.getSerialNumber(), equalTo(BigInteger.ONE)); assertThat(holder.getNotBefore(), equalTo(new Time(start.toDate()).getDate())); assertThat(holder.getNotAfter(), equalTo(new Time(end.toDate()).getDate())); assertThat(holder.getSubject().toString(), equalTo("cn=A")); assertThat("Unable to validate public key", holder.getSubjectPublicKeyInfo(), equalTo(SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded()))); final org.bouncycastle.asn1.x509.Extension csn = holder .getExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName); assertThat(csn.getParsedValue().toASN1Primitive().getEncoded(ASN1Encoding.DER), equalTo(new GeneralNamesBuilder().addName(new GeneralName(GeneralName.iPAddress, "1.2.3.4")) .addName(new GeneralName(GeneralName.dNSName, "A")).build().getEncoded(ASN1Encoding.DER))); }
From source file:org.deviceconnect.android.ssl.CertificateAuthority.java
License:MIT License
/** * ???? Subject Alternative Names (SANs) ??. * * @param request ???/*from ww w. j a va2s . co m*/ * @return SubjectAlternativeNames? {@link GeneralNames} * @throws IOException ????? */ private GeneralNames parseSANs(final PKCS10CertificationRequest request) throws IOException { List<ASN1Encodable> generalNames = new ArrayList<>(); CertificationRequestInfo info = request.getCertificationRequestInfo(); ASN1Set attributes = info.getAttributes(); for (int i = 0; i < attributes.size(); i++) { DEREncodable extensionRequestObj = attributes.getObjectAt(i); if (!(extensionRequestObj instanceof DERSequence)) { continue; } DERSequence extensionRequest = (DERSequence) extensionRequestObj; if (extensionRequest.size() != 2) { continue; } DEREncodable idObj = extensionRequest.getObjectAt(0); DEREncodable contentObj = extensionRequest.getObjectAt(1); if (!(idObj instanceof ASN1ObjectIdentifier && contentObj instanceof DERSet)) { continue; } ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) idObj; DERSet content = (DERSet) contentObj; if (!id.getId().equals("1.2.840.113549.1.9.14")) { continue; } if (content.size() < 1) { continue; } DEREncodable extensionsObj = content.getObjectAt(0); if (!(extensionsObj instanceof DERSequence)) { continue; } DERSequence extensions = (DERSequence) extensionsObj; for (int k = 0; k < extensions.size(); k++) { DEREncodable extensionObj = extensions.getObjectAt(k); if (!(extensionObj instanceof DERSequence)) { continue; } DERSequence extension = (DERSequence) extensionObj; if (extension.size() != 2) { continue; } DEREncodable extensionIdObj = extension.getObjectAt(0); DEREncodable extensionContentObj = extension.getObjectAt(1); if (!(extensionIdObj instanceof ASN1ObjectIdentifier)) { continue; } ASN1ObjectIdentifier extensionId = (ASN1ObjectIdentifier) extensionIdObj; if (extensionId.getId().equals("2.5.29.17")) { DEROctetString san = (DEROctetString) extensionContentObj; ASN1StreamParser sanParser = new ASN1StreamParser(san.parser().getOctetStream()); DEREncodable namesObj = sanParser.readObject().getDERObject(); if (namesObj instanceof DERSequence) { DERSequence names = (DERSequence) namesObj; for (int m = 0; m < names.size(); m++) { DEREncodable nameObj = names.getObjectAt(m); if (nameObj instanceof DERTaggedObject) { DERTaggedObject name = (DERTaggedObject) nameObj; switch (name.getTagNo()) { case GeneralName.dNSName: generalNames.add(new GeneralName(GeneralName.dNSName, DERIA5String.getInstance(name, false))); break; case GeneralName.iPAddress: generalNames.add(new GeneralName(GeneralName.iPAddress, DEROctetString.getInstance(name, true))); break; } } } } } } } if (generalNames.size() > 0) { return new GeneralNames(new DERSequence(generalNames.toArray(new ASN1Encodable[generalNames.size()]))); } return null; }
From source file:org.deviceconnect.android.ssl.EndPointKeyStoreManager.java
License:MIT License
@Override public void requestKeyStore(final String ipAddress, final KeyStoreCallback callback) { mExecutor.execute(new Runnable() { @Override/* w w w .ja va2 s. c om*/ public void run() { if (BuildConfig.DEBUG) { mLogger.info("Requested keystore: alias = " + getAlias() + ", IP Address = " + ipAddress); } try { String alias = getAlias(); if (hasIPAddress(ipAddress)) { if (BuildConfig.DEBUG) { mLogger.info("Certificate is cached for alias: " + alias); } Certificate[] chain = mKeyStore.getCertificateChain(getAlias()); callback.onSuccess(mKeyStore, chain[0], chain[1]); } else { if (BuildConfig.DEBUG) { mLogger.info("Generating key pair..."); } final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); final KeyPair keyPair = keyGenerator.generateKeyPair(); if (BuildConfig.DEBUG) { mLogger.info("Generated key pair."); mLogger.info("Executing certificate request..."); } final CertificateAuthorityClient localCA = new CertificateAuthorityClient(mContext, mRootCA); final List<ASN1Encodable> names = new ArrayList<>(); names.add(new GeneralName(GeneralName.iPAddress, ipAddress)); for (SAN cache : mSANs) { if (!cache.mName.equals(ipAddress)) { names.add(new GeneralName(cache.mTagNo, cache.mName)); } } names.add(new GeneralName(GeneralName.iPAddress, "0.0.0.0")); names.add(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); names.add(new GeneralName(GeneralName.dNSName, "localhost")); GeneralNames generalNames = new GeneralNames( new DERSequence(names.toArray(new ASN1Encodable[names.size()]))); localCA.executeCertificateRequest(createCSR(keyPair, "localhost", generalNames), new CertificateRequestCallback() { @Override public void onCreate(final Certificate cert, final Certificate rootCert) { if (BuildConfig.DEBUG) { mLogger.info("Generated server certificate"); } try { Certificate[] chain = { cert, rootCert }; setCertificate(chain, keyPair.getPrivate()); saveKeyStore(); if (BuildConfig.DEBUG) { mLogger.info("Saved server certificate"); } mSANs.add(new SAN(GeneralName.iPAddress, ipAddress)); callback.onSuccess(mKeyStore, cert, rootCert); } catch (Exception e) { mLogger.log(Level.SEVERE, "Failed to save server certificate", e); callback.onError(KeyStoreError.FAILED_BACKUP_KEYSTORE); } finally { localCA.dispose(); } } @Override public void onError() { mLogger.severe("Failed to generate server certificate"); localCA.dispose(); callback.onError(KeyStoreError.FAILED_BACKUP_KEYSTORE); } }); } } catch (KeyStoreException e) { callback.onError(KeyStoreError.BROKEN_KEYSTORE); } catch (GeneralSecurityException e) { callback.onError(KeyStoreError.UNSUPPORTED_CERTIFICATE_FORMAT); } } }); }
From source file:org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java
License:Open Source License
protected void addSubjectAlternativeNames(X509v3CertificateBuilder certificateBuilder, KeyPair keyPair, @Nullable String applicationUri, List<String> dnsNames, List<String> ipAddresses) throws CertIOException, NoSuchAlgorithmException { List<GeneralName> generalNames = new ArrayList<>(); if (applicationUri != null) { generalNames.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); }//from w w w.j a v a 2s.com dnsNames.stream().distinct().map(s -> new GeneralName(GeneralName.dNSName, s)).forEach(generalNames::add); ipAddresses.stream().distinct().map(s -> new GeneralName(GeneralName.iPAddress, s)) .forEach(generalNames::add); certificateBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(generalNames.toArray(new GeneralName[] {}))); // Subject Key Identifier certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); }
From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java
License:Open Source License
@SuppressForbidden(reason = "need to use getHostName to resolve DNS name and getHostAddress to ensure we resolved the name") private static void addSubjectAlternativeNames(boolean resolveName, InetAddress inetAddress, Set<GeneralName> list) { String hostaddress = inetAddress.getHostAddress(); String ip = NetworkAddress.format(inetAddress); list.add(new GeneralName(GeneralName.iPAddress, ip)); if (resolveName && (inetAddress.isLinkLocalAddress() == false)) { String possibleHostName = inetAddress.getHostName(); if (possibleHostName.equals(hostaddress) == false) { list.add(new GeneralName(GeneralName.dNSName, possibleHostName)); }/*from w w w.j a v a2s.c o m*/ } }