List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setNotBefore
public void setNotBefore(Date date)
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;//from w ww. j av a2 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.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); v3CertGen.setNotAfter(notAfter);//w ww. ja v a 2 s. c o m 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 va 2 s .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 * /*from ww w . j av a 2s .co 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 ww . j a va 2s. 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>/*w ww.jav 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 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 www.j a v a2 s.c om*/ * 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 w 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./* ww w . ja v a2 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 w w w. j a v a 2s. 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; } }