List of usage examples for org.bouncycastle.asn1.x509 Extension subjectAlternativeName
ASN1ObjectIdentifier subjectAlternativeName
To view the source code for org.bouncycastle.asn1.x509 Extension subjectAlternativeName.
Click Source Link
From source file:org.elasticsearch.xpack.core.ssl.CertificateToolTests.java
License:Open Source License
public void testGeneratingCsr() throws Exception { Path tempDir = initTempDir(); Path outputFile = tempDir.resolve("out.zip"); Path instanceFile = writeInstancesTo(tempDir.resolve("instances.yml")); Collection<CertificateInformation> certInfos = CertificateTool.parseFile(instanceFile); assertEquals(4, certInfos.size());/*from w w w . j a va 2 s. c o m*/ assertFalse(Files.exists(outputFile)); int keySize = randomFrom(1024, 2048); new CertificateTool.SigningRequestCommand().generateAndWriteCsrs(outputFile, keySize, certInfos); assertTrue(Files.exists(outputFile)); Set<PosixFilePermission> perms = Files.getPosixFilePermissions(outputFile); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_READ)); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_WRITE)); assertEquals(perms.toString(), 2, perms.size()); FileSystem fileSystem = FileSystems.newFileSystem(new URI("jar:" + outputFile.toUri()), Collections.emptyMap()); Path zipRoot = fileSystem.getPath("/"); assertFalse(Files.exists(zipRoot.resolve("ca"))); for (CertificateInformation certInfo : certInfos) { String filename = certInfo.name.filename; assertTrue(Files.exists(zipRoot.resolve(filename))); final Path csr = zipRoot.resolve(filename + "/" + filename + ".csr"); assertTrue(Files.exists(csr)); assertTrue(Files.exists(zipRoot.resolve(filename + "/" + filename + ".key"))); PKCS10CertificationRequest request = readCertificateRequest(csr); assertEquals(certInfo.name.x500Principal.getName(), request.getSubject().toString()); Attribute[] extensionsReq = request.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); if (certInfo.ipAddresses.size() > 0 || certInfo.dnsNames.size() > 0) { assertEquals(1, extensionsReq.length); Extensions extensions = Extensions.getInstance(extensionsReq[0].getAttributeValues()[0]); GeneralNames subjAltNames = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName); assertSubjAltNames(subjAltNames, certInfo); } else { assertEquals(0, extensionsReq.length); } } }
From source file:org.elasticsearch.xpack.core.ssl.CertificateToolTests.java
License:Open Source License
public void testGeneratingSignedPemCertificates() throws Exception { Path tempDir = initTempDir(); Path outputFile = tempDir.resolve("out.zip"); Path instanceFile = writeInstancesTo(tempDir.resolve("instances.yml")); Collection<CertificateInformation> certInfos = CertificateTool.parseFile(instanceFile); assertEquals(4, certInfos.size());/* www . ja v a2s .com*/ int keySize = randomFrom(1024, 2048); int days = randomIntBetween(1, 1024); KeyPair keyPair = CertGenUtils.generateKeyPair(keySize); X509Certificate caCert = CertGenUtils.generateCACertificate(new X500Principal("CN=test ca"), keyPair, days); final boolean generatedCa = randomBoolean(); final boolean keepCaKey = generatedCa && randomBoolean(); final String keyPassword = randomBoolean() ? SecuritySettingsSourceField.TEST_PASSWORD : null; assertFalse(Files.exists(outputFile)); CAInfo caInfo = new CAInfo(caCert, keyPair.getPrivate(), generatedCa, keyPassword == null ? null : keyPassword.toCharArray()); final GenerateCertificateCommand command = new GenerateCertificateCommand(); List<String> args = CollectionUtils.arrayAsArrayList("-keysize", String.valueOf(keySize), "-days", String.valueOf(days), "-pem"); if (keyPassword != null) { args.add("-pass"); args.add(keyPassword); } if (keepCaKey) { args.add("-keep-ca-key"); } final OptionSet options = command.getParser().parse(Strings.toStringArray(args)); command.generateAndWriteSignedCertificates(outputFile, true, options, certInfos, caInfo, null); assertTrue(Files.exists(outputFile)); Set<PosixFilePermission> perms = Files.getPosixFilePermissions(outputFile); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_READ)); assertTrue(perms.toString(), perms.contains(PosixFilePermission.OWNER_WRITE)); assertEquals(perms.toString(), 2, perms.size()); FileSystem fileSystem = FileSystems.newFileSystem(new URI("jar:" + outputFile.toUri()), Collections.emptyMap()); Path zipRoot = fileSystem.getPath("/"); if (generatedCa) { assertTrue(Files.exists(zipRoot.resolve("ca"))); assertTrue(Files.exists(zipRoot.resolve("ca").resolve("ca.crt"))); // check the CA cert try (InputStream input = Files.newInputStream(zipRoot.resolve("ca").resolve("ca.crt"))) { X509Certificate parsedCaCert = readX509Certificate(input); assertThat(parsedCaCert.getSubjectX500Principal().getName(), containsString("test ca")); assertEquals(caCert, parsedCaCert); long daysBetween = getDurationInDays(caCert); assertEquals(days, (int) daysBetween); } if (keepCaKey) { assertTrue(Files.exists(zipRoot.resolve("ca").resolve("ca.key"))); // check the CA key if (keyPassword != null) { try (Reader reader = Files.newBufferedReader(zipRoot.resolve("ca").resolve("ca.key"))) { PEMParser pemParser = new PEMParser(reader); Object parsed = pemParser.readObject(); assertThat(parsed, instanceOf(PEMEncryptedKeyPair.class)); char[] zeroChars = new char[caInfo.password.length]; Arrays.fill(zeroChars, (char) 0); assertArrayEquals(zeroChars, caInfo.password); } } PrivateKey privateKey = PemUtils.readPrivateKey(zipRoot.resolve("ca").resolve("ca.key"), () -> keyPassword != null ? keyPassword.toCharArray() : null); assertEquals(caInfo.certAndKey.key, privateKey); } } else { assertFalse(Files.exists(zipRoot.resolve("ca"))); } for (CertificateInformation certInfo : certInfos) { String filename = certInfo.name.filename; assertTrue(Files.exists(zipRoot.resolve(filename))); final Path cert = zipRoot.resolve(filename + "/" + filename + ".crt"); assertTrue(Files.exists(cert)); assertTrue(Files.exists(zipRoot.resolve(filename + "/" + filename + ".key"))); final Path p12 = zipRoot.resolve(filename + "/" + filename + ".p12"); try (InputStream input = Files.newInputStream(cert)) { X509Certificate certificate = readX509Certificate(input); assertEquals(certInfo.name.x500Principal.toString(), certificate.getSubjectX500Principal().getName()); final int sanCount = certInfo.ipAddresses.size() + certInfo.dnsNames.size() + certInfo.commonNames.size(); if (sanCount == 0) { assertNull(certificate.getSubjectAlternativeNames()); } else { X509CertificateHolder x509CertHolder = new X509CertificateHolder(certificate.getEncoded()); GeneralNames subjAltNames = GeneralNames.fromExtensions(x509CertHolder.getExtensions(), Extension.subjectAlternativeName); assertSubjAltNames(subjAltNames, certInfo); } assertThat(p12, Matchers.not(TestMatchers.pathExists(p12))); } } }
From source file:org.elasticsearch.xpack.core.ssl.CertificateToolTests.java
License:Open Source License
private void assertSubjAltNames(Certificate certificate, String ip, String dns) throws Exception { final X509CertificateHolder holder = new X509CertificateHolder(certificate.getEncoded()); final GeneralNames names = GeneralNames.fromExtensions(holder.getExtensions(), Extension.subjectAlternativeName); final CertificateInformation certInfo = new CertificateInformation("n", "n", Collections.singletonList(ip), Collections.singletonList(dns), Collections.emptyList()); assertSubjAltNames(names, certInfo); }
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 . j av a2 s .co 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.kontalk.certgen.X509Bridge.java
License:Open Source License
/** * Creates a self-signed certificate from a public and private key. The * (critical) key-usage extension is set up with: digital signature, * non-repudiation, key-encipherment, key-agreement and certificate-signing. * The (non-critical) Netscape extension is set up with: SSL client and * S/MIME. A URI subjectAltName may also be set up. * * @param pubKey//from ww w. j av a 2s. com * public key * @param privKey * private key * @param subject * subject (and issuer) DN for this certificate, RFC 2253 format * preferred. * @param startDate * date from which the certificate will be valid * (defaults to current date and time if null) * @param endDate * date until which the certificate will be valid * (defaults to start date and time if null) * @param subjectAltName * URI to be placed in subjectAltName * @return self-signed certificate */ private static X509Certificate createCertificate(PublicKey pubKey, PrivateKey privKey, X500Name subject, Date startDate, Date endDate, String subjectAltName, byte[] publicKeyData) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException, IOException, OperatorCreationException { /* * Sets the signature algorithm. */ BcContentSignerBuilder signerBuilder; String pubKeyAlgorithm = pubKey.getAlgorithm(); if (pubKeyAlgorithm.equals("DSA")) { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithDSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); signerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId); } else if (pubKeyAlgorithm.equals("RSA")) { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("SHA1WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); } /* else if (pubKeyAlgorithm.equals("ECDSA")) { // TODO is this even legal? certGenerator.setSignatureAlgorithm("SHA1WithECDSA"); } */ else { throw new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm); } AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(privKey.getEncoded()); ContentSigner signer = signerBuilder.build(keyp); /* * Sets up the validity dates. */ if (startDate == null) { startDate = new Date(System.currentTimeMillis()); } if (endDate == null) { endDate = startDate; } X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( /* * Sets up the subject distinguished name. * Since it's a self-signed certificate, issuer and subject are the * same. */ subject, /* * The serial-number of this certificate is 1. It makes sense * because it's self-signed. */ BigInteger.ONE, startDate, endDate, subject, /* * Sets the public-key to embed in this certificate. */ SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pubKey.getEncoded()).readObject())); /* * Adds the Basic Constraint (CA: true) extension. */ certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); /* * Adds the Key Usage extension. */ certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment | KeyUsage.keyAgreement | KeyUsage.keyCertSign)); /* * Adds the Netscape certificate type extension. */ certBuilder.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime)); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); /* * Adds the subject key identifier extension. */ SubjectKeyIdentifier subjectKeyIdentifier = extUtils.createSubjectKeyIdentifier(pubKey); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier); /* * Adds the authority key identifier extension. */ AuthorityKeyIdentifier authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(pubKey); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); /* * Adds the subject alternative-name extension. */ if (subjectAltName != null) { GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, subjectAltName)); certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); } /* * Adds the PGP public key block extension. */ SubjectPGPPublicKeyInfo publicKeyExtension = new SubjectPGPPublicKeyInfo(publicKeyData); certBuilder.addExtension(SubjectPGPPublicKeyInfo.OID, false, publicKeyExtension); /* * Creates and sign this certificate with the private key * corresponding to the public key of the certificate * (hence the name "self-signed certificate"). */ X509CertificateHolder holder = certBuilder.build(signer); /* * Checks that this certificate has indeed been correctly signed. */ X509Certificate cert = new JcaX509CertificateConverter().getCertificate(holder); cert.verify(pubKey); return cert; }
From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java
License:Apache License
protected List<Extension> createExtensions(PublicKey publicKey, X509Certificate issuerCertificate) throws CertIOException, NoSuchAlgorithmException, IOException { List<Extension> extensions = new ArrayList<>(); String certType = getProperty(PROPERTY_CERT_TYPE, CERT_TYPE_TLS); // backward compatibility if (CERT_TYPE_CA_OLD.equals(certType)) { certType = CERT_TYPE_CA;/*from w ww .ja va 2s . c om*/ } // subject key identifier boolean criticalKeyIdentifier = getProperty(PROPERTY_CERT_CRITICAL_KEY_IDENTIFIER, false); extensions.add(new Extension(Extension.subjectKeyIdentifier, criticalKeyIdentifier, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey).getEncoded())); // basic constraints if (CERT_TYPE_CA.equals(certType)) { boolean criticalCaConstraints = getProperty(PROPERTY_CERT_CRITICAL_CA, true); int chainLengthConstraint = getProperty(PROPERTY_CERT_CHAIN_LENGTH, 0); if (chainLengthConstraint > 0) { extensions.add(new Extension(Extension.basicConstraints, criticalCaConstraints, new BasicConstraints(chainLengthConstraint).getEncoded())); } else { extensions.add(new Extension(Extension.basicConstraints, criticalCaConstraints, new BasicConstraints(true).getEncoded())); } } // key usage int keyUsageInt = getKeyUsage(certType); if (keyUsageInt != 0) { // FIXME: test whether we can default to true here boolean criticalKeyUsage = getProperty(PROPERTY_CERT_CRITICAL_KEY_USAGE, false); KeyUsage keyUsage = new KeyUsage(keyUsageInt); extensions.add(new Extension(Extension.keyUsage, criticalKeyUsage, keyUsage.getEncoded())); } // extended key usage KeyPurposeId[] keyPurposeDefault = null; if (CERT_TYPE_TLS.equals(certType)) { // defaults for TLS keyPurposeDefault = new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }; } boolean criticalKeyPurpose = getProperty(PROPERTY_CERT_CRITICAL_KEY_PURPOSE, false); KeyPurposeId[] keyPurpose = createKeyPurposeIds(keyPurposeDefault); if (keyPurpose != null) { extensions.add(new Extension(Extension.extendedKeyUsage, criticalKeyPurpose, new ExtendedKeyUsage(keyPurpose).getEncoded())); } // subjectAlternativeName List<ASN1Encodable> subjectAlternativeNames = extractAlternativeNames(PROPERTY_PREFIX_CERT_NAME); if (!subjectAlternativeNames.isEmpty()) { boolean criticalNames = getProperty(PROPERTY_CERT_CRITICAL_NAMES, false); DERSequence subjectAlternativeNamesExtension = new DERSequence( subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()])); extensions.add(new Extension(Extension.subjectAlternativeName, criticalNames, subjectAlternativeNamesExtension.getEncoded())); } if (issuerCertificate == null) { // crl distribution point DistributionPoint[] crlDistributionPoints = createCrlDistributionPoints(); if (crlDistributionPoints != null) { boolean criticalCrlDistPoints = getProperty(PROPERTY_CERT_CRITICAL_CRL_DISTRIBUTION_POINTS, false); extensions.add(new Extension(Extension.cRLDistributionPoints, criticalCrlDistPoints, new CRLDistPoint(crlDistributionPoints).getEncoded())); } // authority information access AccessDescription[] accessDescriptions = createAccessDescriptions(); if (accessDescriptions != null) { boolean criticalAuthorityInformationAccess = getProperty( PROPERTY_CERT_CRITICAL_AUTHORITY_INFORMATION_ACCESS, false); extensions.add(new Extension(Extension.authorityInfoAccess, criticalAuthorityInformationAccess, new AuthorityInformationAccess(accessDescriptions).getEncoded())); } } else { copyExtension(Extension.cRLDistributionPoints, issuerCertificate, extensions); copyExtension(Extension.authorityInfoAccess, issuerCertificate, extensions); } return extensions; }
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 ww. j a v a 2 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 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>//from w w w .j a v a 2s . 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.opensaml.xml.security.x509.tls.MockX509Certificate.java
License:Open Source License
/** * Constructor.//ww w . jav a 2s .c o m * * @param subjectX500Principal */ public MockX509Certificate(X500Principal subject, Collection<List<?>> subjAlts) { super(); subjectX500Principal = subject; subjectAltNames = subjAlts; extensions = new HashMap<String, byte[]>(); // Add proper DER-encoded alt names extension based on subjAlts values, so works with code that extracts // subject alt names via extensions parsing. if (subjAlts != null && subjAlts.size() > 0) { GeneralNamesBuilder generalNamesBuilder = new GeneralNamesBuilder(); for (List<?> subjAlt : subjAlts) { Integer type = (Integer) subjAlt.get(0); String value = (String) subjAlt.get(1); GeneralName generalName = new GeneralName(type, value); generalNamesBuilder.addName(generalName); } GeneralNames generalNames = generalNamesBuilder.build(); try { Extension ext = new Extension(Extension.subjectAlternativeName, false, generalNames.getEncoded()); extensions.put(ext.getExtnId().getId(), ext.getExtnValue().getEncoded("DER")); } catch (IOException e) { throw new RuntimeException("Problem building subject alt names extension", e); } } }