List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator generate
public X509Certificate generate(PrivateKey key, String provider) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
From source file:org.ebayopensource.fido.uaf.crypto.X509.java
License:Apache License
public static X509Certificate generateV3Cert(KeyPair pair) { X509Certificate cert = null;/*w w w . ja v a 2 s. c om*/ try { X509V3CertificateGenerator gen = new X509V3CertificateGenerator(); gen.setPublicKey(pair.getPublic()); gen.setSerialNumber(new BigInteger(Long.toString(System.currentTimeMillis() / 1000))); Hashtable<ASN1ObjectIdentifier, String> attrs = new Hashtable<ASN1ObjectIdentifier, String>(); Vector<ASN1ObjectIdentifier> vOrder = new Vector<ASN1ObjectIdentifier>(); attrs.put(X509Principal.E, "npesic@ebay.com"); vOrder.add(0, X509Principal.E); attrs.put(X509Principal.CN, "eBay, Inc"); vOrder.add(0, X509Principal.CN); attrs.put(X509Principal.OU, "TNS"); vOrder.add(0, X509Principal.OU); attrs.put(X509Principal.O, "eBay, Inc."); vOrder.add(0, X509Principal.O); attrs.put(X509Principal.L, "San Jose"); vOrder.add(0, X509Principal.L); attrs.put(X509Principal.ST, "CA"); vOrder.add(0, X509Principal.ST); attrs.put(X509Principal.C, "US"); vOrder.add(0, X509Principal.C); gen.setIssuerDN(new X509Principal(vOrder, attrs)); gen.setSubjectDN(new X509Principal(vOrder, attrs)); gen.setNotBefore(new Date(System.currentTimeMillis())); gen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); gen.setSignatureAlgorithm("SHA1WithECDSA"); cert = gen.generate(pair.getPrivate(), "BC"); } catch (Exception e) { System.out.println("Unable to generate a X509Certificate." + e); } return cert; }
From source file:org.ejbca.core.model.ca.caadmin.X509CA.java
License:Open Source License
/** * sequence is ignored by X509CA/* w ww . ja v a2 s . co m*/ */ public Certificate generateCertificate(UserDataVO subject, X509Name requestX509Name, PublicKey publicKey, int keyusage, Date notBefore, Date notAfter, CertificateProfile certProfile, X509Extensions extensions, String sequence, PublicKey caPublicKey, PrivateKey caPrivateKey, String provider) throws Exception { // We must only allow signing to take place if the CA itself if on line, even if the token is on-line. // We have to allow expired as well though, so we can renew expired CAs if ((getStatus() != SecConst.CA_ACTIVE) && ((getStatus() != SecConst.CA_EXPIRED))) { String msg = intres.getLocalizedMessage("error.caoffline", getName(), getStatus()); if (log.isDebugEnabled()) { log.debug(msg); // This is something we handle so no need to log with higher priority } throw new CAOfflineException(msg); } final String sigAlg; if (certProfile.getSignatureAlgorithm() == null) { sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm(); } else { sigAlg = certProfile.getSignatureAlgorithm(); } final X509Certificate cacert = (X509Certificate) getCACertificate(); String dn = subject.getCertificateDN(); // Check if this is a root CA we are creating final boolean isRootCA = certProfile.getType() == CertificateProfile.TYPE_ROOTCA; // Get certificate validity time notBefore and notAfter final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert, isRootCA); final X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); { // Serialnumber is either random bits, where random generator is initialized by the serno generator. // Or a custom serial number defined in the end entity object final ExtendedInformation ei = subject.getExtendedinformation(); BigInteger customSN = ei != null ? ei.certificateSerialNumber() : null; if (customSN != null) { if (!certProfile.getAllowCertSerialNumberOverride()) { final String msg = intres.getLocalizedMessage( "signsession.certprof_not_allowing_cert_sn_override_using_normal", customSN.toString(16)); log.info(msg); customSN = null; } else { if (log.isDebugEnabled()) { log.debug("Using custom serial number: " + customSN.toString(16)); } } } final BigInteger serno = customSN != null ? customSN : SernoGenerator.instance().getSerno(); certgen.setSerialNumber(serno); } certgen.setNotBefore(val.getNotBefore()); certgen.setNotAfter(val.getNotAfter()); certgen.setSignatureAlgorithm(sigAlg); // Make DNs if (certProfile.getUseSubjectDNSubSet()) { dn = certProfile.createSubjectDNSubSet(dn); } if (certProfile.getUseCNPostfix()) { dn = CertTools.insertCNPostfix(dn, certProfile.getCNPostfix()); } X509NameEntryConverter converter = null; if (getUsePrintableStringSubjectDN()) { converter = new PrintableStringEntryConverter(); } else { converter = new X509DefaultEntryConverter(); } // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN boolean ldapdnorder = true; if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) { ldapdnorder = false; } X509Name subjectDNName = CertTools.stringToBcX509Name(dn, converter, ldapdnorder); if (certProfile.getAllowDNOverride() && (requestX509Name != null)) { subjectDNName = requestX509Name; if (log.isDebugEnabled()) { log.debug("Using X509Name from request instead of user's registered."); } } if (log.isDebugEnabled()) { log.debug("Using subjectDN: " + subjectDNName.toString()); } certgen.setSubjectDN(subjectDNName); // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN // which many applications do not like. if (isRootCA) { // This will be an initial root CA, since no CA-certificate exists // Or it is a root CA, since the cert is self signed. If it is a root CA we want to use the same encoding for subject and issuer, // it might have changed over the years. if (log.isDebugEnabled()) { log.debug("Using subject DN also as issuer DN, because it is a root CA"); } certgen.setIssuerDN(subjectDNName); } else { javax.security.auth.x500.X500Principal issuerPrincipal = cacert.getSubjectX500Principal(); if (log.isDebugEnabled()) { log.debug("Using issuer DN directly from the CA certificate: " + issuerPrincipal.getName()); } certgen.setIssuerDN(issuerPrincipal); } certgen.setPublicKey(publicKey); // // X509 Certificate Extensions // // Extensions we will add to the certificate, later when we have filled the structure with // everything we want. X509ExtensionsGenerator extgen = new X509ExtensionsGenerator(); // First we check if there is general extension override, and add all extensions from // the request in that case if (certProfile.getAllowExtensionOverride() && extensions != null) { Enumeration en = extensions.oids(); while (en != null && en.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement(); X509Extension ext = extensions.getExtension(oid); if (log.isDebugEnabled()) { log.debug("Overriding extension with oid: " + oid); } extgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } // Second we see if there is Key usage override X509Extensions overridenexts = extgen.generate(); if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) { if (log.isDebugEnabled()) { log.debug("AllowKeyUsageOverride=true. Using KeyUsage from parameter: " + keyusage); } if ((certProfile.getUseKeyUsage() == true) && (keyusage >= 0)) { X509KeyUsage ku = new X509KeyUsage(keyusage); // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(X509Extensions.KeyUsage) == null) { extgen.addExtension(X509Extensions.KeyUsage, certProfile.getKeyUsageCritical(), ku); } else { if (log.isDebugEnabled()) { log.debug( "KeyUsage was already overridden by an extension, not using KeyUsage from parameter."); } } } } // Third, check for standard Certificate Extensions that should be added. // Standard certificate extensions are defined in CertificateProfile and CertificateExtensionFactory // and implemented in package org.ejbca.core.model.certextensions.standard CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance(); List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions(); Iterator<String> certStdExtIter = usedStdCertExt.iterator(); overridenexts = extgen.generate(); while (certStdExtIter.hasNext()) { String oid = certStdExtIter.next(); // We don't want to try to add standard extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new DERObjectIdentifier(oid)) == null) { CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile); if (certExt != null) { byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey); if (value != null) { extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + oid + " has been overridden, standard extension will not be added."); } } } // Fourth, check for custom Certificate Extensions that should be added. // Custom certificate extensions is defined in certextensions.properties fact = CertificateExtensionFactory.getInstance(); List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions(); Iterator<Integer> certExtIter = usedCertExt.iterator(); while (certExtIter.hasNext()) { Integer id = certExtIter.next(); CertificateExtension certExt = fact.getCertificateExtensions(id); if (certExt != null) { // We don't want to try to add custom extensions with the same oid if we have already added them // from the request, if AllowExtensionOverride is enabled. // Two extensions with the same oid is not allowed in the standard. if (overridenexts.getExtension(new DERObjectIdentifier(certExt.getOID())) == null) { byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey); if (value != null) { extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(), value); } } else { if (log.isDebugEnabled()) { log.debug("Extension with oid " + certExt.getOID() + " has been overridden, custom extension will not be added."); } } } } // Finally add extensions to certificate generator X509Extensions exts = extgen.generate(); Enumeration en = exts.oids(); while (en.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement(); X509Extension ext = exts.getExtension(oid); certgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } // // End of extensions // X509Certificate cert; if (log.isTraceEnabled()) { log.trace(">certgen.generate"); } cert = certgen.generate(caPrivateKey, provider); if (log.isTraceEnabled()) { log.trace("<certgen.generate"); } // Verify using the CA certificate before returning // If we can not verify the issued certificate using the CA certificate we don't want to issue this cert // because something is wrong... PublicKey verifyKey; // We must use the configured public key if this is a rootCA, because then we can renew our own certificate, after changing // the keys. In this case the _new_ key will not match the current CA certificate. if ((cacert != null) && (!isRootCA)) { verifyKey = cacert.getPublicKey(); } else { verifyKey = caPublicKey; } cert.verify(verifyKey); // If we have a CA-certificate, verify that we have all path verification stuff correct if (cacert != null) { byte[] aki = CertTools.getAuthorityKeyId(cert); byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert); if ((aki != null) && (ski != null)) { boolean eq = Arrays.equals(aki, ski); if (!eq) { String akistr = new String(Hex.encode(aki)); String skistr = new String(Hex.encode(ski)); log.error(intres.getLocalizedMessage("signsession.errorpathverifykeyid", akistr, skistr)); } } Principal issuerDN = cert.getIssuerX500Principal(); Principal subjectDN = cacert.getSubjectX500Principal(); if ((issuerDN != null) && (subjectDN != null)) { boolean eq = issuerDN.equals(subjectDN); if (!eq) { log.error(intres.getLocalizedMessage("signsession.errorpathverifydn", issuerDN.getName(), subjectDN.getName())); } } } if (log.isDebugEnabled()) { log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: " + subject.getCertificateDN()); } return cert; }
From source file:org.ejbca.util.CertTools.java
License:Open Source License
public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException, NoSuchProviderException { // Create self signed certificate Date firstDate = new Date(); // Set back startdate ten minutes to avoid some problems with wrongly set clocks. firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); // validity in days = validity*24*60*60*1000 milliseconds lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;/* w w w. j a v a 2 s . com*/ if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { log.error("Error creating RSAPublicKey from spec: ", e); publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { log.error("Error creating ECPublicKey from spec: ", e); publicKey = pubKey; } catch (NullPointerException e) { log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage()); publicKey = pubKey; } } else { log.debug("Not converting key of class. " + pubKey.getClass().getName()); publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); certgen.setSerialNumber(new java.math.BigInteger(serno).abs()); certgen.setNotBefore(firstDate); certgen.setNotAfter(lastDate); certgen.setSignatureAlgorithm(sigAlg); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(dn)); certgen.setPublicKey(publicKey); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded())) .readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski); certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki); } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq); } X509Certificate selfcert = certgen.generate(privKey, provider); return selfcert; }
From source file:org.gluu.oxeleven.service.PKCS11Service.java
License:MIT License
private X509Certificate[] generateV3Certificate(KeyPair pair, String dnName, SignatureAlgorithm signatureAlgorithm, Long expirationTime) throws NoSuchAlgorithmException, CertificateEncodingException, NoSuchProviderException, InvalidKeyException, SignatureException { X500Principal principal = new X500Principal(dnName); BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(principal);/*from ww w .j a v a2 s . com*/ certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); certGen.setNotAfter(new Date(expirationTime)); certGen.setSubjectDN(principal); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm(signatureAlgorithm.getAlgorithm()); //certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); //certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); //certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); //certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); X509Certificate[] chain = new X509Certificate[1]; chain[0] = certGen.generate(pair.getPrivate(), "SunPKCS11-SoftHSM"); return chain; }
From source file:org.guanxi.common.security.SecUtils.java
License:Mozilla Public License
/** * Generates a self signed public/private key pair and puts them and the associated certificate in * a KeyStore./*w w w. ja v a 2 s .c om*/ * * @param cn The CN of the X509 containing the public key, e.g. "cn=guanxi_sp,ou=smo,o=uhi" * @param keystoreFile The full path and name of the KeyStore to create or add the certificate to * @param keystorePassword The password for the KeyStore * @param privateKeyPassword The password for the private key associated with the public key certificate * @param privateKeyAlias The alias under which the private key will be stored * @param keyType The type of key, RSA or DSA * @throws GuanxiException if an error occurred */ public void createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias, String keyType) throws GuanxiException { try { KeyStore ks = KeyStore.getInstance("JKS"); // Does the keystore exist? File keyStore = new File(keystoreFile); if (keyStore.exists()) { FileInputStream fis = new FileInputStream(keystoreFile); ks.load(fis, keystorePassword.toCharArray()); fis.close(); } else ks.load(null, null); // Generate a new public/private key pair KeyPairGenerator keyGen = null; if (keyType.toLowerCase().equals("rsa")) { keyGen = KeyPairGenerator.getInstance("RSA"); } else if (keyType.toLowerCase().equals("dsa")) { keyGen = KeyPairGenerator.getInstance("DSA"); } keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); /* Set the attributes of the X509 Certificate that will contain the public key. * This is a self signed certificate so the issuer and subject will be the same. */ Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); // Certificate valid from now Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); // Initialise the X509 Certificate information... X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); if (keyType.toLowerCase().equals("rsa")) { x509.setSignatureAlgorithm("SHA1withRSA"); } else if (keyType.toLowerCase().equals("dsa")) { x509.setSignatureAlgorithm("SHA1withDSA"); } x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); // ...generate it... X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); // ...and add the self signed certificate as the certificate chain java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; // Under the alias, store the X509 Certificate and it's public key... ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); // ...and the chain... ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); // ...and write the keystore to disk FileOutputStream fos = new FileOutputStream(keystoreFile); ks.store(fos, keystorePassword.toCharArray()); fos.close(); } catch (Exception se) { /* We'll end up here if a security manager is installed and it refuses us * permission to add the BouncyCastle provider */ throw new GuanxiException(se); } }
From source file:org.guanxi.idp.Bootstrap.java
License:Mozilla Public License
public boolean createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null;/*from ww w .j av a 2 s. c o m*/ try { ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java
License:Mozilla Public License
/** * Handles the nitty gritty of signing a CSR * * @param rootCert The certificate of the root authority who will vouch for the entity * @param rootPrivKey The private key of the root authority who will vouch for the entity * @param csr The entitie's CSR/*from w ww. jav a 2 s . c o m*/ * @param keyType The type of the key, e.g. "RSA", "DSA" * @return A certificate chain as an array of X509Certificate instances or null if an * error occurred */ private X509Certificate[] createSignedCert(X509Certificate rootCert, PrivateKey rootPrivKey, PKCS10CertificationRequest csr, String keyType) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); try { Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(validFrom); certGen.setNotAfter(validTo); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(csr.getPublicKey("BC")); if (keyType.toLowerCase().equals("rsa")) certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); if (keyType.toLowerCase().equals("dsa")) certGen.setSignatureAlgorithm("DSAWithSHA1"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); X509Certificate issuedCert = certGen.generate(rootPrivKey, "BC"); return new X509Certificate[] { issuedCert, rootCert }; } catch (Exception e) { logger.error(e); return null; } }
From source file:org.intermine.web.security.KeySigner.java
License:GNU General Public License
/** * Create a self-signed X.509 Certificate * * Should be eventually replaced with X509v3CertificateBuilder. * * @param subject Who we trust.//from w w w .j av a 2 s . co m * @param key The key we are asserting that we trust. * @return A certificate wrapping the key, signed by us. * @throws SigningException If we cannot generate the certificate for some reason. */ public X509Certificate generateCertificate(String subject, PublicKey key) throws SigningException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V3CertificateGenerator cert = new X509V3CertificateGenerator(); cert.setSerialNumber(BigInteger.valueOf(1)); //or generate a random number cert.setSubjectDN(new X509Principal("CN=" + subject)); //see examples to add O,OU etc cert.setIssuerDN(new X509Principal(issuer)); //same since it is self-signed cert.setPublicKey(key); cert.setNotBefore(new Date()); cert.setNotAfter(new Date(System.currentTimeMillis() + 1000L * 60L * 60L * 24L * days)); cert.setSignatureAlgorithm(algorithm); try { return cert.generate(signingKey, "BC"); } catch (CertificateEncodingException e) { throw new SigningException(e); } catch (InvalidKeyException e) { throw new SigningException(e); } catch (IllegalStateException e) { throw new SigningException(e); } catch (NoSuchProviderException e) { throw new SigningException(e); } catch (NoSuchAlgorithmException e) { throw new SigningException("Unknown algorithm", e); } catch (SignatureException e) { throw new SigningException(e); } }
From source file:org.jcryptool.visual.jctca.Util.java
License:Open Source License
public static X509Certificate certificateForKeyPair(String principal, String country, String street, String zip, String city, String unit, String organisation, String mail, PublicKey pub, PrivateKey priv, BigInteger serialNumber, X509Certificate caCert, Date expiryDate, Date startDate, PrivateKey caKey) { try {/* w w w . ja va 2 s .com*/ KeyPair keyPair = new KeyPair(pub, priv); // public/private key pair // that we are creating // certificate for X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Name subjectName = new X509Name("CN=" + principal + ", " + //$NON-NLS-1$ //$NON-NLS-2$ "ST=" + street + ", " + //$NON-NLS-1$ //$NON-NLS-2$ "L=" + zip + " " + city + ", " + "C=" + country + ", " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ "OU=" + unit + ", " + //$NON-NLS-1$ //$NON-NLS-2$ "O=" + organisation + ", " + //$NON-NLS-1$ //$NON-NLS-2$ "E=" + mail); //$NON-NLS-1$ certGen.setSerialNumber(serialNumber); if (caCert != null) { certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); // FIXME not working any more with BouncyCastle 1.51 // certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure( // keyPair.getPublic())); } else { certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); } certGen.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(subjectName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA512withRSA");//$NON-NLS-1$ X509Certificate cert; cert = certGen.generate(caKey, "BC");//$NON-NLS-1$ return cert; } catch (CertificateEncodingException e) { LogUtil.logError(e); } catch (InvalidKeyException e) { LogUtil.logError(e); } catch (IllegalStateException e) { LogUtil.logError(e); } catch (NoSuchProviderException e) { LogUtil.logError(e); } catch (NoSuchAlgorithmException e) { LogUtil.logError(e); } catch (SignatureException e) { LogUtil.logError(e); } catch (CertificateParsingException e) { LogUtil.logError(e); } return null; // note: private key of CA }
From source file:org.jcryptool.visual.ssl.protocol.Crypto.java
License:Open Source License
/** * Generates a default certificate with the given key pair {@link pubKey} * The certificate will be singed with the {@link sigKey} and uses the * {@link strHash} with and the {@link strSignature} algorithm. * * @param key// w w w. j a v a 2 s. c o m * @throws CertificateEncodingException * @throws InvalidKeyException * @throws IllegalStateException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws SignatureException */ public X509Certificate generateX509(KeyPair pubKey, KeyPair sigKey, String strHash, String strSignature) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException { Calendar notBefore = Calendar.getInstance(); Calendar notAfter = Calendar.getInstance(); notAfter.set(Calendar.YEAR, notBefore.get(Calendar.YEAR) + 1); notAfter.set(Calendar.HOUR, 23); notAfter.set(Calendar.MINUTE, 59); notAfter.set(Calendar.SECOND, 59); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal certName = new X500Principal("CN=Test Server Certificate"); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(certName); certGen.setNotAfter(notAfter.getTime()); certGen.setNotBefore(notBefore.getTime()); certGen.setSubjectDN(certName); certGen.setPublicKey(pubKey.getPublic()); certGen.setSignatureAlgorithm(strHash + "With" + strSignature); X509Certificate cert = certGen.generate(sigKey.getPrivate(), "BC"); return cert; }