List of usage examples for org.bouncycastle.asn1.x509 X509Extensions CertificatePolicies
ASN1ObjectIdentifier CertificatePolicies
To view the source code for org.bouncycastle.asn1.x509 X509Extensions CertificatePolicies.
Click Source Link
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 w w. j a 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.ejbca.util.CertTools.java
License:Open Source License
/** * Get a certificate policy ID from a certificate policies extension * * @param cert certificate containing the extension * @param pos position of the policy id, if several exist, the first is as pos 0 * @return String with the certificate policy OID * @throws IOException if extension can not be parsed *///w ww. java 2s . c o m public static String getCertificatePolicyId(Certificate cert, int pos) throws IOException { String ret = null; if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; byte[] extvalue = x509cert.getExtensionValue(X509Extensions.CertificatePolicies.getId()); if (extvalue == null) { return null; } DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)) .readObject()); ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())) .readObject(); // Check the size so we don't ArrayIndexOutOfBounds if (seq.size() < pos + 1) { return null; } PolicyInformation pol = new PolicyInformation((ASN1Sequence) seq.getObjectAt(pos)); ret = pol.getPolicyIdentifier().getId(); } return ret; }
From source file:org.glite.slcs.pki.CertificateExtensionFactory.java
License:eu-egee.org license
/** * Creates a CertificateExtension. The id can be the OID or the name as * defined below. The values is a comma separated list of value(s) * <p>/* ww w .j av a 2 s.co m*/ * Valid names and values: * <ul> * <li>KeyUsage * <ul> * <li>DigitalSignature * <li>NonRepudiation * <li>KeyEncipherment * <li>DataEncipherment * <li>KeyAgreement * <li>KeyCertSign * <li>CRLSign * <li>EncipherOnly * <li>DecipherOnly * </ul> * <li>ExtendedKeyUsage * <ul> * <li>AnyExtendedKeyUsage * <li>ServerAuth * <li>ClientAuth * <li>CodeSigning * <li>EmailProtection * <li>IPSecEndSystem * <li>IPSecTunnel * <li>IPSecUser * <li>OCSPSigning * <li>Smartcardlogon * </ul> * <li>CertificatePolicies * <ul> * <li>The policy OID(s) * </ul> * <li>SubjectAltName * <ul> * <li>email:EMAIL_ADDRESS * <li>dns:HOSTNAME * </ul> * </ul> * <p> * Example: * <pre> * CertificateExtension keyUsageExtension = * CertificateExtensionFactory.createCertificateExtension("KeyUsage", "DigitalSignature,KeyEncipherment"); * CertificateExtension subjectAltNameExtension = * CertificateExtensionFactory.createCertificateExtension("SubjectAltName", "email:john.doe@example.com,dns:www.exmaple.com"); * </pre> * * @param id * The name or the OID of the extension. * @param values * A comma separated list of extension value(s). * @return The corresponding CertificateExtension or <code>null</code> if * the id (name or oid) is not supported. */ static public CertificateExtension createCertificateExtension(String id, String values) { if (LOG.isDebugEnabled()) { LOG.debug("id:" + id + " value(s):" + values); } if (id.equals(X509Extensions.KeyUsage.getId()) || id.equalsIgnoreCase("KeyUsage")) { // parse the comma separated list of key usage int usage = 0; StringTokenizer st = new StringTokenizer(values, ","); while (st.hasMoreElements()) { String keyUsage = (String) st.nextElement(); keyUsage = keyUsage.trim(); if (keyUsage.equalsIgnoreCase("DigitalSignature")) { usage += KeyUsage.digitalSignature; } else if (keyUsage.equalsIgnoreCase("NonRepudiation")) { usage += KeyUsage.nonRepudiation; } else if (keyUsage.equalsIgnoreCase("KeyEncipherment")) { usage += KeyUsage.keyEncipherment; } else if (keyUsage.equalsIgnoreCase("DataEncipherment")) { usage += KeyUsage.dataEncipherment; } else if (keyUsage.equalsIgnoreCase("KeyAgreement")) { usage += KeyUsage.keyAgreement; } else if (keyUsage.equalsIgnoreCase("KeyCertSign")) { usage += KeyUsage.keyCertSign; } else if (keyUsage.equalsIgnoreCase("CRLSign")) { usage += KeyUsage.cRLSign; } else if (keyUsage.equalsIgnoreCase("EncipherOnly")) { usage += KeyUsage.encipherOnly; } else if (keyUsage.equalsIgnoreCase("DecipherOnly")) { usage += KeyUsage.decipherOnly; } else { LOG.error("Unknown KeyUsage: " + keyUsage); } } return createKeyUsageExtension(usage, values); } else if (id.equals(X509Extensions.ExtendedKeyUsage.getId()) || id.equalsIgnoreCase("ExtendedKeyUsage")) { // value is a comma separated list of keyPurpose Vector keyPurposeIds = new Vector(); StringTokenizer st = new StringTokenizer(values, ","); while (st.hasMoreElements()) { String keyPurpose = (String) st.nextElement(); keyPurpose = keyPurpose.trim(); if (keyPurpose.equalsIgnoreCase("AnyExtendedKeyUsage")) { keyPurposeIds.add(KeyPurposeId.anyExtendedKeyUsage); } else if (keyPurpose.equalsIgnoreCase("ServerAuth")) { keyPurposeIds.add(KeyPurposeId.id_kp_serverAuth); } else if (keyPurpose.equalsIgnoreCase("ClientAuth")) { keyPurposeIds.add(KeyPurposeId.id_kp_clientAuth); } else if (keyPurpose.equalsIgnoreCase("CodeSigning")) { keyPurposeIds.add(KeyPurposeId.id_kp_codeSigning); } else if (keyPurpose.equalsIgnoreCase("EmailProtection")) { keyPurposeIds.add(KeyPurposeId.id_kp_emailProtection); } else if (keyPurpose.equalsIgnoreCase("IPSecEndSystem")) { keyPurposeIds.add(KeyPurposeId.id_kp_ipsecEndSystem); } else if (keyPurpose.equalsIgnoreCase("IPSecTunnel")) { keyPurposeIds.add(KeyPurposeId.id_kp_ipsecTunnel); } else if (keyPurpose.equalsIgnoreCase("IPSecUser")) { keyPurposeIds.add(KeyPurposeId.id_kp_ipsecUser); } else if (keyPurpose.equalsIgnoreCase("TimeStamping")) { keyPurposeIds.add(KeyPurposeId.id_kp_timeStamping); } else if (keyPurpose.equalsIgnoreCase("OCSPSigning")) { keyPurposeIds.add(KeyPurposeId.id_kp_OCSPSigning); } else if (keyPurpose.equalsIgnoreCase("Smartcardlogon")) { keyPurposeIds.add(KeyPurposeId.id_kp_smartcardlogon); } else { LOG.error("Unknown ExtendedKeyUsage: " + keyPurpose); } } return createExtendedKeyUsageExtension(keyPurposeIds, values); } else if (id.equals(X509Extensions.CertificatePolicies.getId()) || id.equalsIgnoreCase("CertificatePolicies")) { // values is a comma separated list of policyOIDs Vector policyOIDs = new Vector(); StringTokenizer st = new StringTokenizer(values, ","); while (st.hasMoreElements()) { String policyOID = (String) st.nextElement(); policyOID = policyOID.trim(); policyOIDs.add(policyOID); } return createCertificatePoliciesExtension(policyOIDs, values); } else if (id.equals(X509Extensions.SubjectAlternativeName.getId()) || id.equalsIgnoreCase("SubjectAltName")) { // values is a comma separated list of altername names prefixed with // the type (email: or dns:) Vector typedSubjectAltNames = new Vector(); StringTokenizer st = new StringTokenizer(values, ","); while (st.hasMoreElements()) { String typedAltName = (String) st.nextElement(); typedAltName = typedAltName.trim(); typedSubjectAltNames.add(typedAltName); } return createSubjectAltNameExtension(typedSubjectAltNames, values); } LOG.error("Unsupported CertificateExtension: " + id); return null; }
From source file:org.glite.slcs.pki.CertificateExtensionFactory.java
License:eu-egee.org license
/** * Creates a Cerificate Policies: policyOID extension with the given policy * OID./* w w w.jav a2 s . c o m*/ * * @param policyOID * The policy OID (2.16.756.1.2.*) * @return The certificate policies CertificateExtension. */ static protected CertificateExtension createCertificatePoliciesExtension(String policyOID) { DERObjectIdentifier policyIdentifier = new DERObjectIdentifier(policyOID); PolicyInformation policyInformation = new PolicyInformation(policyIdentifier); DERSequence certificatePolicies = new DERSequence(policyInformation); X509Extension certificatePoliciesExtension = new X509Extension(false, new DEROctetString(certificatePolicies)); return new CertificateExtension(X509Extensions.CertificatePolicies, "CertificatePolicies", certificatePoliciesExtension, policyOID); }
From source file:org.glite.slcs.pki.CertificateExtensionFactory.java
License:eu-egee.org license
/** * // ww w .ja va 2 s . c o m * @param policyOIDs * @param values * @return */ static protected CertificateExtension createCertificatePoliciesExtension(Vector policyOIDs, String values) { ASN1EncodableVector policyInformations = new ASN1EncodableVector(); Enumeration pOids = policyOIDs.elements(); while (pOids.hasMoreElements()) { String policyOid = (String) pOids.nextElement(); DERObjectIdentifier policyIdentifier = new DERObjectIdentifier(policyOid); PolicyInformation policyInformation = new PolicyInformation(policyIdentifier); policyInformations.add(policyInformation); } DERSequence certificatePolicies = new DERSequence(policyInformations); X509Extension certificatePoliciesExtension = new X509Extension(false, new DEROctetString(certificatePolicies)); return new CertificateExtension(X509Extensions.CertificatePolicies, "CertificatePolicies", certificatePoliciesExtension, values); }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
/** * DOCUMENT ME!/* w w w . j a v a2 s. c o m*/ * * @param dn DOCUMENT ME! * @param validity DOCUMENT ME! * @param policyId DOCUMENT ME! * @param privKey DOCUMENT ME! * @param pubKey DOCUMENT ME! * @param isCA DOCUMENT ME! * * @return DOCUMENT ME! * * @throws NoSuchAlgorithmException DOCUMENT ME! * @throws SignatureException DOCUMENT ME! * @throws InvalidKeyException DOCUMENT ME! * @throws IllegalStateException * @throws CertificateEncodingException */ public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException { // Create self signed certificate String sigAlg = "SHA1WithRSA"; 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(); // 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(pubKey); // 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 == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; 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 Mozilla. try { if (isCA == true) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.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); return selfcert; }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
public static X509Certificate genCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, boolean isCA, String caDn, PrivateKey caPrivateKey, PublicKey acPubKey) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException, IllegalStateException {/*from w ww . j ava 2s. co m*/ // Create self signed certificate String sigAlg = "SHA1WithRSA"; 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(); // 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(caDn)); certgen.setPublicKey(pubKey); // 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 (false) { //if (isCA == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; 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 Mozilla. try { if (false) { //if (isCA == true) { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())) .readObject()); SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(acPubKey.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 cert = certgen.generate(caPrivateKey); return cert; }
From source file:org.objectweb.proactive.core.security.CertTools.java
License:Open Source License
/** * Get a certificate policy ID from a certificate policies extension * * @param cert certificate containing the extension * @param pos position of the policy id, if several exist, the first is as pos 0 * @return String with the certificate policy OID * @throws IOException if extension can not be parsed *///www . j a va 2s. co m public static String getCertificatePolicyId(X509Certificate cert, int pos) throws IOException { byte[] extvalue = cert.getExtensionValue(X509Extensions.CertificatePolicies.getId()); if (extvalue == null) { return null; } DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)) .readObject()); ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())) .readObject(); // Check the size so we don't ArrayIndexOutOfBounds if (seq.size() < (pos + 1)) { return null; } PolicyInformation pol = new PolicyInformation((ASN1Sequence) seq.getObjectAt(pos)); String id = pol.getPolicyIdentifier().getId(); return id; }
From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java
License:Open Source License
@Override public Set<PolicyInformation> getCertificatePolicies(X509Certificate cert) { try {/*from w w w. ja va 2 s. c o m*/ byte[] value = cert.getExtensionValue(X509Extensions.CertificatePolicies.getId()); if (value == null) { return Collections.emptySet(); } ASN1Sequence policiesSequence = (ASN1Sequence) ASN1Object.fromByteArray(value); Set<PolicyInformation> certPolicies = new LinkedHashSet<PolicyInformation>(); for (int idx = 0; idx < policiesSequence.size(); idx++) { PolicyInformation policy = PolicyInformation.getInstance(policiesSequence.getObjectAt(idx)); certPolicies.add(policy); } return certPolicies; } catch (IOException ex) { throw new CryptoFailure("Unable to extract CertificatePolicies from X509Certificate extensions", ex); } }