List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator X509V3CertificateGenerator
public X509V3CertificateGenerator()
From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java
License:Apache License
/** * Creates a proxy certificate. A set of X.509 extensions can be optionally included in the new proxy * certificate. <BR>/*from w w w . j av a 2 s .c o m*/ * If a GSI-2 proxy is created, the serial number of the proxy certificate will be the same as of the * issuing certificate. Also, none of the extensions in the issuing certificate will be copied into the * proxy certificate.<BR> * If a GSI-3 or GSI 4 proxy is created, the serial number of the proxy certificate will be picked * randomly. If the issuing certificate contains a <i>KeyUsage</i> extension, the extension will be copied * into the proxy certificate with <i>keyCertSign</i> and <i>nonRepudiation</i> bits turned off. No other * extensions are currently copied. * * The methods defaults to creating GSI 4 proxy * * @param issuerCert_ * the issuing certificate * @param issuerKey * private key matching the public key of issuer certificate. The new proxy certificate will be * signed by that key. * @param publicKey * the public key of the new certificate * @param lifetime * lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will * have the same lifetime as the issuing certificate. * @param certType * can be one of {@link org.globus.gsi.GSIConstants.CertificateType#GSI_2_LIMITED_PROXY GSIConstants.CertificateType.GSI_2_LIMITED_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_2_PROXY GSIConstants.CertificateType.GSI_2_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_IMPERSONATION_PROXY GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_LIMITED_PROXY GSIConstants.CertificateType.GSI_3_LIMITED_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_INDEPENDENT_PROXY GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY}. * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_IMPERSONATION_PROXY GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_LIMITED_PROXY GSIConstants.CertificateType.GSI_3_LIMITED_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_INDEPENDENT_PROXY GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY}, * {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY}. * * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY * GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then * {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be * present in the extension set. * * @param cnValue * the value of the CN component of the subject of the new certificate. If null, the defaults * will be used depending on the proxy certificate type created. * @return <code>X509Certificate</code> the new proxy certificate. * @exception GeneralSecurityException * if a security error occurs. */ public X509Certificate createProxyCertificate(X509Certificate issuerCert_, PrivateKey issuerKey, PublicKey publicKey, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet, String cnValue) throws GeneralSecurityException { X509Certificate issuerCert = issuerCert_; if (!(issuerCert_ instanceof X509CertificateObject)) { issuerCert = CertificateLoadUtil.loadCertificate(new ByteArrayInputStream(issuerCert.getEncoded())); } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); org.globus.gsi.X509Extension x509Ext = null; BigInteger serialNum = null; String delegDN = null; if (ProxyCertificateUtil.isGsi3Proxy(certType) || ProxyCertificateUtil.isGsi4Proxy(certType)) { Random rand = new Random(); delegDN = String.valueOf(Math.abs(rand.nextInt())); serialNum = new BigInteger(20, rand); if (extSet != null) { x509Ext = extSet.get(ProxyCertInfo.OID.getId()); if (x509Ext == null) { x509Ext = extSet.get(ProxyCertInfo.OLD_OID.getId()); } } if (x509Ext == null) { // create ProxyCertInfo extension ProxyPolicy policy = null; if (ProxyCertificateUtil.isLimitedProxy(certType)) { policy = new ProxyPolicy(ProxyPolicy.LIMITED); } else if (ProxyCertificateUtil.isIndependentProxy(certType)) { policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT); } else if (ProxyCertificateUtil.isImpersonationProxy(certType)) { // since limited has already been checked, this should work. policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION); } else if ((certType == GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY) || (certType == GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY)) { String err = i18n.getMessage("restrictProxy"); throw new IllegalArgumentException(err); } else { String err = i18n.getMessage("invalidProxyType"); throw new IllegalArgumentException(err); } ProxyCertInfo proxyCertInfo = new ProxyCertInfo(policy); x509Ext = new ProxyCertInfoExtension(proxyCertInfo); if (ProxyCertificateUtil.isGsi4Proxy(certType)) { // RFC compliant OID x509Ext = new ProxyCertInfoExtension(proxyCertInfo); } else { // old OID x509Ext = new GlobusProxyCertInfoExtension(proxyCertInfo); } } try { // add ProxyCertInfo extension to the new cert certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue()); // handle KeyUsage in issuer cert TBSCertificateStructure crt = BouncyCastleUtil.getTBSCertificateStructure(issuerCert); X509Extensions extensions = crt.getExtensions(); if (extensions != null) { X509Extension ext; // handle key usage ext ext = extensions.getExtension(X509Extension.keyUsage); if (ext != null) { // TBD: handle this better if (extSet != null && (extSet.get(X509Extension.keyUsage.getId()) != null)) { String err = i18n.getMessage("keyUsageExt"); throw new GeneralSecurityException(err); } DERBitString bits = (DERBitString) BouncyCastleUtil.getExtensionObject(ext); byte[] bytes = bits.getBytes(); // make sure they are disabled if ((bytes[0] & KeyUsage.nonRepudiation) != 0) { bytes[0] ^= KeyUsage.nonRepudiation; } if ((bytes[0] & KeyUsage.keyCertSign) != 0) { bytes[0] ^= KeyUsage.keyCertSign; } bits = new DERBitString(bytes, bits.getPadBits()); certGen.addExtension(X509Extension.keyUsage, ext.isCritical(), bits); } } } catch (IOException e) { // but this should not happen throw new GeneralSecurityException(e.getMessage()); } } else if (certType == GSIConstants.CertificateType.GSI_2_LIMITED_PROXY) { delegDN = "limited proxy"; serialNum = issuerCert.getSerialNumber(); } else if (certType == GSIConstants.CertificateType.GSI_2_PROXY) { delegDN = "proxy"; serialNum = issuerCert.getSerialNumber(); } else { String err = i18n.getMessage("unsupportedProxy", certType); throw new IllegalArgumentException(err); } // add specified extensions if (extSet != null) { Iterator iter = extSet.oidSet().iterator(); while (iter.hasNext()) { String oid = (String) iter.next(); // skip ProxyCertInfo extension if (oid.equals(ProxyCertInfo.OID.getId()) || oid.equals(ProxyCertInfo.OLD_OID.getId())) { continue; } x509Ext = (org.globus.gsi.X509Extension) extSet.get(oid); certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue()); } } X509Name issuerDN; if (issuerCert.getSubjectDN() instanceof X509Name) { issuerDN = (X509Name) issuerCert.getSubjectDN(); } else { issuerDN = new X509Name(true, issuerCert.getSubjectX500Principal().getName()); } X509NameHelper issuer = new X509NameHelper(issuerDN); X509NameHelper subject = new X509NameHelper(issuerDN); subject.add(BCStyle.CN, (cnValue == null) ? delegDN : cnValue); certGen.setSubjectDN(subject.getAsName()); certGen.setIssuerDN(issuer.getAsName()); certGen.setSerialNumber(serialNum); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm(issuerCert.getSigAlgName()); GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT")); /* Allow for a five minute clock skew here. */ date.add(Calendar.MINUTE, -5); certGen.setNotBefore(date.getTime()); /* If hours = 0, then cert lifetime is set to user cert */ if (lifetime <= 0) { certGen.setNotAfter(issuerCert.getNotAfter()); } else { date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime); certGen.setNotAfter(date.getTime()); } return certGen.generateX509Certificate(issuerKey); }
From source file:org.globus.gsi.gssapi.test.GlobusGSSCredentialTest.java
License:Apache License
@Override protected void setUp() throws Exception { manager = new GlobusGSSManagerImpl(); kpg = KeyPairGenerator.getInstance("RSA"); certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.setIssuerDN(SELF_SIGNED_DN); certificateGenerator.setSubjectDN(SELF_SIGNED_DN); certificateGenerator.setNotBefore(new Date()); certificateGenerator.setNotAfter(new Date(System.currentTimeMillis() + 1000 * 60)); certificateGenerator.setSerialNumber(BigInteger.ONE); certificateGenerator.setSignatureAlgorithm("SHA1WithRSA"); }
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);/* ww w. j a v a 2 s . c o m*/ 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./*from w ww . ja v a 2 s . c o m*/ * * @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 w w w .j av a 2s .com*/ 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 www. j av a2 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 a v a2 s.c om * @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 {//from w w w .j a v a 2 s.co m 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.sigVerification.cert.CertGeneration.java
License:Open Source License
/** * this method creates the x.509 certificate and the needed keypair * @param x - the number value of the certificate (root=1) * @return the generated certificate//w w w .j av a2 s . c om * @throws Exception */ public X509Certificate createCertificate(int x) throws Exception { this.x = x; X509Certificate cert = null; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CERTIFICATE_ALGORITHM); keyPairGenerator.initialize(CERTIFICATE_BITS, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // GENERATE THE X509 CERTIFICATE X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); v3CertGen.setIssuerDN(new X509Principal(CERTIFICATE_DN)); v3CertGen.setNotBefore(now); v3CertGen.setNotAfter(end); v3CertGen.setSubjectDN(new X509Principal(CERTIFICATE_DN)); v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); cert = v3CertGen.generateX509Certificate(keyPair.getPrivate()); saveCert(cert, keyPair.getPrivate()); return cert; }
From source file:org.jcryptool.visual.sigVerification.cert.CertGeneration.java
License:Open Source License
/** * this method creates the needed keypair and the x.509 certificate valid till the given date * @param x - the number value of the certificate (root=1) * @param newend - the new not after date * @return the generated certificate/*from w ww. java 2s.c om*/ */ public X509Certificate createCertificateNew(int x, Date newend) throws Exception { this.x = x; X509Certificate cert = null; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CERTIFICATE_ALGORITHM); keyPairGenerator.initialize(CERTIFICATE_BITS, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // GENERATE THE X509 CERTIFICATE X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); v3CertGen.setIssuerDN(new X509Principal(CERTIFICATE_DN)); v3CertGen.setNotBefore(now); v3CertGen.setNotAfter(newend); v3CertGen.setSubjectDN(new X509Principal(CERTIFICATE_DN)); v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); cert = v3CertGen.generateX509Certificate(keyPair.getPrivate()); saveCert(cert, keyPair.getPrivate()); return cert; }