List of usage examples for org.bouncycastle.asn1.x509 X509Extensions BasicConstraints
ASN1ObjectIdentifier BasicConstraints
To view the source code for org.bouncycastle.asn1.x509 X509Extensions BasicConstraints.
Click Source Link
From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java
License:Open Source License
@Override public BasicConstraints getBasicConstraints(X509Certificate cert) { try {//from w w w. j av a2s .c om byte[] value = cert.getExtensionValue(X509Extensions.BasicConstraints.getId()); if (value == null) { return null; } return BasicConstraints.getInstance( ASN1Object.fromByteArray(((ASN1OctetString) ASN1Object.fromByteArray(value)).getOctets())); // return BasicConstraints.getInstance( ASN1Object.fromByteArray( value ) ); } catch (IOException ex) { throw new CryptoFailure("Unable to extract BasicConstraints from X509Certificate extensions", ex); } }
From source file:org.signserver.validationservice.server.ValidationTestUtils.java
License:Open Source License
public static X509Certificate genCert(String dn, String issuerdn, PrivateKey privKey, PublicKey pubKey, Date startDate, Date endDate, boolean isCA, int keyUsage, CRLDistPoint crlDistPoint) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException { X509V3CertificateGenerator certgen = new X509V3CertificateGenerator(); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno);/*from w w w. j a v a2 s.c o m*/ certgen.setSerialNumber((new java.math.BigInteger(serno)).abs()); certgen.setNotBefore(startDate); certgen.setNotAfter(endDate); certgen.setSignatureAlgorithm("SHA1WithRSA"); certgen.setSubjectDN(CertTools.stringToBcX509Name(dn)); certgen.setIssuerDN(CertTools.stringToBcX509Name(issuerdn)); certgen.setPublicKey(pubKey); // CRL Distribution point if (crlDistPoint != null) { certgen.addExtension(X509Extensions.CRLDistributionPoints, false, crlDistPoint); } // 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 (keyUsage == 0) { if (isCA == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } } else { X509KeyUsage ku = new X509KeyUsage(keyUsage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); } X509Certificate cert = certgen.generate(privKey); return cert; }
From source file:org.sufficientlysecure.keychain.pgp.PgpToX509.java
License:Open Source License
/** * Creates a self-signed certificate from a public and private key. The (critical) key-usage * extension is set up with: digital signature, non-repudiation, key-encipherment, key-agreement * and certificate-signing. The (non-critical) Netscape extension is set up with: SSL client and * S/MIME. A URI subjectAltName may also be set up. * * @param pubKey public key// ww w . ja v a 2s. c o m * @param privKey private key * @param subject subject (and issuer) DN for this certificate, RFC 2253 format preferred. * @param startDate date from which the certificate will be valid (defaults to current date and time * if null) * @param endDate date until which the certificate will be valid (defaults to current date and time * if null) * * @param subjAltNameURI URI to be placed in subjectAltName * @return self-signed certificate * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws IllegalStateException * @throws NoSuchProviderException * @throws CertificateException * @throws Exception * @author Bruno Harbulot */ public static X509Certificate createSelfSignedCert(PublicKey pubKey, PrivateKey privKey, X509Name subject, Date startDate, Date endDate, String subjAltNameURI) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException { X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.reset(); /* * Sets up the subject distinguished name. Since it's a self-signed certificate, issuer and * subject are the same. */ certGenerator.setIssuerDN(subject); certGenerator.setSubjectDN(subject); /* * Sets up the validity dates. */ if (startDate == null) { startDate = new Date(System.currentTimeMillis()); } certGenerator.setNotBefore(startDate); if (endDate == null) { endDate = new Date(startDate.getTime() + (365L * 24L * 60L * 60L * 1000L)); Log.d(Constants.TAG, "end date is=" + DateFormat.getDateInstance().format(endDate)); } certGenerator.setNotAfter(endDate); /* * The serial-number of this certificate is 1. It makes sense because it's self-signed. */ certGenerator.setSerialNumber(BigInteger.ONE); /* * Sets the public-key to embed in this certificate. */ certGenerator.setPublicKey(pubKey); /* * Sets the signature algorithm. */ String pubKeyAlgorithm = pubKey.getAlgorithm(); if (pubKeyAlgorithm.equals("DSA")) { certGenerator.setSignatureAlgorithm("SHA1WithDSA"); } else if (pubKeyAlgorithm.equals("RSA")) { certGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption"); } else { RuntimeException re = new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm); Log.e(Constants.TAG, re.getMessage(), re); throw re; } /* * Adds the Basic Constraint (CA: true) extension. */ certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); /* * Adds the subject key identifier extension. */ SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pubKey); certGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier); /* * Adds the authority key identifier extension. */ AuthorityKeyIdentifier authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(pubKey); certGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); /* * Adds the subject alternative-name extension. */ if (subjAltNameURI != null) { GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.uniformResourceIdentifier, subjAltNameURI)); certGenerator.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltNames); } /* * Creates and sign this certificate with the private key corresponding to the public key of * the certificate (hence the name "self-signed certificate"). */ X509Certificate cert = certGenerator.generate(privKey); /* * Checks that this certificate has indeed been correctly signed. */ cert.verify(pubKey); return cert; }
From source file:org.votingsystem.signature.util.CertUtils.java
License:Open Source License
/** * Generate V3 certificate for users/*from w w w.j a v a 2 s .c om*/ */ public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert, Date dateBegin, Date dateFinish, String endEntitySubjectDN) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(KeyGeneratorVS.INSTANCE.getSerno()); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setNotBefore(dateBegin); certGen.setNotAfter(dateFinish); certGen.setSubjectDN(new X500Principal(endEntitySubjectDN)); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm(ContextVS.CERT_GENERATION_SIG_ALGORITHM); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); return certGen.generate(caKey, ContextVS.PROVIDER); }
From source file:org.votingsystem.signature.util.CertUtils.java
License:Open Source License
/** * Generate V3 certificate for root CA Authority */// ww w .j a v a2 s.co m public static X509Certificate generateV3RootCert(KeyPair pair, Date dateBegin, Date dateFinish, String strSubjectDN) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); log.info("strSubjectDN: " + strSubjectDN); X509Principal x509Principal = new X509Principal(strSubjectDN); certGen.setSerialNumber(KeyGeneratorVS.INSTANCE.getSerno()); certGen.setIssuerDN(x509Principal); certGen.setNotBefore(dateBegin); certGen.setNotAfter(dateFinish); log.info("dateBegin: " + dateBegin.toString() + " - dateFinish: " + dateFinish.toString()); certGen.setSubjectDN(x509Principal); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm(ContextVS.CERT_GENERATION_SIG_ALGORITHM); //The following fragment shows how to create one which indicates that //the certificate containing it is a CA and that only one certificate can follow in the certificate path. certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true, 0)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pair.getPublic())); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); return certGen.generate(pair.getPrivate(), ContextVS.PROVIDER); }
From source file:org.votingsystem.signature.util.CertUtils.java
License:Open Source License
/** * Generate V3 certificate for TimeStamp signing *//*from w w w . jav a 2 s . c o m*/ public static X509Certificate generateTimeStampingCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert, long begin, long period, String endEntitySubjectDN) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setNotBefore(new Date(begin)); certGen.setNotAfter(new Date(begin + period)); certGen.setSubjectDN(new X500Principal(endEntitySubjectDN)); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm(ContextVS.CERT_GENERATION_SIG_ALGORITHM); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); 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(new DERSequence(KeyPurposeId.id_kp_timeStamping))); return certGen.generate(caKey, ContextVS.PROVIDER); }
From source file:org.votingsystem.signature.util.CertUtils.java
License:Open Source License
/** * Generate V3 Certificate from CSR/*from www .j a v a 2s .co m*/ */ public static X509Certificate generateV3EndEntityCertFromCsr(PKCS10CertificationRequest csr, PrivateKey caKey, X509Certificate caCert, Date dateBegin, Date dateFinish, String strSubjectDN, DERTaggedObject... certExtensions) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); PublicKey requestPublicKey = csr.getPublicKey(); X509Principal x509Principal = new X509Principal(strSubjectDN); certGen.setSerialNumber(KeyGeneratorVS.INSTANCE.getSerno()); log.info("generateV3EndEntityCertFromCsr - SubjectX500Principal(): " + caCert.getSubjectX500Principal()); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setNotBefore(dateBegin); certGen.setNotAfter(dateFinish); certGen.setSubjectDN(x509Principal); certGen.setPublicKey(requestPublicKey); certGen.setSignatureAlgorithm(ContextVS.CERT_GENERATION_SIG_ALGORITHM); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(requestPublicKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));//Certificado final certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); ASN1Set attributes = csr.getCertificationRequestInfo().getAttributes(); if (attributes != null) { for (int i = 0; i != attributes.size(); i++) { if (attributes.getObjectAt(i) instanceof DERTaggedObject) { DERTaggedObject taggedObject = (DERTaggedObject) attributes.getObjectAt(i); ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier( ContextVS.VOTING_SYSTEM_BASE_OID + taggedObject.getTagNo()); certGen.addExtension(oid, true, taggedObject); } else { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } } } if (certExtensions != null) { for (DERTaggedObject taggedObject : certExtensions) { if (taggedObject != null) { ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier( ContextVS.VOTING_SYSTEM_BASE_OID + taggedObject.getTagNo()); certGen.addExtension(oid, true, taggedObject); } log.log(Level.FINE, "null taggedObject"); } } X509Certificate cert = certGen.generate(caKey, ContextVS.PROVIDER); cert.verify(caCert.getPublicKey()); return cert; }
From source file:org.xwiki.crypto.x509.internal.X509Keymaker.java
License:Open Source License
/** * Create a new X509 client certificate. * * @param forCert the public key which will be embedded in the certificate, whoever has the matching private key * "owns" the certificate. * @param toSignWith the private key in this pair will be used to sign the certificate. * @param daysOfValidity number of days the cert should be valid for. * @param nonRepudiable this should only be true if the private key is not stored on the server. * @param webId the URI to put as the alternative name (for FOAFSSL webId compatibility) * @param userName a String representation of the name of the user getting the certificate. * @return a new X509 certificate./*from w ww . ja v a 2 s . c o m*/ * @throws GeneralSecurityException if something goes wrong. */ public synchronized X509Certificate makeClientCertificate(final PublicKey forCert, final KeyPair toSignWith, final int daysOfValidity, final boolean nonRepudiable, final String webId, final String userName) throws GeneralSecurityException { try { // the UID (same for issuer since this certificate confers no authority) final X509Name dName = new X509Name("UID=" + userName); this.prepareGenericCertificate(forCert, daysOfValidity, dName, dName); // Not a CA certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); // Client cert certGenerator.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime)); // Key Usage extension. int keyUsage = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement; if (nonRepudiable) { keyUsage |= KeyUsage.nonRepudiation; } certGenerator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage)); // Set the authority key identifier to be the CA key which we are using. certGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(toSignWith.getPublic())); // FOAFSSL compatibility. final GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.uniformResourceIdentifier, webId)); certGenerator.addExtension(X509Extensions.SubjectAlternativeName, true, subjectAltNames); return this.generate(toSignWith); } finally { // Clean up after ourselves so that it is more difficult to try to extract private keys from the heap. this.certGenerator.reset(); } }
From source file:org.xwiki.crypto.x509.internal.X509Keymaker.java
License:Open Source License
/** * Create a new self signed X509 certificate authority certificate. * * @param keyPair the public key will appear in the certificate and the private key will be used to sign it. * @param daysOfValidity number of days the cert should be valid for. * @param commonName what to put in the common name field, this field will identify this certificate authority * in the list on the user's browser. * @return a new X509 certificate authority. * @throws GeneralSecurityException if something goes wrong. *///from w w w. jav a2 s . c o m public synchronized X509Certificate makeCertificateAuthority(final KeyPair keyPair, final int daysOfValidity, final String commonName) throws GeneralSecurityException { try { final X509Name name = new X509Name(new Vector<DERObjectIdentifier>() { { this.add(X509Name.O); this.add(X509Name.CN); } }, new Vector<String>() { { this.add(X509Keymaker.CA_ORGANIZATION_NAME); this.add(commonName); } }); this.prepareGenericCertificate(keyPair.getPublic(), daysOfValidity, name, name); // This authority can't sign other CA's. certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); // Allow certificate signing only. certGenerator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.keyCertSign)); // Adds the subject key identifier extension. Self singed so uses it's own key. certGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); return this.generate(keyPair); } finally { // Clean up after ourselves so that it is more difficult to try to extract private keys from the heap. this.certGenerator.reset(); } }
From source file:sernet.verinice.encryption.test.CryptoTest.java
License:Open Source License
X509Certificate generateCertificate(String dn, KeyPair pair, int days) throws GeneralSecurityException, IOException { PublicKey publicKey = pair.getPublic(); PrivateKey privateKey = pair.getPrivate(); if (publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPk = (RSAPublicKey) publicKey; RSAPublicKeySpec rsaPkSpec = new RSAPublicKeySpec(rsaPk.getModulus(), rsaPk.getPublicExponent()); try {// w w w.j a v a2 s. c o m publicKey = KeyFactory.getInstance("RSA").generatePublic(rsaPkSpec); } catch (InvalidKeySpecException e) { publicKey = pair.getPublic(); } } if (privateKey instanceof RSAPrivateKey) { RSAPrivateKey rsaPk = (RSAPrivateKey) privateKey; RSAPrivateKeySpec rsaPkSpec = new RSAPrivateKeySpec(rsaPk.getModulus(), rsaPk.getPrivateExponent()); try { privateKey = KeyFactory.getInstance("RSA").generatePrivate(rsaPkSpec); } catch (InvalidKeySpecException e) { privateKey = pair.getPrivate(); } } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); String commonName = "CN=" + dn + ", OU=None, O=None L=None, C=None"; X500Principal dnName = new X500Principal(commonName); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(dnName); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); cal.add(Calendar.YEAR, 5); certGen.setNotAfter(cal.getTime()); certGen.setSubjectDN(dnName); certGen.setPublicKey(publicKey); certGen.setSignatureAlgorithm("MD5WithRSA"); return certGen.generate(privateKey, BouncyCastleProvider.PROVIDER_NAME); }