List of usage examples for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier
ASN1ObjectIdentifier subjectKeyIdentifier
To view the source code for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier.
Click Source Link
From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java
License:Open Source License
/** * Generates a signed certificate/*from w w w . j a v a2 s . co m*/ * * @param principal the principal of the certificate; commonly referred to as the * distinguished name (DN) * @param subjectAltNames the subject alternative names that should be added to the * certificate as an X509v3 extension. May be {@code null} * @param keyPair the key pair that will be associated with the certificate * @param caCert the CA certificate. If {@code null}, this results in a self signed * certificate * @param caPrivKey the CA private key. If {@code null}, this results in a self signed * certificate * @param isCa whether or not the generated certificate is a CA * @param days no of days certificate will be valid from now * @param signatureAlgorithm algorithm used for signing certificate. If {@code null} or * empty, then use default algorithm {@link CertGenUtils#getDefaultSignatureAlgorithm(PrivateKey)} * @return a signed {@link X509Certificate} */ private static X509Certificate generateSignedCertificate(X500Principal principal, GeneralNames subjectAltNames, KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivKey, boolean isCa, int days, String signatureAlgorithm) throws NoSuchAlgorithmException, CertificateException, CertIOException, OperatorCreationException { Objects.requireNonNull(keyPair, "Key-Pair must not be null"); final DateTime notBefore = new DateTime(DateTimeZone.UTC); if (days < 1) { throw new IllegalArgumentException("the certificate must be valid for at least one day"); } final DateTime notAfter = notBefore.plusDays(days); final BigInteger serial = CertGenUtils.getSerial(); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); X500Name subject = X500Name.getInstance(principal.getEncoded()); final X500Name issuer; final AuthorityKeyIdentifier authorityKeyIdentifier; if (caCert != null) { if (caCert.getBasicConstraints() < 0) { throw new IllegalArgumentException("ca certificate is not a CA!"); } issuer = X500Name.getInstance(caCert.getIssuerX500Principal().getEncoded()); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()); } else { issuer = subject; authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(keyPair.getPublic()); } JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, new Time(notBefore.toDate(), Locale.ROOT), new Time(notAfter.toDate(), Locale.ROOT), subject, keyPair.getPublic()); builder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(keyPair.getPublic())); builder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); if (subjectAltNames != null) { builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); } builder.addExtension(Extension.basicConstraints, isCa, new BasicConstraints(isCa)); PrivateKey signingKey = caPrivKey != null ? caPrivKey : keyPair.getPrivate(); ContentSigner signer = new JcaContentSignerBuilder( (Strings.isNullOrEmpty(signatureAlgorithm)) ? getDefaultSignatureAlgorithm(signingKey) : signatureAlgorithm).setProvider(CertGenUtils.BC_PROV).build(signingKey); X509CertificateHolder certificateHolder = builder.build(signer); return new JcaX509CertificateConverter().getCertificate(certificateHolder); }
From source file:org.keycloak.common.util.CertificateUtils.java
License:Apache License
/** * Generates version 3 {@link java.security.cert.X509Certificate}. * * @param keyPair the key pair//from w w w. j av a 2s . c om * @param caPrivateKey the CA private key * @param caCert the CA certificate * @param subject the subject name * * @return the x509 certificate * * @throws Exception the exception */ public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert, String subject) throws Exception { try { X500Name subjectDN = new X500Name("CN=" + subject); // Serial Number SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt())); // Validity Date notBefore = new Date(System.currentTimeMillis()); Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3); // SubjectPublicKeyInfo SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(keyPair.getPublic().getEncoded())); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder( new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo); DigestCalculator digCalc = new BcDigestCalculatorProvider() .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc); // Subject Key Identifier certGen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo)); // Authority Key Identifier certGen.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo)); // Key Usage certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); // Extended Key Usage KeyPurposeId[] EKU = new KeyPurposeId[2]; EKU[0] = KeyPurposeId.id_kp_emailProtection; EKU[1] = KeyPurposeId.id_kp_serverAuth; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU)); // Basic Constraints certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); // Content Signer ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC") .build(caPrivateKey); // Certificate return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen)); } catch (Exception e) { throw new RuntimeException("Error creating X509v3Certificate.", e); } }
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//w w w . j a v a 2 s . c om * 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.kse.gui.KeyStoreTableModel.java
License:Open Source License
private String getCertificateSKI(String alias, KeyStore keyStore) throws CryptoException, KeyStoreException { X509Certificate x509Cert = getCertificate(alias, keyStore); try {/*from w w w.j a v a 2 s.c o m*/ byte[] skiValue = x509Cert.getExtensionValue(Extension.subjectKeyIdentifier.getId()); byte[] octets = DEROctetString.getInstance(skiValue).getOctets(); byte[] skiBytes = SubjectKeyIdentifier.getInstance(octets).getKeyIdentifier(); return HexUtil.getHexString(skiBytes); } catch (Exception e) { return "-"; } }
From source file:org.metaeffekt.dcc.agent.AuthenticationKeyGenerator.java
License:Apache License
private X509Certificate generateCertificate(KeyPair key, String certificateCN, Date begin, Date end) throws GeneralSecurityException, IOException, OperatorException { final X500NameBuilder nameBuilder = new X500NameBuilder(); nameBuilder.addRDN(BCStyle.CN, certificateCN); final X500Name name = nameBuilder.build(); final JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(name, new BigInteger(String.valueOf(random.nextInt())), begin, end, name, key.getPublic()); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(key.getPublic())); final X509CertificateHolder certificateHolder = certBuilder .build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(key.getPrivate())); final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateHolder); return certificate; }
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 w w . 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 w w . jav a 2 s. co 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.transport.security.BcCertificateProvider.java
License:Open Source License
/** * Build a X509 V3 certificate to use as an issuer (CA) certificate. The * certificate does not define OPC UA specific fields, so it cannot be used * for an application instance certificate. * /*from w w w. j a v a2 s. c o m*/ * @param publicKey * the public key to use for the certificate * @param privateKey * the private key corresponding to the publicKey * @param issuerKeys * the certificate and private key of the certificate issuer: if * null a self-signed certificate is created. * @param commonName * the CommonName to use for the subject of the certificate. * @param serialNr * @param startDate * @param expiryDate * @throws OperatorCreationException */ @Override public X509Certificate generateIssuerCert(PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys, String commonName, BigInteger serialNr, Date startDate, Date expiryDate) throws GeneralSecurityException, IOException { JcaX509v3CertificateBuilder certBldr; JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); AuthorityKeyIdentifier authorityKeyIdentifier; if (issuerKeys == null) { X500Name dn = new X500Name(commonName); certBldr = new JcaX509v3CertificateBuilder(dn, serialNr, startDate, expiryDate, dn, publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey); } else { X509Certificate caCert = issuerKeys.getCertificate().getCertificate(); certBldr = new JcaX509v3CertificateBuilder(caCert, serialNr, startDate, expiryDate, new X500Principal(commonName), publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert); } certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(0)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); ContentSigner signer; try { signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm()) .setProvider("BC").build(privateKey); } catch (OperatorCreationException e) { throw new GeneralSecurityException("Failed to sign the certificate", e); } return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); }
From source file:org.opcfoundation.ua.utils.BouncyCastleUtils.java
License:Open Source License
/** * Build a X509 V3 certificate to use as an issuer (CA) certificate. The * certificate does not define OPC UA specific fields, so it cannot be used * for an application instance certificate. * //from w w w . j a v a 2 s .c om * @param publicKey * the public key to use for the certificate * @param privateKey * the private key corresponding to the publicKey * @param issuerKeys * the certificate and private key of the certificate issuer: if * null a self-signed certificate is created. * @param commonName * the CommonName to use for the subject of the certificate. * @param serialNr * @param startDate * @param expiryDate * @throws OperatorCreationException */ public static X509Certificate generateIssuerCert(PublicKey publicKey, PrivateKey privateKey, KeyPair issuerKeys, String commonName, BigInteger serialNr, Date startDate, Date expiryDate) throws GeneralSecurityException, IOException { JcaX509v3CertificateBuilder certBldr; JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); AuthorityKeyIdentifier authorityKeyIdentifier; if (issuerKeys == null) { X500Name dn = new X500Name(commonName); certBldr = new JcaX509v3CertificateBuilder(dn, serialNr, startDate, expiryDate, dn, publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(publicKey); } else { X509Certificate caCert = issuerKeys.getCertificate().getCertificate(); certBldr = new JcaX509v3CertificateBuilder(caCert, serialNr, startDate, expiryDate, new X500Principal(commonName), publicKey); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert); } certBldr.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(publicKey)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(0)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); ContentSigner signer; try { signer = new JcaContentSignerBuilder(CertificateUtils.getCertificateSignatureAlgorithm()) .setProvider("BC").build(privateKey); } catch (OperatorCreationException e) { throw new GeneralSecurityException("Failed to sign the certificate", e); } return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer)); }
From source file:org.opcfoundation.ua.utils.BouncyCastleUtils.java
License:Open Source License
/** * Generates a new certificate using the Bouncy Castle implementation. * <p>//ww w .j av 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 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); } }