List of usage examples for org.bouncycastle.asn1.x509 X509Name X509Name
public X509Name(boolean reverse, String dirName)
From source file:ClientOCSPDriver.java
License:Open Source License
/** Generates a signed OCSP client request with the parameters specified in the constructor. This method can only be called once.//from w w w.jav a 2 s. com @param signingalgorithm The algorithm, that should be used to sign the OCSP client request, default is "MD5WITHRSA". @param provider The provider used to compute the hashes and sign the request, default is "BC" (Bouncy Castle). @return The raw DER encoded client OCSP request. This data has to be transported over a specific protocol (such as HTTP) to the OCSP server in order to get an OCSP server response. */ public byte[] getRequest(String signingalgorithm, String provider, String user) throws OCSPException, NoSuchProviderException, IOException { if (calledgenerate) throw new OCSPException("Request was already generated!"); map.clear(); OCSPReqGenerator gen = new OCSPReqGenerator(); for (int i = 0; i < certificates.length; ++i) { CertificateID certid = new CertificateID(CertificateID.HASH_SHA1, mastercert, certificates[i].getSerialNumber()); System.out.println("issuerNameHash: " + toHexadecimal(certid.getIssuerNameHash())); System.out.println("issuerKeyHash: " + toHexadecimal(certid.getIssuerKeyHash())); System.out.println("serialNumber: " + certid.getSerialNumber()); map.put(certid, certificates[i]); gen.addRequest(certid); } ASN1Sequence seq = null; if (usercert != null && userkey != null && user == null) { X509Name subjectName = new X509Name(true, usercert.getSubjectX500Principal().getName()); Vector oids = subjectName.getOIDs(); Vector values = subjectName.getValues(); //Create a ASNSequence object for the subject DN seq = getASNSequence(oids, values); gen.setRequestorName(new GeneralName(new X509Name(seq))); } if (user != null) { gen.setRequestorName(new GeneralName(GeneralName.rfc822Name, user)); } //Include nonce extension 1.3.6.1.5.5.7.48.1.2 /* byte[] Nonce = new byte[16]; random.nextBytes(Nonce); ASN1EncodableVector v = new ASN1EncodableVector(); ASN1EncodableVector sVec = new ASN1EncodableVector(); DERObjectIdentifier oid = new DERObjectIdentifier("1.3.6.1.5.5.7.48.1.2"); v.add(oid); v.add(new DEROctetString(Nonce)); sVec.add(new DERSequence(v)); seq = new DERSequence(sVec); gen.setRequestExtensions(new X509Extensions(seq)); */ //End byte[] ocspdata = null; if (usercert != null && userkey != null) { ocspdata = gen.generate(signingalgorithm, userkey, new X509Certificate[] { usercert }, provider) .getEncoded(); } else { ocspdata = gen.generate().getEncoded(); } calledgenerate = true; return ocspdata; }
From source file:net.java.bd.tools.security.SecurityUtil.java
License:Open Source License
private void generateSelfSignedCertificate(String issuer, String alias, String keyPassword, boolean isRootCert) throws Exception { Date validFrom, validTo;// w w w . ja va 2s.c o m // For forcing GeneralizedTime DER encoding, with Bouncy Castle Provider // make the range before 1950 and after 2050. The BD-J spec recommends // using the default validity period used below Calendar calendar = Calendar.getInstance(); calendar.set(0000, 1, 1); validFrom = calendar.getTime(); calendar.clear(); calendar.set(9999, 1, 1); validTo = calendar.getTime(); // Generate a new keypair for this certificate KeyPair keyPair = generateKeyPair(); X509V3CertificateGenerator cg = new X509V3CertificateGenerator(); cg.reset(); X509Name name = new X509Name(issuer, new X509BDJEntryConverter()); // Generate Serial Number SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); BigInteger serNo = new BigInteger(32, prng); cg.setSerialNumber(serNo); if (!isRootCert) { appCertSerNo = serNo; } cg.setIssuerDN(name); cg.setNotBefore(validFrom); cg.setNotAfter(validTo); cg.setSubjectDN(name); cg.setPublicKey(keyPair.getPublic()); cg.setSignatureAlgorithm("SHA1WITHRSA"); if (isRootCert) { // Need to add root cert extensions. if (isBindingUnitCert) { // This certificate is used only for signing cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(X509KeyUsage.digitalSignature)); } else { int usage = X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign; cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(usage)); } cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false, getRfc822Name(altName)); cg.addExtension(X509Extensions.BasicConstraints.getId(), true, new BasicConstraints(true)); } // For an app cert, most of the extensions will be added when generating // a certificate in response to the certificate request file. cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName)); Certificate cert = cg.generate(keyPair.getPrivate()); store.setKeyEntry(alias, keyPair.getPrivate(), keyPassword.toCharArray(), new Certificate[] { cert }); FileOutputStream fos = new FileOutputStream(keystoreFile); store.store(fos, keystorePassword.toCharArray()); fos.close(); }
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 . j a v a 2s . 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>/*w w w .j a v a2s .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.bc.BouncyCastleUtil.java
License:Apache License
/** * Returns the subject DN of the given certificate in the Globus format. * * @param cert the certificate to get the subject of. The certificate * must be of <code>X509CertificateObject</code> type. * @return the subject DN of the certificate in the Globus format. *///from w w w. j a v a 2 s .c om public static String getIdentity(X509Certificate cert) { if (cert == null) { return null; } String subjectDN = cert.getSubjectX500Principal().getName(X500Principal.RFC2253); X509Name name = new X509Name(true, subjectDN); return X509NameHelper.toString(name); }
From source file:org.globus.gsi.bc.BouncyCastleUtil.java
License:Apache License
public static String getIdentityPrefix(X509Certificate cert) { if (cert == null) { return null; }/*from w w w . jav a 2s .c om*/ String subjectDN = cert.getSubjectX500Principal().getName(X500Principal.RFC2253); LdapName ldapname = null; try { ldapname = new LdapName(subjectDN); ldapname.remove(ldapname.size() - 1); } catch (InvalidNameException e) { return null; } X509Name name = new X509Name(true, ldapname.toString()); return X509NameHelper.toString(name); }
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 ww w . ja v a 2 s . co 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 a va 2 s. co m try { ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
From source file:org.gudy.azureus2.core3.security.impl.SESecurityManagerBC.java
License:Open Source License
public static Certificate createSelfSignedCertificate(SESecurityManagerImpl manager, String alias, String cert_dn, int strength) throws Exception { KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA"); kg.initialize(strength, RandomUtils.SECURE_RANDOM); KeyPair pair = kg.generateKeyPair(); X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.setSignatureAlgorithm("MD5WithRSAEncryption"); certificateGenerator.setSerialNumber(new BigInteger("" + SystemTime.getCurrentTime())); X509Name issuer_dn = new X509Name(true, cert_dn); certificateGenerator.setIssuerDN(issuer_dn); X509Name subject_dn = new X509Name(true, cert_dn); certificateGenerator.setSubjectDN(subject_dn); Calendar not_after = Calendar.getInstance(); not_after.add(Calendar.YEAR, 1); certificateGenerator.setNotAfter(not_after.getTime()); certificateGenerator.setNotBefore(Calendar.getInstance().getTime()); certificateGenerator.setPublicKey(pair.getPublic()); X509Certificate certificate = certificateGenerator.generateX509Certificate(pair.getPrivate()); java.security.cert.Certificate[] certChain = { (java.security.cert.Certificate) certificate }; manager.addCertToKeyStore(alias, pair.getPrivate(), certChain); return (certificate); }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
/** * Creates a (Bouncycastle) X509Name object from a string with a DN. Known OID (with order) * are: <code> EmailAddress, UID, CN, SN (SerialNumber), GivenName, Initials, SurName, T, OU, * O, L, ST, DC, C </code>//from w w w .j a v a 2s.co m * To change order edit 'dnObjects' in this source file. * * @param dn String containing DN that will be transformed into X509Name, The DN string has the * format "CN=zz,OU=yy,O=foo,C=SE". Unknown OIDs in the string will be silently * dropped. * * @return X509Name */ public static X509Name stringToBcX509Name(String dn) { //log.debug(">stringToBcX509Name: " + dn); // first make two vectors, one with all the C, O, OU etc specifying // the order and one holding the actual values ArrayList<String> oldordering = new ArrayList<String>(); ArrayList<String> oldvalues = new ArrayList<String>(); X509NameTokenizer xt = new X509NameTokenizer(dn); while (xt.hasMoreTokens()) { // This is a pair (CN=xx) String pair = xt.nextToken(); int ix = pair.indexOf("="); if (ix != -1) { // make lower case so we can easily compare later oldordering.add(pair.substring(0, ix).toLowerCase()); oldvalues.add(pair.substring(ix + 1)); } else { // Huh, what's this? } } // Now in the specified order, move from oldordering to newordering, // reshuffling as we go along Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); Vector<String> values = new Vector<String>(); int index = -1; for (String object : dNObjects) { while ((index = oldordering.indexOf(object)) != -1) { //log.debug("Found 1 "+object+" at index " + index); DERObjectIdentifier oid = getOid(object); if (oid != null) { //log.debug("Added "+object+", "+oldvalues.elementAt(index)); ordering.add(oid); // remove from the old vectors, so we start clean the next round values.add(oldvalues.remove(index)); oldordering.remove(index); index = -1; } } } /* if (log.isDebugEnabled()) { Iterator i1 = ordering.iterator(); Iterator i2 = values.iterator(); log.debug("Order: "); while (i1.hasNext()) { log.debug(((DERObjectIdentifier)i1.next()).getId()); } log.debug("Values: "); while (i2.hasNext()) { log.debug((String)i2.next()); } } */ //log.debug("<stringToBcX509Name"); return new X509Name(ordering, values); }