List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name
public X500Name(String dirName)
From source file:org.opcfoundation.ua.utils.BouncyCastleUtils.java
License:Open Source License
/** * Generates a new certificate using the Bouncy Castle implementation. * <p>/* w w w. ja v a2 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 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.openconcerto.modules.finance.payment.ebics.crypto.X509CertificateGenerator.java
License:Open Source License
/** * This method implements the public one, but offers an additional parameter which is only used * when creating a new CA, namely the export alias to use. * //w ww. j a v a2 s. c o m * @param commonName @see #createCertificate(String, int, String, String) * @param validityDays @see #createCertificate(String, int, String, String) * @param exportFile @see #createCertificate(String, int, String, String) * @param exportPassword @see #createCertificate(String, int, String, String) * @param exportAlias If this additional parameter is null, a default value will be used as the * "friendly name" in the PKCS12 file. * @return @see #createCertificate(String, int, String, String) * * @see #X509CertificateGenerator(boolean) */ protected boolean createCertificate(String commonName, int validityDays, String exportFile, String exportPassword, String exportAlias) throws IOException, InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException, DataLengthException, CryptoException, KeyStoreException, CertificateException, InvalidKeySpecException { if (commonName == null || exportFile == null || exportPassword == null || validityDays < 1) { throw new IllegalArgumentException("Can not work with null parameter"); } System.out.println("Generating certificate for distinguished common subject name '" + commonName + "', valid for " + validityDays + " days"); SecureRandom sr = new SecureRandom(); // the JCE representation PublicKey pubKey; PrivateKey privKey; // the BCAPI representation RSAPrivateCrtKeyParameters privateKey = null; System.out.println("Creating RSA keypair"); // generate the keypair for the new certificate RSAKeyPairGenerator gen = new RSAKeyPairGenerator(); // TODO: what are these values?? gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), sr, 1024, 80)); AsymmetricCipherKeyPair keypair = gen.generateKeyPair(); System.out .println("Generated keypair, extracting components and creating public structure for certificate"); RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic(); privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate(); // used to get proper encoding for the certificate RSAPublicKeyStructure pkStruct = new RSAPublicKeyStructure(publicKey.getModulus(), publicKey.getExponent()); System.out.println("New public key is '" + new String(Hex.encode(pkStruct.getEncoded())) + ", exponent=" + publicKey.getExponent() + ", modulus=" + publicKey.getModulus()); // TODO: these two lines should go away // JCE format needed for the certificate - because getEncoded() is necessary... pubKey = KeyFactory.getInstance("RSA") .generatePublic(new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent())); // and this one for the KeyStore privKey = KeyFactory.getInstance("RSA") .generatePrivate(new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(), privateKey.getExponent(), privateKey.getP(), privateKey.getQ(), privateKey.getDP(), privateKey.getDQ(), privateKey.getQInv())); Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityDays); X500Name x509Name = new X500Name("CN=" + commonName); V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator(); certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis()))); if (caCert != null) { // Attention: this is a catch! Just using // "new X509Name(caCert.getSubjectDN().getName())" will not work! // I don't know why, because the issuerDN strings look similar with both versions. certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert)); } else { // aha, no CA set, which means that we should create a self-signed certificate (called // from createCA) certGen.setIssuer(x509Name); } certGen.setSubject(x509Name); // TODO GM: DERObjectIdentifier sigOID = PKCSObjectIdentifiers.sha1WithRSAEncryption;// DERObjectIdentifier. // X509Util.getAlgorithmOID(CertificateSignatureAlgorithm); AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull()); certGen.setSignature(sigAlgId); // certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(sigAlgId, // pkStruct.toASN1Object())); // TODO: why does the coding above not work? - make me work without PublicKey class certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())).readObject())); certGen.setStartDate(new Time(new Date(System.currentTimeMillis()))); certGen.setEndDate(new Time(expiry.getTime())); // These X509v3 extensions are not strictly necessary, but be nice and provide them... Hashtable extensions = new Hashtable(); Vector extOrdering = new Vector(); addExtensionHelper(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey), extOrdering, extensions); if (caCert != null) { // again: only if we have set CA addExtensionHelper(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert), extOrdering, extensions); } else { // but if we create a new self-signed cert, set its capability to be a CA // this is a critical extension (true)! addExtensionHelper(X509Extension.basicConstraints, true, new BasicConstraints(0), extOrdering, extensions); } certGen.setExtensions(new X509Extensions(extOrdering, extensions)); System.out.println("Certificate structure generated, creating SHA1 digest"); // attention: hard coded to be SHA1+RSA! SHA1Digest digester = new SHA1Digest(); AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine()); TBSCertificateStructure tbsCert = certGen.generateTBSCertificate(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(tbsCert); // and now sign byte[] signature; byte[] certBlock = bOut.toByteArray(); // first create digest System.out.println("Block to sign is '" + new String(Hex.encode(certBlock)) + "'"); digester.update(certBlock, 0, certBlock.length); byte[] hash = new byte[digester.getDigestSize()]; digester.doFinal(hash, 0); // and sign that if (caCert != null) { rsa.init(true, caPrivateKey); } else { // no CA - self sign System.out.println("No CA has been set, creating self-signed certificate as a new CA"); rsa.init(true, privateKey); } DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash); byte[] digest = dInfo.getEncoded(ASN1Encodable.DER); signature = rsa.processBlock(digest, 0, digest.length); System.out.println("SHA1/RSA signature of digest is '" + new String(Hex.encode(signature)) + "'"); // and finally construct the certificate structure ASN1EncodableVector v = new ASN1EncodableVector(); v.add(tbsCert); v.add(sigAlgId); v.add(new DERBitString(signature)); X509CertificateObject clientCert = new X509CertificateObject( new X509CertificateStructure(new DERSequence(v))); System.out.println("Verifying certificate for correct signature with CA public key"); /* * if (caCert != null) { clientCert.verify(caCert.getPublicKey()); } else { * clientCert.verify(pubKey); } */ // and export as PKCS12 formatted file along with the private key and the CA certificate System.out.println("Exporting certificate in PKCS12 format"); PKCS12BagAttributeCarrier bagCert = clientCert; // if exportAlias is set, use that, otherwise a default name bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(exportAlias == null ? CertificateExportFriendlyName : exportAlias)); bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifierStructure(pubKey)); // this does not work as in the example /* * PKCS12BagAttributeCarrier bagKey = (PKCS12BagAttributeCarrier)privKey; * bagKey.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new * SubjectKeyIdentifierStructure(tmpKey)); */ JDKPKCS12KeyStore store; store = new JDKPKCS12KeyStore.BCPKCS12KeyStore(); store.engineLoad(null, null); FileOutputStream fOut = new FileOutputStream(exportFile); X509Certificate[] chain; if (caCert != null) { chain = new X509Certificate[2]; // first the client, then the CA certificate - this is the expected order for a // certificate chain chain[0] = clientCert; chain[1] = caCert; } else { // for a self-signed certificate, there is no chain... chain = new X509Certificate[1]; chain[0] = clientCert; } store.engineSetKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias, privKey, exportPassword.toCharArray(), chain); store.engineStore(fOut, exportPassword.toCharArray()); return true; }
From source file:org.openestate.tool.server.utils.SslGenerator.java
License:Apache License
/** * Start SSL initialization./*w w w . jav a 2 s . co m*/ * * @param args command line arguments, * the first argument might contain the common name, * the second argument might contain the keystore password */ @SuppressWarnings("Duplicates") public static void main(String[] args) { final Console console = System.console(); final String line = StringUtils.repeat("-", 75); console.writer().println(StringUtils.EMPTY); console.writer().println(line); console.writer().println(I18N.tr("Generate RSA key pair and certificate for SSL encryption.")); console.writer().println(line); console.writer().println(StringUtils.EMPTY); // register bouncy castle provider Security.addProvider(new BouncyCastleProvider()); // get common name String commonName = (args.length > 0) ? StringUtils.trimToNull(args[0]) : null; while (commonName == null) { //LOGGER.error( "No common name was specified as first command line argument!" ); //System.exit( 1 ); //return; console.writer().print(I18N.tr("Enter the ip-address / hostname of this server:") + StringUtils.SPACE); console.writer().flush(); commonName = StringUtils.trimToNull(console.readLine()); } // get password char[] password = (args.length > 1) ? StringUtils.trimToEmpty(args[1]).toCharArray() : null; if (password == null) { //LOGGER.error( "No password was specified as second command line argument!" ); //System.exit( 1 ); //return; while (password == null) { console.writer().print(I18N.tr("Enter the password to access the keystore:") + StringUtils.SPACE); console.writer().flush(); password = console.readPassword(); } console.writer().print(I18N.tr("Enter the password to access the keystore again:") + StringUtils.SPACE); console.writer().flush(); char[] password2 = console.readPassword(); if (!StringUtils.equals(String.valueOf(password), String.valueOf(password2))) { console.writer().println(StringUtils.capitalize(I18N.tr("error")) + "!"); console.writer().println(I18N.tr("The provided passwords do not match.")); System.exit(1); } } console.writer().println(StringUtils.EMPTY); console.writer().println(line); console.writer().println(I18N.tr("Creating files for SSL encryption...")); console.writer().println(line); console.writer().println(StringUtils.EMPTY); final File etcDir; final File sslDir; try { etcDir = ServerUtils.getEtcDir(); sslDir = new File(etcDir, "ssl"); } catch (IOException ex) { LOGGER.error("Can't locate ssl directory!"); System.exit(1); return; } if (!sslDir.exists() && !sslDir.mkdirs()) { LOGGER.error("Can't create ssl directory at '" + sslDir.getAbsolutePath() + "'!"); System.exit(1); return; } // create random number generator final SecureRandom random = new SecureRandom(); // create key generator final KeyPairGenerator keyGen; try { keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM, PROVIDER); keyGen.initialize(KEY_LENGTH, random); } catch (Exception ex) { LOGGER.error("Can't initialize key generator!"); LOGGER.error("> " + ex.getLocalizedMessage(), ex); System.exit(1); return; } // generate a key pair final KeyPair pair = keyGen.generateKeyPair(); // export private key final PrivateKey privateKey = pair.getPrivate(); final File privateKeyFile = new File(sslDir, "private.key"); FileUtils.deleteQuietly(privateKeyFile); console.writer() .println(I18N.tr("Writing private key to {0}.", "'" + privateKeyFile.getAbsolutePath() + "'")); try (PemWriter pemWriter = new PemWriter(new FileWriterWithEncoding(privateKeyFile, "UTF-8"))) { pemWriter.writeObject(new PemObject(ALIAS + " / Private Key", privateKey.getEncoded())); pemWriter.flush(); } catch (Exception ex) { LOGGER.error("Can't export private key!"); LOGGER.error("> " + ex.getLocalizedMessage(), ex); System.exit(1); return; } // export public key final PublicKey publicKey = pair.getPublic(); final File publicKeyFile = new File(sslDir, "public.key"); FileUtils.deleteQuietly(publicKeyFile); console.writer() .println(I18N.tr("Writing public key to {0}.", "'" + publicKeyFile.getAbsolutePath() + "'")); try (PemWriter pemWriter = new PemWriter(new FileWriterWithEncoding(publicKeyFile, "UTF-8"))) { pemWriter.writeObject(new PemObject(ALIAS + " / Public Key", publicKey.getEncoded())); pemWriter.flush(); } catch (Exception ex) { LOGGER.error("Can't export public key!"); LOGGER.error("> " + ex.getLocalizedMessage(), ex); System.exit(1); return; } // generate certificate final X509Certificate cert; try { Date startDate = new Date(); Date expiryDate = DateUtils.addYears(startDate, 10); X500Name subject = new X500Name("CN=" + commonName); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); BigInteger serial = BigInteger.valueOf(random.nextLong()).abs(); //X509v1CertificateBuilder builder = new X509v1CertificateBuilder( subject, serial, startDate, expiryDate, subject, publicKeyInfo ); //X509CertificateHolder holder = builder.build( createSigner( privateKey ) ); //cert = new JcaX509CertificateConverter().getCertificate( holder ); X509v3CertificateBuilder builder = new X509v3CertificateBuilder(subject, serial, startDate, expiryDate, subject, publicKeyInfo); X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils( new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1))); builder.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo)); X509CertificateHolder holder = builder.build(createSigner(privateKey)); cert = new JcaX509CertificateConverter().getCertificate(holder); // export certificate File f = new File(sslDir, "private.crt"); FileUtils.deleteQuietly(f); console.writer().println(I18N.tr("Writing certificate to {0}.", "'" + f.getAbsolutePath() + "'")); try (PemWriter pemWriter = new PemWriter(new FileWriterWithEncoding(f, "UTF-8"))) { pemWriter.writeObject(new PemObject(ALIAS + " / Certificate", cert.getEncoded())); pemWriter.flush(); } } catch (Exception ex) { LOGGER.error("Can't create certificate!"); LOGGER.error("> " + ex.getLocalizedMessage(), ex); System.exit(1); return; } // create keystore try { KeyStore store = KeyStore.getInstance("jks"); store.load(null, password); store.setKeyEntry(ALIAS, privateKey, password, new Certificate[] { cert }); File f = new File(sslDir, "keystore.jks"); FileUtils.deleteQuietly(f); console.writer().println(I18N.tr("Writing keystore to {0}.", "'" + f.getAbsolutePath() + "'")); try (OutputStream output = new FileOutputStream(f)) { store.store(output, password); output.flush(); } } catch (Exception ex) { LOGGER.error("Can't create keystore!"); LOGGER.error("> " + ex.getLocalizedMessage(), ex); System.exit(1); return; } console.writer().println(StringUtils.EMPTY); console.writer().println(line); console.writer().println(I18N.tr("SSL encryption was successfully prepared!")); console.writer().println(line); console.writer().println(StringUtils.EMPTY); console.writer().println(I18N.tr("Follow these steps in order to enable SSL encryption.")); console.writer().println(StringUtils.EMPTY); console.writer().println("(1) " + I18N.tr("Open the following configuration file with a text editor:")); console.writer().println(StringUtils.EMPTY); console.writer().println(new File(etcDir, "server.properties").getAbsolutePath()); console.writer().println(StringUtils.EMPTY); console.writer().println("(2) " + I18N.tr("Change the following values in the configuration file:")); console.writer().println(StringUtils.EMPTY); console.writer().println("server.tls=true"); //console.writer().println("system.javax.net.ssl.keyStore=./etc/ssl/keystore.jks"); console.writer().println("system.javax.net.ssl.keyStorePassword=" + String.valueOf(password)); console.writer().println(StringUtils.EMPTY); console.writer().println("(3) " + I18N.tr("Restart {0}.", ServerUtils.TITLE)); console.writer().println(StringUtils.EMPTY); console.writer().println(line); console.writer().println(StringUtils.EMPTY); console.writer().println(I18N.tr("Press ENTER to exit this application.")); try { console.readLine(); } catch (Exception ignored) { } }
From source file:org.openfact.common.util.CertificateUtils.java
License:Apache License
/** * Generates version 3 {@link X509Certificate}. * * @param keyPair the key pair/*w w w.j a v a 2 s.co m*/ * @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.openhab.io.jetty.certificate.internal.CertificateGenerator.java
License:Open Source License
/** * Generate a new certificate and store it in the given keystore. * * @param keystore// w w w .ja va 2 s .c o m * @throws CertificateException if the certificate generation has failed. * @throws KeyStoreException If save of the keystore has failed. */ private void generateCertificate(KeyStore keystore) throws CertificateException, KeyStoreException { try { long startTime = System.currentTimeMillis(); org.bouncycastle.jce.spec.ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE_NAME); ECField field = new ECFieldFp(ecSpec.getCurve().getField().getCharacteristic()); EllipticCurve curve = new EllipticCurve(field, ecSpec.getCurve().getA().toBigInteger(), ecSpec.getCurve().getB().toBigInteger()); ECPoint pointG = new ECPoint(ecSpec.getG().getXCoord().toBigInteger(), ecSpec.getG().getYCoord().toBigInteger()); ECParameterSpec spec = new ECParameterSpec(curve, pointG, ecSpec.getN(), ecSpec.getH().intValue()); KeyPairGenerator g = KeyPairGenerator.getInstance(KEY_PAIR_GENERATOR_TYPE); g.initialize(spec, new SecureRandom()); KeyPair keysPair = g.generateKeyPair(); ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(((ECPrivateKey) keysPair.getPrivate()).getS(), spec); ECPublicKeySpec ecPublicSpec = new ECPublicKeySpec(((ECPublicKey) keysPair.getPublic()).getW(), spec); KeyFactory kf = KeyFactory.getInstance(KEY_FACTORY_TYPE); PrivateKey privateKey = kf.generatePrivate(ecPrivSpec); PublicKey publicKey = kf.generatePublic(ecPublicSpec); logger.debug("Keys generated in {} ms.", (System.currentTimeMillis() - startTime)); X500Name issuerDN = new X500Name(X500_NAME); Integer randomNumber = new Random().nextInt(); BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); X500Name subjectDN = new X500Name(X500_NAME); byte[] publickeyb = publicKey.getEncoded(); ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb); SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore, notAfter, subjectDN, subPubKeyInfo); ContentSigner contentSigner = new JcaContentSignerBuilder(CONTENT_SIGNER_ALGORITHM) .build(keysPair.getPrivate()); X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner); Certificate certificate = java.security.cert.CertificateFactory.getInstance(CERTIFICATE_X509_TYPE) .generateCertificate(new ByteArrayInputStream( ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded()).array())); logger.debug("Total certificate generation time: {} ms.", (System.currentTimeMillis() - startTime)); keystore.setKeyEntry(KEYSTORE_ENTRY_ALIAS, privateKey, KEYSTORE_PASSWORD.toCharArray(), new java.security.cert.Certificate[] { certificate }); logger.debug("Save the keystore into {}.", keystoreFile.getAbsolutePath()); keystore.store(new FileOutputStream(keystoreFile), KEYSTORE_PASSWORD.toCharArray()); } catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException | OperatorCreationException | InvalidAlgorithmParameterException e) { throw new CertificateException("Failed to generate the new certificate.", e); } }
From source file:org.openremote.security.provider.BouncyCastleKeySigner.java
License:Open Source License
/** * Creates a BouncyCastle X.509 V3 certificate builder. The certificate is configured with * X.500 names given in the configuration for the issuer and subject and a given validity * period for the certificate. The certificate's serial number is generated as an unique * 40 character integer value, see {@link #generateUniqueSerial()} for details. * * @param config/*from w w w. ja v a 2 s . c o m*/ * configuration for the X.509 certificate builder * * @return BouncyCastle certificate builder instance */ private X509v3CertificateBuilder createCertificateBuilder(Configuration config) { X500Name issuerName = new X500Name(config.getIssuer().toX500Name()); X500Name subjectName = new X500Name(config.getSubject().toX500Name()); // Get configured certificate validity dates... Date notBefore = new Date(config.getValidityPeriod().getNotBeforeDate().getTime()); Date notAfter = new Date(config.getValidityPeriod().getNotAfterDate().getTime()); // BouncyCastle API to build a certificate with the public key, issuer and subject, // validity dates and a serial number... return new JcaX509v3CertificateBuilder(issuerName, new BigInteger(generateUniqueSerial()), notBefore, notAfter, subjectName, config.getPublicKey()); }
From source file:org.picketbox.keystore.util.CertificateUtil.java
License:Open Source License
/** * Create a X509 V1 {@link Certificate}//from w w w .j a v a 2s .com * * @param pair {@link KeyPair} * @param numberOfDays Number of days the certificate will be valid * @param DN The DN of the subject * @return * @throws CertificateException */ public Certificate createX509V1Certificate(KeyPair pair, int numberOfDays, String DN) throws CertificateException { try { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory .createKey(pair.getPrivate().getEncoded()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date endDate = new Date(System.currentTimeMillis() + numberOfDays * 24 * 60 * 60 * 1000); X500Name name = new X500Name(DN); BigInteger serialNum = createSerialNumber(); X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, serialNum, startDate, endDate, name, subPubKeyInfo); X509CertificateHolder certificateHolder = v1CertGen.build(sigGen); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder); } catch (CertificateException e1) { throw e1; } catch (Exception e) { throw new CertificateException(e); } }
From source file:org.picketbox.keystore.util.CertificateUtil.java
License:Open Source License
/** * Create a certificate signing request/*from w w w. jav a 2s .co m*/ * * @throws CertificateException */ public byte[] createCSR(String dn, KeyPair keyPair) throws CertificateException { X500Name name = new X500Name(dn); try { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory .createKey(keyPair.getPrivate().getEncoded()); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(name, subPubKeyInfo); PKCS10CertificationRequest csr = builder.build(sigGen); return csr.getEncoded(); } catch (Exception e) { throw new CertificateException(e); } }
From source file:org.picketlink.pki.internal.DefaultCertificateAuthority.java
License:Open Source License
@Override public CertificateType issue(IdentityType identityType) { CertificateType certificate;//from w ww . j a v a2 s.co m try { IdentityManager identityManager = getIdentityManager(); IdentityType storedIdentityType = identityManager.lookupIdentityById(IdentityType.class, identityType.getId()); KeyPair userKeyPair = this.keyAuthority.getKeyPair(storedIdentityType); String commonName = null; if (User.class.isInstance(identityType)) { commonName = ((User) identityType).getLoginName(); } X500Name subjectDN = new X500Name("CN=" + commonName + "," + getConfiguration().getBaseDN()); X509Certificate x509Certificate = X509Util.generateV3Certificate(getCertificate().getObject(), getPartitionKeyPair(), subjectDN, userKeyPair, getConfiguration()); certificate = new CertificateType(storedIdentityType, x509Certificate, getConfiguration()); identityManager.add(certificate); } catch (Exception e) { throw new RuntimeException("Could not issue certificate.", e); } return certificate; }
From source file:org.picketlink.pki.internal.DefaultCertificateAuthority.java
License:Open Source License
private static X509CRLHolder createRevocationList(KeyPair partitionKeys, X509Certificate certificate, CertificateAuthorityConfig config) { Date date = new Date(); X509v2CRLBuilder builder = new X509v2CRLBuilder(new X500Name(certificate.getSubjectDN().getName()), date); Date nextUpdate = new Date(date.getTime() + 30 * 24 * 60 * 60 * 1000); // Every 30 days builder.setNextUpdate(nextUpdate);//from ww w. j a v a2 s . c o m ContentSigner contentSigner = createSigner(partitionKeys.getPrivate(), config); return builder.build(contentSigner); }