List of usage examples for org.bouncycastle.asn1.x509 GeneralName GeneralName
public GeneralName(int tag, String name)
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
License:Open Source License
protected CertificationRequest generateCSR(KeyPair keyPair, UserInfo userInfo) throws CertException { CertificationRequest csr;/*from www . ja v a 2s . co m*/ GeneralNames subjectAltName = new GeneralNames( new GeneralName(GeneralName.rfc822Name, userInfo.getUserFields().get(CNField.Email))); Vector<DERObjectIdentifier> objectIdentifiers = new Vector<DERObjectIdentifier>(); Vector<X509Extension> extensionValues = new Vector<X509Extension>(); objectIdentifiers.add(X509Extensions.SubjectAlternativeName); extensionValues.add(new X509Extension(false, new DEROctetString(subjectAltName))); X509Extensions extensions = new X509Extensions(objectIdentifiers, extensionValues); Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(extensions)); try { csr = new PKCS10CertificationRequest(CERT_SIGNATURE_ALGORITHM, userInfo.getX500Principal(), keyPair.getPublic(), new DERSet(attribute), keyPair.getPrivate()); } catch (InvalidKeyException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } catch (NoSuchProviderException e) { throw new CertException(e); } catch (java.security.SignatureException e) { throw new CertException(e); } catch (Exception e) { throw new CertException(e); } return csr; }
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. java 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.utils.BouncyCastleUtils.java
License:Open Source License
/** * Generates a new certificate using the Bouncy Castle implementation. * <p>/*from ww w . j av a 2 s . c om*/ * The method is used from * {@link CertificateUtils#createApplicationInstanceCertificate(String, String, String, int, String...)} * and * {@link CertificateUtils#renewApplicationInstanceCertificate(String, String, String, int, org.opcfoundation.ua.transport.security.KeyPair, String...)} * * @param domainName * the X500 domain name for the certificate * @param publicKey * the public key of the cert * @param privateKey * the private key of the cert * @param issuerKeys * the certificate and private key of the issuer * @param from * validity start time * @param to * validity end time * @param serialNumber * a unique serial number for the certificate * @param applicationUri * the OPC UA ApplicationUri of the application - added to * SubjectAlternativeName * @param hostNames * the additional host names to 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.opcfoundation.ua.utils.CertificateUtils.java
License:Open Source License
/** * /*w w w . j a v a 2s. com*/ * @param commonName - Common Name (CN) for generated certificate * @param organisation - Organisation (O) for generated certificate * @param applicationUri - Alternative name (one of x509 extensiontype) for generated certificate. Must not be null * @param validityTime - the time that the certificate is valid (in days) * @return * @throws IOException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws CertificateEncodingException * @throws InvalidKeyException * @throws IllegalStateException * @throws NoSuchProviderException * @throws SignatureException * @throws CertificateParsingException */ public static org.opcfoundation.ua.transport.security.KeyPair createApplicationInstanceCertificate( String commonName, String organisation, String applicationUri, int validityTime) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, SignatureException, CertificateParsingException { if (applicationUri == null) throw new NullPointerException("applicationUri must not be null"); //Add provider for generator Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //Initializes generator SecureRandom srForCert = new SecureRandom(); RSAKeyPairGenerator genForCert = new RSAKeyPairGenerator(); //Used for generating prime Random r = new Random(System.currentTimeMillis()); int random = -1; while (random < 3) { random = r.nextInt(32); } //calculate(generate) possible value for public modulus //used method is "monte carlo -algorithm", so we calculate it as long as it generates value. BigInteger value = null; while (value == null) { value = BigInteger.probablePrime(random, new SecureRandom()); } //Generate (Java) keypair genForCert.init(new RSAKeyGenerationParameters(value, srForCert, KEY_SIZE, 80)); AsymmetricCipherKeyPair keypairForCert = genForCert.generateKeyPair(); //Extract the keys from parameters logger.debug("Generated keypair, extracting components and creating public structure for certificate"); RSAKeyParameters clientPublicKey = (RSAKeyParameters) keypairForCert.getPublic(); RSAPrivateCrtKeyParameters clientPrivateKey = (RSAPrivateCrtKeyParameters) keypairForCert.getPrivate(); // used to get proper encoding for the certificate RSAPublicKeyStructure clientPkStruct = new RSAPublicKeyStructure(clientPublicKey.getModulus(), clientPublicKey.getExponent()); logger.debug("New public key is '" + makeHexString(clientPkStruct.getEncoded()) + ", exponent=" + clientPublicKey.getExponent() + ", modulus=" + clientPublicKey.getModulus()); // JCE format needed for the certificate - because getEncoded() is necessary... PublicKey certPubKey = KeyFactory.getInstance("RSA") .generatePublic(new RSAPublicKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent())); // and this one for the KeyStore PrivateKey certPrivKey = KeyFactory.getInstance("RSA").generatePrivate( new RSAPrivateCrtKeySpec(clientPublicKey.getModulus(), clientPublicKey.getExponent(), clientPrivateKey.getExponent(), clientPrivateKey.getP(), clientPrivateKey.getQ(), clientPrivateKey.getDP(), clientPrivateKey.getDQ(), clientPrivateKey.getQInv())); //The data for the certificate.. Calendar expiryTime = Calendar.getInstance(); expiryTime.add(Calendar.DAY_OF_YEAR, validityTime); X509Name certificateX509Name = new X509Name( "CN=" + commonName + ", O=" + organisation + ", C=" + System.getProperty("user.country")); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); certGen.setSerialNumber(serial); //Issuer and subject must be the same (because this is self signed) certGen.setIssuerDN(certificateX509Name); certGen.setSubjectDN(certificateX509Name); //expiry & start time for this certificate certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000 * 60 * 60)); //take 60 minutes (1000 ms * 60 s * 60) away from system clock (in case there is some lag in system clocks) certGen.setNotAfter(expiryTime.getTime()); certGen.setPublicKey(certPubKey); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); //******* X.509 V3 Extensions ***************** SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(certPubKey.getEncoded())).readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(apki); /*certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true, new DEROctetString(ski//new SubjectKeyIdentifier Structure(apki/*certPubKey))); */ certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); certGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, /*new DEROctetString(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign ))*/new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); BasicConstraints b = new BasicConstraints(false); Vector<KeyPurposeId> extendedKeyUsages = new Vector<KeyPurposeId>(); extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, /*new DEROctetString(new ExtendedKeyUsage(extendedKeyUsages))*/new ExtendedKeyUsage( extendedKeyUsages)); // create the extension value ASN1EncodableVector names = new ASN1EncodableVector(); names.add(new GeneralName(GeneralName.uniformResourceIdentifier, applicationUri)); // GeneralName dnsName = new GeneralName(GeneralName.dNSName, applicationUri); // names.add(dnsName); final GeneralNames subjectAltNames = new GeneralNames(new DERSequence(names)); certGen.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames); // AuthorityKeyIdentifier final GeneralNames certificateIssuer = new GeneralNames(new GeneralName(certificateX509Name)); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki, certificateIssuer, serial); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); //***** generate certificate ***********/ X509Certificate cert = certGen.generate(certPrivKey, "BC"); //Encapsulate Certificate and private key to CertificateKeyPair Cert certificate = new Cert(cert); org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey( (RSAPrivateKey) certPrivKey); return new org.opcfoundation.ua.transport.security.KeyPair(certificate, UAkey); }
From source file:org.openqa.selenium.security.CertificateGenerator.java
License:Apache License
public KeyAndCert generateCertificate(String hostname, String certificateRevocationList) { X500Principal x500issuer = caCert.getCertificate().getIssuerX500Principal(); String subject = String.format("CN=%s, OU=Test, O=CyberVillainsCA, L=Seattle, S=Washington, C=US", hostname);//from www . j ava 2 s .c om X500Principal x500subject = new X500Principal(subject); Date begin = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)); Date end = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)); KeyPair keypair = pairGenerator.generateKeyPair(); try { SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(keypair.getPublic().getEncoded())) .readObject()); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(x500issuer, BigInteger.valueOf(serialSeed.getAndIncrement()), begin, end, x500subject, keypair.getPublic()); builder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false)); builder.addExtension(X509Extension.subjectKeyIdentifier, false, info); AuthorityKeyIdentifier caIdentifier = new JcaX509ExtensionUtils() .createAuthorityKeyIdentifier(caCert.getCertificate()); builder.addExtension(X509Extension.authorityKeyIdentifier, false, caIdentifier); DERSequence typicalSSLServerExtendedKeyUsages = new DERSequence(new ASN1Encodable[] { new DERObjectIdentifier(SERVER_AUTH), new DERObjectIdentifier(CLIENT_AUTH), }); builder.addExtension(X509Extension.extendedKeyUsage, false, typicalSSLServerExtendedKeyUsages); if (certificateRevocationList != null) { /* Safari on Windows requires a CRL and validates it */ DistributionPoint crl = new DistributionPoint( new DistributionPointName(DistributionPointName.FULL_NAME, new GeneralName(GeneralName.uniformResourceIdentifier, certificateRevocationList)), null, null); builder.addExtension(X509Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[] { crl })); } ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE) .build(caCert.getPrivateKey()); X509CertificateHolder holder = builder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE) .getCertificate(holder); return new KeyAndCert(keypair.getPrivate(), cert); } catch (GeneralSecurityException e) { throw Throwables.propagate(e); } catch (IOException e) { throw Throwables.propagate(e); } catch (OperatorCreationException e) { throw Throwables.propagate(e); } }
From source file:org.opensaml.xml.security.x509.tls.MockX509Certificate.java
License:Open Source License
/** * Constructor.//from w w w .j a v a 2 s. 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); } } }
From source file:org.pidome.server.services.provider.CertGen.java
License:Apache License
private void gen() throws CertGenException { try {/* www. j av a 2 s.c o m*/ File store = new File(SystemConfig.getProperty("system", "server.keystore")); store.getParentFile().mkdirs(); if (store.exists()) { store.delete(); } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setSubjectDN(new X500Principal("CN=" + curHost)); certGen.setIssuerDN(new X500Principal("CN=PiDome Server at " + curHost)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); certGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); certGen.setPublicKey(KPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); GeneralName altName = new GeneralName(GeneralName.iPAddress, Network.getIpAddressProperty().get().getHostAddress()); GeneralNames subjectAltName = new GeneralNames(altName); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName); X509Certificate cert = certGen.generate(KPair.getPrivate(), "BC"); /// Always, but always create a new keystore. a new keystore pass has is always created. privateKS = KeyStore.getInstance("JKS"); privateKS.load(null, null); String storePass = MessageDigest.getInstance("MD5").toString(); privateKS.setKeyEntry("PiDome.Default", KPair.getPrivate(), storePass.toCharArray(), new java.security.cert.Certificate[] { cert }); store.createNewFile(); privateKS.store(new FileOutputStream(store), storePass.toCharArray()); System.setProperty("javax.net.ssl.keyStore", SystemConfig.getProperty("system", "server.keystore")); System.setProperty("javax.net.ssl.keyStorePassword", storePass); available = true; LOG.info("Certificate(s) generated."); } catch (CertificateEncodingException ex) { throw new CertGenException("Could not encode certificate, can not continue: " + ex.getMessage()); } catch (IllegalStateException ex) { throw new CertGenException("Illegal state, can not continue: " + ex.getMessage()); } catch (NoSuchProviderException ex) { throw new CertGenException("No known provider, can not continue: " + ex.getMessage()); } catch (NoSuchAlgorithmException ex) { throw new CertGenException("No such algorithm, can not continue: " + ex.getMessage()); } catch (SignatureException ex) { throw new CertGenException("Signature problem, can not continue: " + ex.getMessage()); } catch (InvalidKeyException ex) { throw new CertGenException("Invalid key used, can not continue: " + ex.getMessage()); } catch (KeyStoreException ex) { throw new CertGenException("KeyStore problem, can not continue: " + ex.getMessage()); } catch (IOException ex) { throw new CertGenException("KeyStore can not be opened, can not continue: " + ex.getMessage()); } catch (CertificateException ex) { throw new CertGenException("KeyStore certificate problem, can not continue: " + ex.getMessage()); } catch (ConfigPropertiesException ex) { throw new CertGenException( "KeyStore location configuration problem, can not continue: " + ex.getMessage()); } }
From source file:org.qipki.ca.tests.http.QiPkiHttpCaTest.java
License:Open Source License
private void testCA() throws InterruptedException, IOException, JSONException, GeneralSecurityException { // Get CA list HttpGet get = new HttpGet(caApi.caListUri().get()); addAcceptJsonHeader(get);/*from w w w. j av a2 s. co m*/ String jsonCaList = httpClient.execute(get, strResponseHandler); LOGGER.debug("CAs List: {}", new JSONObject(jsonCaList).toString(2)); RestListValue caList = valueBuilderFactory.newValueFromJSON(RestListValue.class, jsonCaList); CAValue firstCa = (CAValue) caList.items().get().get(0); // Get first CA as Value get = new HttpGet(firstCa.uri().get()); addAcceptJsonHeader(get); String caJson = httpClient.execute(get, strResponseHandler); CAValue ca = valueBuilderFactory.newValueFromJSON(CAValue.class, caJson); LOGGER.debug("First CA JSON:\n{}", ca.toJSON()); // Get first CA CRL get = new HttpGet(ca.crlUri().get()); String crl = httpClient.execute(get, strResponseHandler); LOGGER.debug("First CA CRL:\n{}", crl); X509CRL x509CRL = cryptio.readCRLPEM(new StringReader(crl)); // Create a new CryptoStore HttpPost post = new HttpPost(caApi.cryptoStoreListUri().get()); addAcceptJsonHeader(post); CryptoStoreFactoryParamsValue csParams = paramsFactory.createCryptoStoreFactoryParams(testCryptoStoreName, KeyStoreType.JKS, "changeit".toCharArray()); post.setEntity(new StringEntity(csParams.toJSON())); String csJson = httpClient.execute(post, strResponseHandler); CryptoStoreValue cryptoStore = valueBuilderFactory.newValueFromJSON(CryptoStoreValue.class, csJson); // Create a new CA post = new HttpPost(caApi.caListUri().get()); addAcceptJsonHeader(post); KeyPairSpecValue keyPairSpec = cryptoValuesFactory.createKeySpec(AsymetricAlgorithm.RSA, 512); CAFactoryParamsValue caParams = paramsFactory.createCAFactoryParams(cryptoStore.uri().get(), testCaName, 1, "CN=" + testCaName, keyPairSpec, null); post.setEntity(new StringEntity(caParams.toJSON())); caJson = httpClient.execute(post, strResponseHandler); ca = valueBuilderFactory.newValueFromJSON(CAValue.class, caJson); // Create a new X509Profile post = new HttpPost(caApi.x509ProfileListUri().get()); addAcceptJsonHeader(post); X509ProfileFactoryParamsValue profileParams = paramsFactory.createX509ProfileFactoryParams("SSLClient", 1, "A simple SSLClient x509 profile for unit tests", x509ExtValuesFactory.buildKeyUsagesValue(true, EnumSet.of(KeyUsage.keyEncipherment, KeyUsage.digitalSignature)), x509ExtValuesFactory.buildExtendedKeyUsagesValue(false, EnumSet.of(ExtendedKeyUsage.clientAuth)), x509ExtValuesFactory.buildNetscapeCertTypesValue(false, EnumSet.of(NetscapeCertType.sslClient)), x509ExtValuesFactory.buildBasicConstraintsValue(true, false, 0), null); post.setEntity(new StringEntity(profileParams.toJSON())); String sslClientProfileJson = httpClient.execute(post, strResponseHandler); X509ProfileValue sslClientProfile = valueBuilderFactory.newValueFromJSON(X509ProfileValue.class, sslClientProfileJson); // Add profile to CA post = new HttpPost(ca.uri().get()); addAcceptJsonHeader(post); ValueBuilder<CAValue> caValueBuilder = valueBuilderFactory.newValueBuilder(CAValue.class).withPrototype(ca); // Needed as Values are immutables ca = caValueBuilder.prototype(); ca.allowedX509Profiles().get().add( paramsFactory.createX509ProfileAssignment(sslClientProfile.uri().get(), KeyEscrowPolicy.allowed)); ca = caValueBuilder.newInstance(); post.setEntity(new StringEntity(ca.toJSON())); caJson = httpClient.execute(post, strResponseHandler); ca = valueBuilderFactory.newValueFromJSON(CAValue.class, caJson); // Request certificate on X509Factory with a PKCS#10 request using the first CA KeyPair keyPair = asymGenerator .generateKeyPair(new AsymetricGeneratorParameters(AsymetricAlgorithm.RSA, 512)); PKCS10CertificationRequest pkcs10 = x509Generator.generatePKCS10(new DistinguishedName("CN=qipki"), keyPair, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "qipki@codeartisans.org"))); String pkcs10PEM = cryptio.asPEM(pkcs10).toString(); LOGGER.debug("Will request a new X509 with the following PKCS#10: " + pkcs10PEM); X509FactoryParamsValue x509FactoryParams = paramsFactory.createX509FactoryParams(ca.uri().get(), sslClientProfile.uri().get(), pkcs10PEM); post = new HttpPost(caApi.x509ListUri().get()); addAcceptJsonHeader(post); post.setEntity(new StringEntity(x509FactoryParams.toJSON())); String jsonX509 = httpClient.execute(post, strResponseHandler); X509Value newX509 = valueBuilderFactory.newValueFromJSON(X509Value.class, jsonX509); LOGGER.debug("New X509 created using /api/x509/factory after POST/302/REDIRECT: {}", newX509.toJSON()); // Get detailled info about new X509 get = new HttpGet(newX509.detailUri().get()); addAcceptJsonHeader(get); String jsonX509Detail = httpClient.execute(get, strResponseHandler); LOGGER.debug("New X509 detail: {}", new JSONObject(jsonX509Detail).toString(2)); X509DetailValue newX509Detail = valueBuilderFactory.newValueFromJSON(X509DetailValue.class, jsonX509Detail); assertTrue(newX509Detail.keysExtensions().get().extendedKeyUsages().get().extendedKeyUsages().get() .contains(ExtendedKeyUsage.clientAuth)); assertTrue(newX509Detail.keysExtensions().get().netscapeCertTypes().get().netscapeCertTypes().get() .contains(NetscapeCertType.sslClient)); // Get X509 list get = new HttpGet(caApi.x509ListUri().get()); addAcceptJsonHeader(get); String jsonX509List = httpClient.execute(get, strResponseHandler); LOGGER.debug("X509s List: {}", new JSONObject(jsonX509List).toString(2)); RestListValue x509List = valueBuilderFactory.newValueFromJSON(RestListValue.class, jsonX509List); X509Value firstX509 = (X509Value) x509List.items().get().get(0); // Get first X509 get = new HttpGet(firstX509.uri().get()); addAcceptJsonHeader(get); jsonX509 = httpClient.execute(get, strResponseHandler); LOGGER.debug("First X509: {}", new JSONObject(jsonX509).toString(2)); firstX509 = valueBuilderFactory.newValueFromJSON(X509Value.class, jsonX509); // Revoke first X509 X509RevocationParamsValue x509RevocationParams = paramsFactory .createX509RevocationParams(RevocationReason.cessationOfOperation); post = new HttpPost(firstX509.revocationUri().get()); addAcceptJsonHeader(post); post.setEntity(new StringEntity(x509RevocationParams.toJSON())); String jsonRevocation = httpClient.execute(post, strResponseHandler); LOGGER.debug(jsonRevocation); // Get KeyPair list get = new HttpGet(caApi.escrowedKeyPairListUri().get()); addAcceptJsonHeader(get); String jsonKeyPairList = httpClient.execute(get, strResponseHandler); LOGGER.debug("EscrowedKeyPair List: {}", new JSONObject(jsonKeyPairList).toString(2)); // Create KeyPair EscrowedKeyPairFactoryParamsValue escrowParams = paramsFactory .createEscrowedKeyPairFactoryParams(AsymetricAlgorithm.RSA, 512); post = new HttpPost(caApi.escrowedKeyPairListUri().get()); addAcceptJsonHeader(post); post.setEntity(new StringEntity(escrowParams.toJSON())); String jsonEscrowed = httpClient.execute(post, strResponseHandler); LOGGER.debug("EscrowedKeyPair : {}", new JSONObject(jsonEscrowed).toString(2)); EscrowedKeyPairValue ekp = valueBuilderFactory.newValueFromJSON(EscrowedKeyPairValue.class, jsonEscrowed); // Recover KeyPair get = new HttpGet(ekp.recoveryUri().get()); addAcceptJsonHeader(get); String kpPem = httpClient.execute(get, strResponseHandler); LOGGER.debug("EscrowedKeyPair PEM: {}", kpPem); KeyPair keypair = cryptio.readKeyPairPEM(new StringReader(kpPem)); // Issue X509Certificate using an escrowed keypair String dn = "CN=qipki-escrowed"; LOGGER.debug("Will request a new X509 with the following DN: " + dn); x509FactoryParams = paramsFactory.createX509FactoryParams(ca.uri().get(), sslClientProfile.uri().get(), ekp.uri().get(), dn); post = new HttpPost(caApi.x509ListUri().get()); addAcceptJsonHeader(post); post.setEntity(new StringEntity(x509FactoryParams.toJSON())); jsonX509 = httpClient.execute(post, strResponseHandler); newX509 = valueBuilderFactory.newValueFromJSON(X509Value.class, jsonX509); LOGGER.debug("New X509 created using /api/x509/factory and an escrowed keypair after POST/302/REDIRECT: {}", newX509.toJSON()); // Getting new X509 PEM get = new HttpGet(newX509.pemUri().get()); String x509pem = httpClient.execute(get, strResponseHandler); LOGGER.debug("X509 created from escrowed keypair PEM: {}", x509pem); X509Certificate x509Certificate = cryptio.readX509PEM(new StringReader(x509pem)); // Getting EscrowedKeyPair from X509Certificate get = new HttpGet(newX509.recoveryUri().get()); kpPem = httpClient.execute(get, strResponseHandler); LOGGER.debug("EscrowedKeyPair PEM: {}", kpPem); keypair = cryptio.readKeyPairPEM(new StringReader(kpPem)); // Create local PKCS#12 keystore with keypair, certificate and full certchain char[] password = "changeit".toCharArray(); KeyStore ks = KeyStore.getInstance(KeyStoreType.PKCS12.typeString(), BouncyCastleProvider.PROVIDER_NAME); ks.load(null, password); ks.setEntry("wow", new KeyStore.PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] { x509Certificate }), new KeyStore.PasswordProtection(password)); String base64encodedp12 = cryptio.base64Encode(ks, password); System.out.println(base64encodedp12); // Exporting CA in a PKCS#12 keystore get = new HttpGet(ca.exportUri().get() + "?password=changeit"); byte[] responseBytes = httpClient.execute(get, bytesResponseHandler); ks = KeyStore.getInstance(KeyStoreType.PKCS12.typeString(), BouncyCastleProvider.PROVIDER_NAME); ks.load(new ByteArrayInputStream(responseBytes), password); base64encodedp12 = cryptio.base64Encode(ks, password); System.out.println(base64encodedp12); // Exporting CA in a JKS keystore get = new HttpGet(ca.exportUri().get() + "?password=changeit&kstype=jks"); responseBytes = httpClient.execute(get, bytesResponseHandler); ks = KeyStore.getInstance(KeyStoreType.JKS.typeString()); ks.load(new ByteArrayInputStream(responseBytes), password); base64encodedp12 = cryptio.base64Encode(ks, password); System.out.println(base64encodedp12); }
From source file:org.shredzone.acme4j.util.CertificateUtils.java
License:Apache License
/** * Creates a self-signed {@link X509Certificate} that can be used for * {@link org.shredzone.acme4j.challenge.TlsSni01Challenge}. The certificate is valid * for 7 days./*from w w w. j a va 2 s.c o m*/ * * @param keypair * A domain {@link KeyPair} to be used for the challenge * @param subject * Subject to create a certificate for * @return Created certificate * @deprecated Will be removed when * {@link org.shredzone.acme4j.challenge.TlsSni01Challenge} is removed */ @Deprecated public static X509Certificate createTlsSniCertificate(KeyPair keypair, String subject) throws IOException { final long now = System.currentTimeMillis(); final long validSpanMs = 7 * 24 * 60 * 60 * 1000L; final String signatureAlg = "SHA256withRSA"; try { X500Name issuer = new X500Name("CN=acme.invalid"); BigInteger serial = BigInteger.valueOf(now); Date notBefore = new Date(now); Date notAfter = new Date(now + validSpanMs); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, keypair.getPublic()); GeneralName[] gns = new GeneralName[1]; gns[0] = new GeneralName(GeneralName.dNSName, subject); certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns)); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlg); byte[] cert = certBuilder.build(signerBuilder.build(keypair.getPrivate())).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert)); } catch (CertificateException | OperatorCreationException ex) { throw new IOException(ex); } }
From source file:org.shredzone.acme4j.util.CertificateUtils.java
License:Apache License
/** * Creates a self-signed {@link X509Certificate} that can be used for * {@link TlsSni02Challenge}. The certificate is valid for 7 days. * * @param keypair//from w ww .j a v a2 s. c o m * A domain {@link KeyPair} to be used for the challenge * @param sanA * SAN-A to be used in the certificate * @param sanB * SAN-B to be used in the certificate * @return Created certificate */ public static X509Certificate createTlsSni02Certificate(KeyPair keypair, String sanA, String sanB) throws IOException { final long now = System.currentTimeMillis(); final long validSpanMs = 7 * 24 * 60 * 60 * 1000L; final String signatureAlg = "SHA256withRSA"; try { X500Name issuer = new X500Name("CN=acme.invalid"); BigInteger serial = BigInteger.valueOf(now); Date notBefore = new Date(now); Date notAfter = new Date(now + validSpanMs); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, keypair.getPublic()); GeneralName[] gns = new GeneralName[2]; gns[0] = new GeneralName(GeneralName.dNSName, sanA); gns[1] = new GeneralName(GeneralName.dNSName, sanB); certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns)); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlg); byte[] cert = certBuilder.build(signerBuilder.build(keypair.getPrivate())).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert)); } catch (CertificateException | OperatorCreationException ex) { throw new IOException(ex); } }