List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber
public void setSerialNumber(BigInteger serialNumber)
From source file:org.ebayopensource.fido.uaf.crypto.X509.java
License:Apache License
public static X509Certificate generateV3Cert(KeyPair pair) { X509Certificate cert = null;//from ww w .java 2 s . com 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 . j ava2s . com */ 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;/*ww w. ja va2 s .c o m*/ 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.everit.osgi.keystore.file.tests.KeyStoreUtil.java
License:Open Source License
private static Certificate generateCertificate(final PrivateKey privateKey, final PublicKey publicKey, final String signatureAlgorithm) throws Exception { Calendar calendar = Calendar.getInstance(); Date notBefore = calendar.getTime(); calendar.add(Calendar.MINUTE, 1); Date notAfter = calendar.getTime(); X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); v3CertGen.setIssuerDN(new X509Principal("CN=cn, O=o, L=L, ST=il, C=c")); v3CertGen.setNotBefore(notBefore);/*w ww . ja v a 2 s . c o m*/ v3CertGen.setNotAfter(notAfter); v3CertGen.setSubjectDN(new X509Principal("CN=cn, O=o, L=L, ST=il, C=c")); v3CertGen.setPublicKey(publicKey); v3CertGen.setSignatureAlgorithm(signatureAlgorithm); return v3CertGen.generateX509Certificate(privateKey); }
From source file:org.geoserver.web.Start.java
License:Open Source License
private static void assureSelfSignedServerCertificate(String hostname, File keyStoreFile, String password) throws Exception { KeyStore privateKS = KeyStore.getInstance("JKS"); if (keyStoreFile.exists()) { FileInputStream fis = new FileInputStream(keyStoreFile); privateKS.load(fis, password.toCharArray()); if (keyStoreContainsCertificate(privateKS, hostname)) return; } else {/* ww w . j a v a 2s . c o m*/ privateKS.load(null); } // create a RSA key pair generator using 1024 bits KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair KPair = keyPairGenerator.generateKeyPair(); // cerate a X509 certifacte generator X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // set validity to 10 years, issuer and subject are equal --> self singed certificate int random = new SecureRandom().nextInt(); if (random < 0) random *= -1; v3CertGen.setSerialNumber(BigInteger.valueOf(random)); v3CertGen.setIssuerDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None")); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); v3CertGen.setSubjectDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None")); v3CertGen.setPublicKey(KPair.getPublic()); v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate PKCertificate = v3CertGen.generateX509Certificate(KPair.getPrivate()); // store the certificate containing the public key,this file is needed // to import the public key in other key store. File certFile = new File(keyStoreFile.getParentFile(), hostname + ".cert"); FileOutputStream fos = new FileOutputStream(certFile.getAbsoluteFile()); fos.write(PKCertificate.getEncoded()); fos.close(); privateKS.setKeyEntry(hostname + ".key", KPair.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { PKCertificate }); privateKS.setCertificateEntry(hostname + ".cert", PKCertificate); privateKS.store(new FileOutputStream(keyStoreFile), password.toCharArray()); }
From source file:org.glite.security.delegation.GrDProxyGenerator.java
License:Apache License
/** * Create a proxy certificate from a given certificate * /*w w w .j a v a 2 s.c o m*/ * @param issuerCert * issuer certificate * @param issuerKey * issuer private key * @param publicKey * public key of delegatee * @param lifetime * life time of proxy * @param proxyType * type of proxy * @param cnValue * common name of proxy * @return created proxy certificate * @throws GeneralSecurityException * @deprecated Use proxy generator from util-java */ public X509Certificate createProxyCertificate(X509Certificate issuerCert, PrivateKey issuerKey, PublicKey publicKey, int lifetime1, int proxyType1, String cnValue) throws GeneralSecurityException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); BigInteger serialNum = null; serialNum = issuerCert.getSerialNumber(); X509Name issuer = (X509Name) issuerCert.getSubjectDN(); ASN1Sequence seqSubject = (ASN1Sequence) issuer.getDERObject(); logger.debug("SubjectDN of IssuerCert" + issuer); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(X509Name.CN); v.add(new DERPrintableString(cnValue)); Enumeration subjectParts = seqSubject.getObjects(); ASN1EncodableVector subjectVector = new ASN1EncodableVector(); while (subjectParts.hasMoreElements()) { DERObject part = (DERObject) subjectParts.nextElement(); subjectVector.add(part); } subjectVector.add(new DERSet(new DERSequence(v))); DERSequence subjDerSeq = new DERSequence(subjectVector); X509Name subjectX = new X509Name(subjDerSeq); logger.debug("SubjectDN :" + subjectX); certGen.setSubjectDN(subjectX); certGen.setIssuerDN(issuer); certGen.setSerialNumber(serialNum); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm(issuerCert.getSigAlgName()); certGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature)); GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("UTC")); date.add(Calendar.MINUTE, -5); certGen.setNotBefore(date.getTime()); if (lifetime1 <= 0) { certGen.setNotAfter(issuerCert.getNotAfter()); } else { date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime1); certGen.setNotAfter(date.getTime()); } return certGen.generateX509Certificate(issuerKey); }
From source file:org.glite.voms.contact.VOMSProxyBuilder.java
License:Open Source License
private static X509Certificate myCreateProxyCertificate(X509Certificate cert, PrivateKey issuerKey, PublicKey publicKey, int lifetime, DelegationType delegationMode, CertificateType gtVersion, HashMap extensions, String policyType) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); String cnValue = null;// w w w . ja va 2 s . c o m ProxyPolicy policy = null; BigInteger serialNum = null; switch (delegationMode) { case LIMITED: cnValue = "limited proxy"; break; case FULL: cnValue = "proxy"; break; default: break; } switch (gtVersion) { case GSI_2_PROXY: policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION); serialNum = cert.getSerialNumber(); case GSI_2_LIMITED_PROXY: policy = new ProxyPolicy(ProxyPolicy.LIMITED); serialNum = cert.getSerialNumber(); break; case GSI_3_IMPERSONATION_PROXY: case GSI_3_INDEPENDENT_PROXY: case GSI_3_LIMITED_PROXY: case GSI_3_RESTRICTED_PROXY: case GSI_4_IMPERSONATION_PROXY: case GSI_4_INDEPENDENT_PROXY: case GSI_4_LIMITED_PROXY: case GSI_4_RESTRICTED_PROXY: Random rand = new Random(); int number = Math.abs(rand.nextInt()); cnValue = String.valueOf(number); serialNum = new BigInteger(String.valueOf(number)); ExtensionData data = (ExtensionData) extensions.get(PROXY_CERT_INFO_V3_OID); if (data == null) { if (policyType == null) { switch (gtVersion) { case GSI_3_LIMITED_PROXY: case GSI_4_LIMITED_PROXY: policy = new ProxyPolicy(ProxyPolicy.LIMITED); break; case GSI_3_IMPERSONATION_PROXY: case GSI_4_IMPERSONATION_PROXY: policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION); break; case GSI_3_INDEPENDENT_PROXY: case GSI_4_INDEPENDENT_PROXY: policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT); break; default: throw new IllegalArgumentException("Invalid proxyType " + gtVersion); } } else { try { policy = new ProxyPolicy(new ASN1ObjectIdentifier(policyType)); } catch (IllegalArgumentException e) { throw new VOMSException("OID required as policyType"); } } if (ProxyCertificateUtil.isGsi3Proxy(gtVersion)) { extensions.put(PROXY_CERT_INFO_V3_OID, ExtensionData.creator(PROXY_CERT_INFO_V3_OID, new MyProxyCertInfo(policy, gtVersion).toASN1Primitive())); } else if (ProxyCertificateUtil.isGsi4Proxy(gtVersion)) { extensions.put(PROXY_CERT_INFO_V4_OID, ExtensionData.creator(PROXY_CERT_INFO_V4_OID, true, new MyProxyCertInfo(policy, gtVersion).toASN1Primitive())); } } } ExtensionData[] exts = (ExtensionData[]) extensions.values().toArray(new ExtensionData[] {}); for (int i = 0; i < exts.length; i++) { certGen.addExtension(exts[i].getOID(), exts[i].getCritical(), exts[i].getObj()); } X509Name issuerDN = (X509Name) cert.getSubjectDN(); X509NameHelper issuer = new X509NameHelper(issuerDN); X509NameHelper subject = new X509NameHelper(issuerDN); subject.add(X509Name.CN, cnValue); certGen.setSubjectDN(subject.getAsName()); certGen.setIssuerDN(issuer.getAsName()); certGen.setSerialNumber(serialNum); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm(cert.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(cert.getNotAfter()); } else { date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime); certGen.setNotAfter(date.getTime()); } try { return certGen.generate(issuerKey); } catch (SignatureException e) { log.error("Error creating proxy: " + e.getMessage()); if (log.isDebugEnabled()) { log.error(e.getMessage(), e); } throw new VOMSException(e); } catch (InvalidKeyException e) { log.error("Error creating proxy: " + e.getMessage()); if (log.isDebugEnabled()) { log.error(e.getMessage(), e); } throw new VOMSException(e); } catch (CertificateEncodingException e) { log.error("Error creating proxy: " + e.getMessage()); if (log.isDebugEnabled()) { log.error(e.getMessage(), e); } throw new VOMSException(e); } catch (IllegalStateException e) { log.error("Error creating proxy: " + e.getMessage()); if (log.isDebugEnabled()) { log.error(e.getMessage(), e); } throw new VOMSException(e); } catch (NoSuchAlgorithmException e) { log.error("Error creating proxy: " + e.getMessage()); if (log.isDebugEnabled()) { log.error(e.getMessage(), e); } throw new VOMSException(e); } }
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 ww w . j a va2 s . com * 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 proxyType * can be one of {@link GSIConstants#DELEGATION_LIMITED GSIConstants.DELEGATION_LIMITED}, * {@link GSIConstants#DELEGATION_FULL GSIConstants.DELEGATION_FULL}, * * {@link GSIConstants#GSI_2_LIMITED_PROXY GSIConstants.GSI_2_LIMITED_PROXY}, * {@link GSIConstants#GSI_2_PROXY GSIConstants.GSI_2_PROXY}, * {@link GSIConstants#GSI_3_IMPERSONATION_PROXY GSIConstants.GSI_3_IMPERSONATION_PROXY}, * {@link GSIConstants#GSI_3_LIMITED_PROXY GSIConstants.GSI_3_LIMITED_PROXY}, * {@link GSIConstants#GSI_3_INDEPENDENT_PROXY GSIConstants.GSI_3_INDEPENDENT_PROXY}, * {@link GSIConstants#GSI_3_RESTRICTED_PROXY GSIConstants.GSI_3_RESTRICTED_PROXY}. * {@link GSIConstants#GSI_4_IMPERSONATION_PROXY GSIConstants.GSI_4_IMPERSONATION_PROXY}, * {@link GSIConstants#GSI_4_LIMITED_PROXY GSIConstants.GSI_3_LIMITED_PROXY}, * {@link GSIConstants#GSI_4_INDEPENDENT_PROXY GSIConstants.GSI_4_INDEPENDENT_PROXY}, * {@link GSIConstants#GSI_4_RESTRICTED_PROXY GSIConstants.GSI_4_RESTRICTED_PROXY}. * * If {@link GSIConstants#DELEGATION_LIMITED GSIConstants.DELEGATION_LIMITED} and if * {@link VersionUtil#isGsi2Enabled() CertUtil.isGsi2Enabled} returns true then a GSI-2 limited * proxy will be created. Else if {@link VersionUtil#isGsi3Enabled() CertUtil.isGsi3Enabled} * returns true then a GSI-3 limited proxy will be created. If not, a GSI-4 limited proxy will * be created. * * If {@link GSIConstants#DELEGATION_FULL GSIConstants.DELEGATION_FULL} and if * {@link VersionUtil#isGsi2Enabled() CertUtil.isGsi2Enabled} returns true then a GSI-2 full proxy * will be created. Else if {@link VersionUtil#isGsi3Enabled() CertUtil.isGsi3Enabled} returns * true then a GSI-3 full proxy will be created. If not, a GSI-4 full proxy will be created. * * @param extSet * a set of X.509 extensions to be included in the new proxy certificate. Can be null. If * delegation mode is {@link GSIConstants#GSI_3_RESTRICTED_PROXY * GSIConstants.GSI_3_RESTRICTED_PROXY} or {@link GSIConstants#GSI_4_RESTRICTED_PROXY * GSIConstants.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. * @deprecated */ public X509Certificate createProxyCertificate(X509Certificate issuerCert_, PrivateKey issuerKey, PublicKey publicKey, int lifetime, int proxyType, X509ExtensionSet extSet, String cnValue) throws GeneralSecurityException { X509Certificate issuerCert = issuerCert_; if (!(issuerCert_ instanceof X509CertificateObject)) { issuerCert = CertificateLoadUtil.loadCertificate(new ByteArrayInputStream(issuerCert.getEncoded())); } if (proxyType == GSIConstants.DELEGATION_LIMITED) { GSIConstants.CertificateType type = BouncyCastleUtil.getCertificateType(issuerCert); if (ProxyCertificateUtil.isGsi4Proxy(type)) { proxyType = GSIConstants.GSI_4_LIMITED_PROXY; } else if (ProxyCertificateUtil.isGsi3Proxy(type)) { proxyType = GSIConstants.GSI_3_LIMITED_PROXY; } else if (ProxyCertificateUtil.isGsi2Proxy(type)) { proxyType = GSIConstants.GSI_2_LIMITED_PROXY; } else { // default to RFC compliant proxy if (VersionUtil.isGsi2Enabled()) { proxyType = GSIConstants.GSI_2_LIMITED_PROXY; } else { proxyType = VersionUtil.isGsi3Enabled() ? GSIConstants.GSI_3_LIMITED_PROXY : GSIConstants.GSI_4_LIMITED_PROXY; } } } else if (proxyType == GSIConstants.DELEGATION_FULL) { GSIConstants.CertificateType type = BouncyCastleUtil.getCertificateType(issuerCert); if (ProxyCertificateUtil.isGsi4Proxy(type)) { proxyType = GSIConstants.GSI_4_IMPERSONATION_PROXY; } else if (ProxyCertificateUtil.isGsi3Proxy(type)) { proxyType = GSIConstants.GSI_3_IMPERSONATION_PROXY; } else if (ProxyCertificateUtil.isGsi2Proxy(type)) { proxyType = GSIConstants.GSI_2_PROXY; } else { // Default to RFC complaint proxy if (VersionUtil.isGsi2Enabled()) { proxyType = GSIConstants.GSI_2_PROXY; } else { proxyType = (VersionUtil.isGsi3Enabled()) ? GSIConstants.GSI_3_IMPERSONATION_PROXY : GSIConstants.GSI_4_IMPERSONATION_PROXY; } } } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); org.globus.gsi.X509Extension x509Ext = null; BigInteger serialNum = null; String delegDN = null; if (ProxyCertificateUtil.isGsi3Proxy(GSIConstants.CertificateType.get(proxyType)) || ProxyCertificateUtil.isGsi4Proxy(GSIConstants.CertificateType.get(proxyType))) { 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(GSIConstants.CertificateType.get(proxyType))) { policy = new ProxyPolicy(ProxyPolicy.LIMITED); } else if (ProxyCertificateUtil.isIndependentProxy(GSIConstants.CertificateType.get(proxyType))) { policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT); } else if (ProxyCertificateUtil.isImpersonationProxy(GSIConstants.CertificateType.get(proxyType))) { // since limited has already been checked, this should work. policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION); } else if ((proxyType == GSIConstants.GSI_3_RESTRICTED_PROXY) || (proxyType == GSIConstants.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(GSIConstants.CertificateType.get(proxyType))) { // 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 (proxyType == GSIConstants.GSI_2_LIMITED_PROXY) { delegDN = "limited proxy"; serialNum = issuerCert.getSerialNumber(); } else if (proxyType == GSIConstants.GSI_2_PROXY) { delegDN = "proxy"; serialNum = issuerCert.getSerialNumber(); } else { String err = i18n.getMessage("unsupportedProxy", Integer.toString(proxyType)); 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.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 ww . ja v 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.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 w ww . j av a 2 s .c om*/ 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; }