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.opcfoundation.ua.transport.security.BcCertificateProvider.java
License:Open Source License
/** * Generates a new certificate using the Bouncy Castle implementation. * <p>/*from w w w. j av a2 s .c om*/ * The method is used from * {@link CertificateUtils#createApplicationInstanceCertificate(String, String, String, int, String...)} * and * {@link CertificateUtils#renewApplicationInstanceCertificate(String, String, String, int, org.opcfoundation.ua.transport.security.KeyPair, String...)} * * @param domainName * the X500 domain name for the certificate * @param publicKey * the public key of the cert * @param privateKey * the private key of the cert * @param issuerKeys * the certificate and private key of the issuer * @param from * validity start time * @param to * validity end time * @param serialNumber * a unique serial number for the certificate * @param applicationUri * the OPC UA ApplicationUri of the application - added to * SubjectAlternativeName * @param hostNames * the additional host names to add to SubjectAlternativeName * @return the generated certificate * @throws GeneralSecurityException * if the generation fails * @throws IOException * if the generation fails due to an IO exception */ @Override public X509Certificate generateCertificate(String domainName, PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys, Date from, Date to, BigInteger serial, String applicationUri, String... hostNames) throws IOException, GeneralSecurityException { JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); X509v3CertificateBuilder certBldr; AuthorityKeyIdentifier authorityKeyIdentifier; PrivateKey signerKey; if (issuerKeys == null) { X500Name dn = new X500Name(domainName); certBldr = new JcaX509v3CertificateBuilder(dn, serial, from, to, dn, publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey); signerKey = privateKey; } else { X509Certificate caCert = issuerKeys.getCertificate().getCertificate(); certBldr = new JcaX509v3CertificateBuilder(caCert, serial, from, to, new X500Principal(domainName), publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert); signerKey = issuerKeys.getPrivateKey().getPrivateKey(); } certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)) .addExtension(Extension.basicConstraints, false, new BasicConstraints(false)).addExtension( Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); // BC 1.49: certBldr.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth })); // create the extension value // URI Name List<GeneralName> names = new ArrayList<GeneralName>(); names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); // Add DNS name from ApplicationUri boolean hasDNSName = false; String uriHostName = null; try { String[] appUriParts = applicationUri.split("[:/]"); if (appUriParts.length > 1) { uriHostName = appUriParts[1]; if (!uriHostName.toLowerCase().equals("localhost")) { GeneralName dnsName = new GeneralName(GeneralName.dNSName, uriHostName); names.add(dnsName); hasDNSName = true; } } } catch (Exception e) { logger.warn("Cannot initialize DNS Name to Certificate from ApplicationUri {}", applicationUri); } // Add other DNS Names List<GeneralName> ipAddressNames = new ArrayList<GeneralName>(); if (hostNames != null) for (String hostName : hostNames) { boolean isIpAddress = hostName.matches("^[0-9.]+$"); if (!hostName.equals(uriHostName) && !hostName.toLowerCase().equals("localhost")) { GeneralName dnsName = new GeneralName( hostName.matches("^[0-9.]+$") ? GeneralName.iPAddress : GeneralName.dNSName, hostName); if (isIpAddress) ipAddressNames.add(dnsName); else { names.add(dnsName); hasDNSName = true; } } } // Add IP Addresses, if no host names are defined if (!hasDNSName) for (GeneralName n : ipAddressNames) names.add(n); final GeneralNames subjectAltNames = new GeneralNames(names.toArray(new GeneralName[0])); certBldr.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); // ***** generate certificate ***********/ try { ContentSigner signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm()) .setProvider("BC").build(signerKey); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } }
From source file:org.opcfoundation.ua.utils.BouncyCastleUtils.java
License:Open Source License
/** * Generates a new certificate using the Bouncy Castle implementation. * <p>/* w ww . ja va2 s . c o m*/ * The method is used from * {@link CertificateUtils#createApplicationInstanceCertificate(String, String, String, int, String...)} * and * {@link CertificateUtils#renewApplicationInstanceCertificate(String, String, String, int, org.opcfoundation.ua.transport.security.KeyPair, String...)} * * @param domainName * the X500 domain name for the certificate * @param publicKey * the public key of the cert * @param privateKey * the private key of the cert * @param issuerKeys * the certificate and private key of the issuer * @param from * validity start time * @param to * validity end time * @param serialNumber * a unique serial number for the certificate * @param applicationUri * the OPC UA ApplicationUri of the application - added to * SubjectAlternativeName * @param hostNames * the additional host names to ass to SubjectAlternativeName * @return the generated certificate * @throws GeneralSecurityException * if the generation fails * @throws IOException * if the generation fails due to an IO exception */ public static X509Certificate generateCertificate(String domainName, PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys, Date from, Date to, BigInteger serial, String applicationUri, String... hostNames) throws IOException, GeneralSecurityException { JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); X509v3CertificateBuilder certBldr; AuthorityKeyIdentifier authorityKeyIdentifier; PrivateKey signerKey; if (issuerKeys == null) { X500Name dn = new X500Name(domainName); certBldr = new JcaX509v3CertificateBuilder(dn, serial, from, to, dn, publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey); signerKey = privateKey; } else { X509Certificate caCert = issuerKeys.getCertificate().getCertificate(); certBldr = new JcaX509v3CertificateBuilder(caCert, serial, from, to, new X500Principal(domainName), publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert); signerKey = issuerKeys.getPrivateKey().getPrivateKey(); } certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)) .addExtension(Extension.basicConstraints, false, new BasicConstraints(false)).addExtension( Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); certBldr.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth })); // Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>(); // extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); // extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); // certBldr.addExtension(Extension.extendedKeyUsage, false, // new ExtendedKeyUsage(extendedKeyUsages)); // BC 1.49: // certBldr.addExtension(X509Extension.extendedKeyUsage, false, // new ExtendedKeyUsage(new KeyPurposeId[] { // KeyPurposeId.id_kp_serverAuth, // KeyPurposeId.id_kp_clientAuth })); // create the extension value // URI Name List<GeneralName> names = new ArrayList<GeneralName>(); names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); // Add DNS name from ApplicationUri boolean hasDNSName = false; String uriHostName = null; try { String[] appUriParts = applicationUri.split("[:/]"); if (appUriParts.length > 1) { uriHostName = appUriParts[1]; if (!uriHostName.toLowerCase().equals("localhost")) { GeneralName dnsName = new GeneralName(GeneralName.dNSName, uriHostName); names.add(dnsName); hasDNSName = true; } } } catch (Exception e) { logger.warn("Cannot initialize DNS Name to Certificate from ApplicationUri {}", applicationUri); } // Add other DNS Names List<GeneralName> ipAddressNames = new ArrayList<GeneralName>(); if (hostNames != null) for (String hostName : hostNames) { boolean isIpAddress = hostName.matches("^[0-9.]+$"); if (!hostName.equals(uriHostName) && !hostName.toLowerCase().equals("localhost")) { GeneralName dnsName = new GeneralName( hostName.matches("^[0-9.]+$") ? GeneralName.iPAddress : GeneralName.dNSName, hostName); if (isIpAddress) ipAddressNames.add(dnsName); else { names.add(dnsName); hasDNSName = true; } } } // Add IP Addresses, if no host names are defined if (!hasDNSName) for (GeneralName n : ipAddressNames) names.add(n); final GeneralNames subjectAltNames = new GeneralNames(names.toArray(new GeneralName[0])); certBldr.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); //***** generate certificate ***********/ try { ContentSigner signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm()) .setProvider("BC").build(signerKey); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } }
From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java
License:Open Source License
@Override public Map.Entry<X509GeneralName, String> asImmutableMapEntry(GeneralName generalName) { int nameType = generalName.getTagNo(); X509GeneralName x509GeneralName = null; String value = null;//from w w w.j av a 2 s. co m switch (nameType) { case GeneralName.otherName: ASN1Sequence otherName = (ASN1Sequence) generalName.getName(); // String oid = ( ( DERObjectIdentifier ) otherName.getObjectAt( 0 ) ).getId(); x509GeneralName = X509GeneralName.otherName; value = cryptCodex.toString(otherName.getObjectAt(1)); break; case GeneralName.rfc822Name: x509GeneralName = X509GeneralName.rfc822Name; value = generalName.getName().toString(); break; case GeneralName.dNSName: x509GeneralName = X509GeneralName.dNSName; value = generalName.getName().toString(); break; case GeneralName.registeredID: x509GeneralName = X509GeneralName.registeredID; value = generalName.getName().toString(); break; case GeneralName.x400Address: x509GeneralName = X509GeneralName.x400Address; value = generalName.getName().toString(); break; case GeneralName.ediPartyName: x509GeneralName = X509GeneralName.ediPartyName; value = generalName.getName().toString(); break; case GeneralName.directoryName: x509GeneralName = X509GeneralName.directoryName; value = new X500Principal(((X509Name) generalName.getName()).toString()) .getName(X500Principal.CANONICAL); break; case GeneralName.uniformResourceIdentifier: x509GeneralName = X509GeneralName.uniformResourceIdentifier; value = generalName.getName().toString(); break; case GeneralName.iPAddress: // What about IPv6 addresses ? ASN1OctetString iPAddress = (ASN1OctetString) generalName.getName(); byte[] iPAddressBytes = iPAddress.getOctets(); StringBuilder sb = new StringBuilder(); for (int idx = 0; idx < iPAddressBytes.length; idx++) { sb.append(iPAddressBytes[idx] & 0xFF); if (idx + 1 < iPAddressBytes.length) { sb.append("."); } } x509GeneralName = X509GeneralName.iPAddress; value = sb.toString(); break; default: x509GeneralName = X509GeneralName.unknownGeneralName; value = generalName.getName().toString(); } return new ImmutableMapEntry(x509GeneralName, value); }
From source file:org.shredzone.acme4j.util.CertificateUtils.java
License:Apache License
/** * Creates a self-signed {@link X509Certificate} that can be used for * {@link org.shredzone.acme4j.challenge.TlsSni01Challenge}. The certificate is valid * for 7 days./*from ww w .j ava 2s . c om*/ * * @param keypair * A domain {@link KeyPair} to be used for the challenge * @param subject * Subject to create a certificate for * @return Created certificate * @deprecated Will be removed when * {@link org.shredzone.acme4j.challenge.TlsSni01Challenge} is removed */ @Deprecated public static X509Certificate createTlsSniCertificate(KeyPair keypair, String subject) throws IOException { final long now = System.currentTimeMillis(); final long validSpanMs = 7 * 24 * 60 * 60 * 1000L; final String signatureAlg = "SHA256withRSA"; try { X500Name issuer = new X500Name("CN=acme.invalid"); BigInteger serial = BigInteger.valueOf(now); Date notBefore = new Date(now); Date notAfter = new Date(now + validSpanMs); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, keypair.getPublic()); GeneralName[] gns = new GeneralName[1]; gns[0] = new GeneralName(GeneralName.dNSName, subject); certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns)); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlg); byte[] cert = certBuilder.build(signerBuilder.build(keypair.getPrivate())).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert)); } catch (CertificateException | OperatorCreationException ex) { throw new IOException(ex); } }
From source file:org.shredzone.acme4j.util.CertificateUtils.java
License:Apache License
/** * Creates a self-signed {@link X509Certificate} that can be used for * {@link TlsSni02Challenge}. The certificate is valid for 7 days. * * @param keypair/*from w w w. j a v a2s. c om*/ * A domain {@link KeyPair} to be used for the challenge * @param sanA * SAN-A to be used in the certificate * @param sanB * SAN-B to be used in the certificate * @return Created certificate */ public static X509Certificate createTlsSni02Certificate(KeyPair keypair, String sanA, String sanB) throws IOException { final long now = System.currentTimeMillis(); final long validSpanMs = 7 * 24 * 60 * 60 * 1000L; final String signatureAlg = "SHA256withRSA"; try { X500Name issuer = new X500Name("CN=acme.invalid"); BigInteger serial = BigInteger.valueOf(now); Date notBefore = new Date(now); Date notAfter = new Date(now + validSpanMs); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, keypair.getPublic()); GeneralName[] gns = new GeneralName[2]; gns[0] = new GeneralName(GeneralName.dNSName, sanA); gns[1] = new GeneralName(GeneralName.dNSName, sanB); certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns)); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlg); byte[] cert = certBuilder.build(signerBuilder.build(keypair.getPrivate())).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert)); } catch (CertificateException | OperatorCreationException ex) { throw new IOException(ex); } }
From source file:org.shredzone.acme4j.util.CertificateUtilsTest.java
License:Apache License
/** * Extracts all DNSName SANs from a certificate. * * @param cert/* www . j a va 2s . c om*/ * {@link X509Certificate} * @return Set of DNSName */ private Set<String> getSANs(X509Certificate cert) throws CertificateParsingException { Set<String> result = new HashSet<>(); for (List<?> list : cert.getSubjectAlternativeNames()) { if (((Number) list.get(0)).intValue() == GeneralName.dNSName) { result.add((String) list.get(1)); } } return result; }
From source file:org.shredzone.acme4j.util.CSRBuilder.java
License:Apache License
/** * Signs the completed CSR.//from w w w . jav a 2 s . c o m * * @param keypair * {@link KeyPair} to sign the CSR with */ public void sign(KeyPair keypair) throws IOException { if (namelist.isEmpty()) { throw new IllegalStateException("No domain was set"); } if (keypair == null) { throw new IllegalArgumentException("keypair must not be null"); } try { GeneralName[] gns = new GeneralName[namelist.size()]; for (int ix = 0; ix < namelist.size(); ix++) { gns[ix] = new GeneralName(GeneralName.dNSName, namelist.get(ix)); } GeneralNames subjectAltName = new GeneralNames(gns); PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder( namebuilder.build(), keypair.getPublic()); ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator(); extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, subjectAltName); p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate()); PrivateKey pk = keypair.getPrivate(); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder( pk instanceof ECKey ? EC_SIGNATURE_ALG : SIGNATURE_ALG); ContentSigner signer = csBuilder.build(pk); csr = p10Builder.build(signer); } catch (OperatorCreationException ex) { throw new IOException("Could not generate CSR", ex); } }
From source file:org.sipfoundry.sipxconfig.cert.CertificateGenerator.java
License:Contributor Agreement License
@Override public X509Certificate createCertificate() throws GeneralSecurityException { try {/* w w w . j a v a 2 s .c o m*/ KeyPair pair = getKeyPair(); X509v3CertificateBuilder gen = createCertificateGenerator(m_issuer, pair.getPublic()); gen.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pair.getPublic())); gen.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); List<GeneralName> names = new ArrayList<GeneralName>(); if (StringUtils.isNotBlank(m_sipDomain)) { names.add(new GeneralName(GeneralName.uniformResourceIdentifier, format("sip:%s", m_sipDomain))); } names.add(new GeneralName(GeneralName.dNSName, getCommonName())); gen.addExtension(X509Extension.subjectAlternativeName, false, new GeneralNames((GeneralName[]) names.toArray(new GeneralName[names.size()]))); return CertificateUtils.generateCert(gen, getAlgorithm(), getAuthorityPrivateKey()); } catch (CertIOException e) { throw new GeneralSecurityException(e); } }
From source file:org.tramaci.onionmail.LibSTLS.java
License:Open Source License
public static X509Certificate CreateCert(KeyPair KP, String onion, long Dfrom, long Dto, String info, String[] AltName) throws Exception { //OK byte[] bi = Stdio.md5(onion.getBytes()); byte[] bx = new byte[bi.length + 9]; System.arraycopy(bi, 0, bx, 1, bi.length); bx[0] = 0x7C;/*ww w. ja v a 2 s . c o m*/ byte[] tmp = Stdio.Stosx(new long[] { Dfrom / 1000L, Dto / 1000L }, 4); int bp = 17; for (int ax = 0; ax < 8; ax++) bx[bp++] = tmp[ax]; Date startDate = new Date(Dfrom); // time from which certificate is valid Date expiryDate = new Date(Dto); // time after which certificate is not valid BigInteger serialNumber = new BigInteger(bx); // serial number for certificate KeyPair keyPair = KP; // EC public/private key pair X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); if (info != null && info.length() > 0) info = ", " + info; else info = ""; X500Principal dnName = new X500Principal("CN=" + onion + info); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(dnName); certGen.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(dnName); // note: same as issuer certGen.setPublicKey(KP.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); if (AltName != null) { int cx = AltName.length; for (int ax = 0; ax < cx; ax++) try { GeneralName generalName = new GeneralName(GeneralName.dNSName, new DERIA5String(AltName[ax].toLowerCase().trim())); GeneralNames subjectAltNames = new GeneralNames(generalName); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new DEROctetString(subjectAltNames)); } catch (Exception EI) { Main.echo("CreateCert Error: " + EI.getMessage() + " (altName=`" + AltName[ax] + "`)\n"); } } X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC"); return cert; }
From source file:org.usrz.libs.crypto.cert.X509CertificateBuilder.java
License:Apache License
/** * Add an alternative name in the form of a DNS name (a host name) to the * generated certificate.//from w ww . j av a 2s . co m */ public X509CertificateBuilder withAlternativeNameDNS(String dnsName) { if (dnsName == null) throw new NullPointerException("Null DNS name"); alternativeNames.add(new GeneralName(GeneralName.dNSName, dnsName)); return this; }