List of usage examples for org.bouncycastle.asn1.x509 BasicConstraints BasicConstraints
public BasicConstraints(int pathLenConstraint)
From source file:at.ac.tuwien.ifs.tita.business.security.TiTASecurity.java
License:Apache License
/** * Generates a fresh Certificate for a Users KeyPair. * //from w w w . ja va2 s . c o m * @param pair the KeyPair to create a Certificate for. * @param userName the Issuer of the Certificate * @return a 10 Year valid Certificate for the User. * @throws TiTASecurityException If an error occurs during the generation Process. */ private static X509Certificate generateV3Certificate(KeyPair pair, String userName) throws TiTASecurityException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=" + userName + " Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALID_TIME_RANGE)); certGen.setSubjectDN(new X500Principal("CN=" + userName + " Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); 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)); X509Certificate targetCertificate = null; try { targetCertificate = certGen.generate(pair.getPrivate(), "BC"); } catch (NoSuchProviderException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Specified provider was not found.\n" + e.getMessage()); } catch (NoSuchAlgorithmException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Specified algorithm was not found.\n" + e.getMessage()); } catch (SignatureException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Signature is not valid.\n" + e.getMessage()); } catch (CertificateEncodingException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". Wrong encoding for Signature.\n" + e.getMessage()); } catch (InvalidKeyException e) { log.error("Could create a certificate for: " + userName + "."); throw new TiTASecurityException("Error while Generating a Certificate for: " + userName + ". The Key is not valid.\n" + e.getMessage()); } return targetCertificate; }
From source file:at.asitplus.regkassen.core.modules.signature.rawsignatureprovider.NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule.java
License:Apache License
public void intialise() { try {// ww w. j a v a 2 s .c om //create random demonstration ECC keys final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC"); kpg.initialize(256); //256 bit ECDSA key //create a key pair for the demo Certificate Authority final KeyPair caKeyPair = kpg.generateKeyPair(); //create a key pair for the signature certificate, which is going to be used to sign the receipts final KeyPair signingKeyPair = kpg.generateKeyPair(); //get references to private keys for the CA and the signing key final PrivateKey caKey = caKeyPair.getPrivate(); signingKey = signingKeyPair.getPrivate(); //create CA certificate and add it to the certificate chain //NOTE: DO NEVER EVER USE IN A REAL CASHBOX, THIS IS JUST FOR DEMONSTRATION PURPOSES //NOTE: these certificates have random values, just for the demonstration purposes here //However, for testing purposes the most important feature is the EC256 Signing Key, since this is required //by the RK Suite final X509v3CertificateBuilder caBuilder = new X509v3CertificateBuilder(new X500Name("CN=RegKassa ZDA"), BigInteger.valueOf(new SecureRandom().nextLong()), new Date(System.currentTimeMillis() - 10000), new Date(System.currentTimeMillis() + 24L * 3600 * 1000), new X500Name("CN=RegKassa CA"), SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded())); caBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false)); caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); final X509CertificateHolder caHolder = caBuilder .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey)); final X509Certificate caCertificate = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(caHolder); certificateChain = new ArrayList<java.security.cert.Certificate>(); certificateChain.add(caCertificate); //create signing cert final long serialNumberCertificate = new SecureRandom().nextLong(); if (!closedSystemSignatureDevice) { serialNumberOrKeyId = Long.toHexString(serialNumberCertificate); } final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( new X500Name("CN=RegKassa CA"), BigInteger.valueOf(Math.abs(serialNumberCertificate)), new Date(System.currentTimeMillis() - 10000), new Date(System.currentTimeMillis() + 24L * 3600 * 1000), new X500Name("CN=Signing certificate"), SubjectPublicKeyInfo.getInstance(signingKeyPair.getPublic().getEncoded())); certBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false)); certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); final X509CertificateHolder certHolder = certBuilder .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey)); signingCertificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } catch (final OperatorCreationException e) { e.printStackTrace(); } catch (final CertIOException e) { e.printStackTrace(); } catch (final CertificateException e) { e.printStackTrace(); } }
From source file:be.fedict.trust.test.PKITestUtils.java
License:Open Source License
public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, DateTime notBefore, DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage, String signatureAlgorithm, boolean tsa, boolean includeSKID, boolean includeAKID, PublicKey akidPublicKey, String certificatePolicy, Boolean qcCompliance, boolean ocspResponder, boolean qcSSCD) throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, OperatorCreationException { X500Name issuerName;//from w ww. j a v a 2 s . c om if (null != issuerCertificate) { issuerName = new X500Name(issuerCertificate.getSubjectX500Principal().toString()); } else { issuerName = new X500Name(subjectDn); } X500Name subjectName = new X500Name(subjectDn); BigInteger serial = new BigInteger(128, new SecureRandom()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded()); X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerName, serial, notBefore.toDate(), notAfter.toDate(), subjectName, publicKeyInfo); JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); if (includeSKID) { x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(subjectPublicKey)); } if (includeAKID) { PublicKey authorityPublicKey; if (null != akidPublicKey) { authorityPublicKey = akidPublicKey; } else if (null != issuerCertificate) { authorityPublicKey = issuerCertificate.getPublicKey(); } else { authorityPublicKey = subjectPublicKey; } x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(authorityPublicKey)); } if (caFlag) { if (-1 == pathLength) { x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(2147483647)); } else { x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(pathLength)); } } if (null != crlUri) { GeneralName generalName = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(crlUri)); GeneralNames generalNames = new GeneralNames(generalName); DistributionPointName distPointName = new DistributionPointName(generalNames); DistributionPoint distPoint = new DistributionPoint(distPointName, null, null); DistributionPoint[] crlDistPoints = new DistributionPoint[] { distPoint }; CRLDistPoint crlDistPoint = new CRLDistPoint(crlDistPoints); x509v3CertificateBuilder.addExtension(Extension.cRLDistributionPoints, false, crlDistPoint); } if (null != ocspUri) { GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); x509v3CertificateBuilder.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } if (null != keyUsage) { x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, keyUsage); } if (null != certificatePolicy) { ASN1ObjectIdentifier policyObjectIdentifier = new ASN1ObjectIdentifier(certificatePolicy); PolicyInformation policyInformation = new PolicyInformation(policyObjectIdentifier); x509v3CertificateBuilder.addExtension(Extension.certificatePolicies, false, new DERSequence(policyInformation)); } if (null != qcCompliance) { ASN1EncodableVector vec = new ASN1EncodableVector(); if (qcCompliance) { vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcCompliance)); } else { vec.add(new QCStatement(QCStatement.id_etsi_qcs_RetentionPeriod)); } if (qcSSCD) { vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcSSCD)); } x509v3CertificateBuilder.addExtension(Extension.qCStatements, true, new DERSequence(vec)); } if (tsa) { x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping)); } if (ocspResponder) { x509v3CertificateBuilder.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false, DERNull.INSTANCE); x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning)); } AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded()); ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(asymmetricKeyParameter); X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); byte[] encodedCertificate = x509CertificateHolder.getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(encodedCertificate)); return certificate; }
From source file:beta01.SimpleRootCA.java
/** * Build a sample V3 certificate to use as an intermediate CA certificate * @param intKey// ww w.ja v a 2 s . com * @param caKey * @param caCert * @return * @throws java.lang.Exception */ public static X509CertificateHolder buildIntermediateCert(AsymmetricKeyParameter intKey, AsymmetricKeyParameter caKey, X509CertificateHolder caCert) throws Exception { SubjectPublicKeyInfo intKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(intKey); X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD), new X500Name("CN=Test CA Certificate"), intKeyInfo); X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator()); certBldr.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert)) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(intKeyInfo)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(0)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA"); AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(caKey); return certBldr.build(signer); }
From source file:beta01.SimpleRootCA.java
/** * Build a sample V3 certificate to use as an end entity certificate *//* w w w .j a va 2 s . co m*/ public static X509CertificateHolder buildEndEntityCert(AsymmetricKeyParameter entityKey, AsymmetricKeyParameter caKey, X509CertificateHolder caCert) throws Exception { SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(entityKey); X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD), new X500Name("CN=Test End Entity Certificate"), entityKeyInfo); X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator()); certBldr.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert)) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(entityKeyInfo)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(false)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA"); AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg); ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(caKey); return certBldr.build(signer); }
From source file:ca.nrc.cadc.cred.CertUtil.java
License:Open Source License
/** * Method that generates an X509 proxy certificate * // w w w. ja va 2 s . c o m * @param csr CSR for the certificate * @param lifetime lifetime of the certificate in SECONDS * @param chain certificate used to sign the proxy certificate * @return generated proxy certificate * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws CertificateParsingException * @throws CertificateEncodingException * @throws SignatureException * @throws CertificateNotYetValidException * @throws CertificateExpiredException */ public static X509Certificate generateCertificate(PKCS10CertificationRequest csr, int lifetime, X509CertificateChain chain) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateParsingException, CertificateEncodingException, SignatureException, CertificateExpiredException, CertificateNotYetValidException { X509Certificate issuerCert = chain.getChain()[0]; PrivateKey issuerKey = chain.getPrivateKey(); Security.addProvider(new BouncyCastleProvider()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(issuerCert.getSubjectX500Principal()); // generate the proxy DN as the issuerDN + CN=random number Random rand = new Random(); String issuerDN = issuerCert.getSubjectX500Principal().getName(X500Principal.RFC2253); String delegDN = String.valueOf(Math.abs(rand.nextInt())); String proxyDn = "CN=" + delegDN + "," + issuerDN; certGen.setSubjectDN(new X500Principal(proxyDn)); // set validity GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT")); // Start date. Allow for a sixty five minute clock skew here. date.add(Calendar.MINUTE, -65); Date beforeDate = date.getTime(); for (X509Certificate currentCert : chain.getChain()) { if (beforeDate.before(currentCert.getNotBefore())) { beforeDate = currentCert.getNotBefore(); } } certGen.setNotBefore(beforeDate); // End date. // If hours = 0, then cert lifetime is set to that of user cert if (lifetime <= 0) { // set the validity of certificates as the minimum // of the certificates in the chain Date afterDate = issuerCert.getNotAfter(); for (X509Certificate currentCert : chain.getChain()) { if (afterDate.after(currentCert.getNotAfter())) { afterDate = currentCert.getNotAfter(); } } certGen.setNotAfter(afterDate); } else { // check the validity of the signing certificate date.add(Calendar.MINUTE, 5); date.add(Calendar.SECOND, lifetime); for (X509Certificate currentCert : chain.getChain()) { currentCert.checkValidity(date.getTime()); } certGen.setNotAfter(date.getTime()); } certGen.setPublicKey(csr.getPublicKey()); // TODO: should be able to get signature algorithm from the csr, but... obtuse certGen.setSignatureAlgorithm(DEFAULT_SIGNATURE_ALGORITHM); // extensions // add ProxyCertInfo extension to the new cert certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuerCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); // add the Proxy Certificate Information // I expect this code to be removed once support to proxy // certificates is provided in Bouncy Castle. // create a proxy policy // types of proxy certificate policies - see RFC3820 // impersonates the user final DERObjectIdentifier IMPERSONATION = new DERObjectIdentifier("1.3.6.1.5.5.7.21.1"); // independent // final DERObjectIdentifier INDEPENDENT = new // DERObjectIdentifier( // "1.3.6.1.5.5.7.21.2"); // defined by a policy language // final DERObjectIdentifier LIMITED = new DERObjectIdentifier( // "1.3.6.1.4.1.3536.1.1.1.9"); ASN1EncodableVector policy = new ASN1EncodableVector(); policy.add(IMPERSONATION); // pathLengthConstr (RFC3820) // The pCPathLenConstraint field, if present, specifies the // maximum // depth of the path of Proxy Certificates that can be signed by // this // Proxy Certificate. A pCPathLenConstraint of 0 means that this // certificate MUST NOT be used to sign a Proxy Certificate. If // the // pCPathLenConstraint field is not present then the maximum proxy // path // length is unlimited. End entity certificates have unlimited // maximum // proxy path lengths. // DERInteger pathLengthConstr = new DERInteger(100); // create the proxy certificate information ASN1EncodableVector vec = new ASN1EncodableVector(); // policy.add(pathLengthConstr); vec.add(new DERSequence(policy)); // OID final DERObjectIdentifier OID = new DERObjectIdentifier("1.3.6.1.5.5.7.1.14"); certGen.addExtension(OID, true, new DERSequence(vec)); return certGen.generate(issuerKey, "BC"); }
From source file:chapter6.PKCS10CertCreateExample.java
public static X509Certificate[] buildChain() throws Exception { // Create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // Create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // Validate the certification request if (request.verify("BC") == false) { System.out.println("Request failed to verify!!"); System.exit(1);// w ww. j a v a2 s.co m } // Create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded())); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); 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)); // Extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i < attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // Process extension request 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()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:chapter6.X509V3CreateExample.java
public static X509Certificate generateV3Certificate(KeyPair pair) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=Test Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X500Principal("CN=Test Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // Extension ::= SEQUENCE { // extnID OBJECT IDENTIFIER, // critical BOOLEAN DEFAULT FALSE // extnValue OCTET STRING } 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"))); return certGen.generateX509Certificate(pair.getPrivate(), CryptoDefs.Provider.BC.getName()); }
From source file:chapter7.Utils.java
/** * Generate a sample V3 certificate to use as an intermediate CA certificate. * @param intKey//from w ww . j a v a 2 s . c o m * @param caKey * @param caCert * @return * @throws Exception */ public static X509Certificate generateIntermediateCert(final PublicKey intKey, final PrivateKey caKey, final X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.ONE); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test Intermediate Certificate")); certGen.setPublicKey(intKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); return certGen.generateX509Certificate(caKey, CryptoDefs.Provider.BC.getName()); }
From source file:chapter7.Utils.java
/** * Generate a sample V3 certificate to use as an end entity certificate. * @param entityKey/*from w ww.jav a2s.c om*/ * @param caKey * @param caCert * @return * @throws Exception */ public static X509Certificate generateEndEntityCert(final PublicKey entityKey, final PrivateKey caKey, final X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.ONE); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test End Certificate")); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); 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.generateX509Certificate(caKey, CryptoDefs.Provider.BC.getName()); }