List of usage examples for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder
public JcaContentSignerBuilder(String signatureAlgorithm)
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
@Test public void testGetOcspResponseWithIncorrectDefaultResponder() throws Exception { // Set a fake value GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); ocspConfiguration.setOcspDefaultResponderReference("CN=FancyPants"); globalConfigurationSession.saveConfiguration(authenticationToken, ocspConfiguration); cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNATUREREQUIRED, "true"); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), ocspSigningCertificate, ocspSigningCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); //Create a signed request in order to test all aspects KeyPair keys = KeyTools.genKeys("512", "RSA"); // Issue a certificate to a test user final String endEntityName = "testGetOcspResponseWithIncorrectDefaultResponder"; final EndEntityInformation user = new EndEntityInformation(endEntityName, "CN=" + endEntityName, x509ca.getCAId(), null, null, new EndEntityType(EndEntityTypes.ENDUSER), 1, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityConstants.TOKEN_USERGEN, 0, null); user.setStatus(EndEntityConstants.STATUS_NEW); user.setPassword("foo123"); final SimpleRequestMessage certreq = new SimpleRequestMessage(keys.getPublic(), user.getUsername(), user.getPassword());// ww w . ja va 2 s . co m final X509ResponseMessage resp = (X509ResponseMessage) certificateCreateSession.createCertificate( authenticationToken, user, certreq, X509ResponseMessage.class, signSession.fetchCertGenParams()); final X509Certificate ocspTestCert = (X509Certificate) resp.getCertificate(); X509CertificateHolder chain[] = new JcaX509CertificateHolder[2]; chain[0] = new JcaX509CertificateHolder(ocspTestCert); chain[1] = new JcaX509CertificateHolder(caCertificate); gen.setRequestorName(chain[0].getSubject()); OCSPReq req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480), chain); //Now delete the original CA, making this test completely standalone. OcspTestUtils.deleteCa(authenticationToken, x509ca); activateKeyBinding(internalKeyBindingId); ocspResponseGeneratorSession.reloadOcspSigningCache(); try { final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); //We're expecting back an unsigned reply saying unauthorized, as per RFC2690 Section 2.3 assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not OCSPRespBuilder.UNAUTHORIZED.", response.getStatus(), OCSPRespBuilder.UNAUTHORIZED); assertNull("Response should not have contained a response object.", response.getResponseObject()); } finally { try { if (ocspTestCert != null) internalCertificateStoreSession.removeCertificate(ocspTestCert); } catch (Exception e) { //NOPMD: Ignore } cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNATUREREQUIRED, "false"); } }
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
/** * Build an OCSP request, that will optionally be signed if authentication parameters are specified * /* ww w . ja va2 s .c om*/ * @param ocspAuthenticationCertificate signing certificate * @param ocspAuthenticationPrivateKey private key to sign with * @param caCertificate issuer of the queried certificate * @param certificateSerialnumber serial number of the certificate to be queried * @return * @throws Exception */ private OCSPReq buildOcspRequest(final X509Certificate ocspAuthenticationCertificate, final PrivateKey ocspAuthenticationPrivateKey, final X509Certificate caCertificate, final BigInteger certificateSerialnumber) throws Exception { final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); if (ocspAuthenticationCertificate != null) { // Signed requests are required to have an OCSPRequest.TBSRequest.requestorName ocspReqBuilder.setRequestorName(new X500Name(ocspAuthenticationCertificate.getSubjectDN().getName())); } ocspReqBuilder.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, certificateSerialnumber)); ocspReqBuilder.setRequestExtensions( new Extensions(new Extension[] { new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())) })); if (ocspAuthenticationCertificate != null && ocspAuthenticationPrivateKey != null) { // Create a signed request final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspAuthenticationPrivateKey), 20480); return ocspReqBuilder.build(signer, new X509CertificateHolder[] { new X509CertificateHolder(ocspAuthenticationCertificate.getEncoded()) }); } else { // Create an unsigned request return ocspReqBuilder.build(); } }
From source file:org.cesecore.keys.util.KeyStoreTools.java
License:Open Source License
private X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair) throws InvalidKeyException, CertificateException { final long currentTime = new Date().getTime(); final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000); final Date lastDate = new Date(currentTime + validity * 1000); final X500Name issuer = new X500Name(myname); final BigInteger serno = BigInteger.valueOf(firstDate.getTime()); final PublicKey publicKey = keyPair.getPublic(); if (publicKey == null) { throw new InvalidKeyException("Public key is null"); }//from w w w. j a va 2 s . co m try { final X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder(issuer, serno, firstDate, lastDate, issuer, publicKey); log.debug("Keystore signing algorithm " + sigAlg); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(this.providerName).build(keyPair.getPrivate()), 20480); final X509CertificateHolder cert = cg.build(signer); return (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded()); } catch (OperatorCreationException e) { log.error("Error creating content signer: ", e); throw new CertificateException(e); } catch (IOException e) { throw new CertificateException("Could not read certificate", e); } }
From source file:org.cesecore.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, Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder, List<Extension> additionalExtensions) throws CertificateParsingException, IOException, OperatorCreationException { // 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))); // 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;// ww w . j a va 2s. 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; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("RSA was not a known algorithm", e); } } 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" final String algo = ecpk.getAlgorithm(); if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { try { publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("ECGOST3410 was not a known algorithm", e); } } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) { try { publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("DSTU4145 was not a known algorithm", e); } } else { try { publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("EC was not a known algorithm", e); } } } 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; try { random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA1PRNG was not a known algorithm", e); } random.setSeed(new Date().getTime()); random.nextBytes(serno); SubjectPublicKeyInfo pkinfo; try { pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); } catch (IOException e) { throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e); } X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA || keyusage != 0) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) { final ASN1EncodableVector v = new ASN1EncodableVector(); if (privateKeyNotBefore != null) { v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore))); } if (privateKeyNotAfter != null) { v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter))); } certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v)); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream sAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream aAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) sAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) aAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { sAsn1InputStream.close(); aAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } // Add any additional if (additionalExtensions != null) { for (final Extension extension : additionalExtensions) { certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue()); } } final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }
From source file:org.cesecore.util.CertTools.java
License:Open Source License
/** * Generates a PKCS10CertificationRequest * /*w w w .j a va 2 s . c o m*/ * Code Example: * ------------- * An example of putting AltName and a password challenge in an 'attributes' set (taken from RequestMessageTest.test01Pkcs10RequestMessage() ): * * {@code * // Create a P10 with extensions, in this case altNames with a DNS name * ASN1EncodableVector altnameattr = new ASN1EncodableVector(); * altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); * // AltNames * GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo1.bar.com"); * ExtensionsGenerator extgen = new ExtensionsGenerator(); * extgen.addExtension(Extension.subjectAlternativeName, false, san ); * Extensions exts = extgen.generate(); * altnameattr.add(new DERSet(exts)); * * // Add a challenge password as well * ASN1EncodableVector pwdattr = new ASN1EncodableVector(); * pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); * ASN1EncodableVector pwdvalues = new ASN1EncodableVector(); * pwdvalues.add(new DERUTF8String("foo123")); * pwdattr.add(new DERSet(pwdvalues)); * * // Complete the Attribute section of the request, the set (Attributes) * // contains one sequence (Attribute) * ASN1EncodableVector v = new ASN1EncodableVector(); * v.add(new DERSequence(altnameattr)); * v.add(new DERSequence(pwdattr)); * DERSet attributes = new DERSet(v); * } * * @param signatureAlgorithm * @param subject The request's subjectDN * @param publickey the public key for the certificate requesting signing * @param attributes A set of attributes, for example, extensions, challenge password, etc. * @param privateKey the private key used to generate the certificate * @param provider * @return a PKCS10CertificateRequest based on the input parameters. * * @throws OperatorCreationException if an error occurred while creating the signing key */ public static PKCS10CertificationRequest genPKCS10CertificationRequest(String signatureAlgorithm, X500Name subject, PublicKey publickey, ASN1Set attributes, PrivateKey privateKey, String provider) throws OperatorCreationException { ContentSigner signer; CertificationRequestInfo reqInfo; try { ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(publickey.getEncoded()); SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(seq); reqInfo = new CertificationRequestInfo(subject, pkinfo, attributes); if (provider == null) { provider = BouncyCastleProvider.PROVIDER_NAME; } signer = new BufferingContentSigner( new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider).build(privateKey), 20480); signer.getOutputStream().write(reqInfo.getEncoded(ASN1Encoding.DER)); signer.getOutputStream().flush(); } catch (IOException e) { throw new IllegalStateException("Unexpected IOException was caught.", e); } byte[] sig = signer.getSignature(); DERBitString sigBits = new DERBitString(sig); CertificationRequest req = new CertificationRequest(reqInfo, signer.getAlgorithmIdentifier(), sigBits); return new PKCS10CertificationRequest(req); }
From source file:org.cloudfoundry.identity.uaa.util.SocketUtils.java
License:Open Source License
public static X509Certificate getSelfCertificate(KeyPair keyPair, String organisation, String orgUnit, String commonName, Date issueDate, long validForSeconds, String signatureAlgorithm) throws CertificateException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, NoSuchProviderException { try {//ww w .ja v a 2 s . co m Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.OU, orgUnit); builder.addRDN(BCStyle.O, organisation); builder.addRDN(BCStyle.CN, commonName); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); Date notAfter = new DateTime(issueDate).plusSeconds((int) validForSeconds).toDate(); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(), serial, issueDate, notAfter, builder.build(), keyPair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC) .build(keyPair.getPrivate()); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(certGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); return cert; } catch (OperatorCreationException ioe) { throw new CertificateEncodingException( "Error during creation of self-signed Certificate: " + ioe.getMessage(), ioe); } }
From source file:org.codice.ddf.security.certificate.generator.CertificateAuthority.java
License:Open Source License
ContentSigner getContentSigner() { try {//from w ww . java2s . co m return new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(BouncyCastleProvider.PROVIDER_NAME) .build(getPrivateKey()); } catch (Exception e) { throw new CertificateGeneratorException("Cannot create content signer of certificate authority", e); } }
From source file:org.computerist.ssltools.zap.FixedSslCertificateService.java
License:Apache License
public KeyStore createCertForHost(String hostname) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException { if (hostname == null) { throw new IllegalArgumentException("Error, 'hostname' is not allowed to be null!"); }/*from w w w. ja v a 2s . com*/ if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) { throw new RuntimeException( this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one."); } final KeyPair mykp = this.createKeyPair(); final PrivateKey privKey = mykp.getPrivate(); final PublicKey pubKey = mykp.getPublic(); X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); namebld.addRDN(BCStyle.CN, hostname); namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project"); namebld.addRDN(BCStyle.O, "OWASP"); namebld.addRDN(BCStyle.C, "xx"); namebld.addRDN(BCStyle.EmailAddress, "owasp-zed-attack-proxy@lists.owasp.org"); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder( new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + 100 * (1000L * 60 * 60 * 24 * 30)), namebld.build(), pubKey); certGen.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); certGen.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); ContentSigner sigGen; try { sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivKey); } catch (OperatorCreationException e) { throw new CertificateException(e); } final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(caPubKey); final Certificate[] chain = new Certificate[2]; chain[1] = this.caCert; chain[0] = cert; userKs.setKeyEntry(hostname, privKey, PASSPHRASE, chain); return userKs; }
From source file:org.computerist.ssltools.zap.ZapSslCertificateUtils.java
License:Apache License
/** * Creates a new Root CA certificate and returns private and public key as * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used. * * @return// w w w. j av a2 s. c om * @throws NoSuchAlgorithmException If no providers are found * for 'RSA' key pair generator * or 'SHA1PRNG' Secure random number generator * @throws IllegalStateException in case of errors during assembling {@link KeyStore} */ public static final KeyStore createRootCA() throws NoSuchAlgorithmException { final Date startDate = Calendar.getInstance().getTime(); final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L)); final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA"); g.initialize(2048, SecureRandom.getInstance("SHA1PRNG")); final KeyPair keypair = g.genKeyPair(); final PrivateKey privKey = keypair.getPrivate(); final PublicKey pubKey = keypair.getPublic(); Random rnd = new Random(); // using the hash code of the user's name and home path, keeps anonymity // but also gives user a chance to distinguish between each other X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA"); namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode())); namebld.addRDN(BCStyle.O, "OWASP Root CA"); namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA"); namebld.addRDN(BCStyle.C, "xx"); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey); KeyStore ks = null; try { certGen.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true)); certGen.addExtension(X509Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)); Vector<DERObject> eku = new Vector<>(3, 1); eku.add(KeyPurposeId.id_kp_serverAuth); eku.add(KeyPurposeId.id_kp_clientAuth); eku.add(KeyPurposeId.anyExtendedKeyUsage); certGen.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku)); final ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC") .build(privKey); final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certGen.build(sigGen)); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setKeyEntry(FixedSslCertificateService.ZAPROXY_JKS_ALIAS, privKey, FixedSslCertificateService.PASSPHRASE, new Certificate[] { cert }); } catch (final Exception e) { throw new IllegalStateException("Errors during assembling root CA.", e); } return ks; }
From source file:org.conscrypt.java.security.TestKeyStore.java
License:Apache License
private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints, BigInteger serialNumber) throws Exception { // Note that there is no way to programmatically make a // Certificate using java.* or javax.* APIs. The // CertificateFactory interface assumes you want to read // in a stream of bytes, typically the X.509 factory would // allow ASN.1 DER encoded bytes and optionally some PEM // formats. Here we use Bouncy Castle's // X509V3CertificateGenerator and related classes. long millisPerDay = 24 * 60 * 60 * 1000; long now = System.currentTimeMillis(); Date start = new Date(now - millisPerDay); Date end = new Date(now + millisPerDay); String keyAlgorithm = privateKey.getAlgorithm(); String signatureAlgorithm;/*from ww w . j ava 2 s .co m*/ if (keyAlgorithm.equals("RSA")) { signatureAlgorithm = "sha256WithRSA"; } else if (keyAlgorithm.equals("DSA")) { signatureAlgorithm = "sha256WithDSA"; } else if (keyAlgorithm.equals("EC")) { signatureAlgorithm = "sha256WithECDSA"; } else if (keyAlgorithm.equals("EC_RSA")) { signatureAlgorithm = "sha256WithRSA"; } else { throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm); } if (serialNumber == null) { byte[] serialBytes = new byte[16]; new SecureRandom().nextBytes(serialBytes); serialNumber = new BigInteger(1, serialBytes); } X509v3CertificateBuilder x509cg = new X509v3CertificateBuilder(X500Name.getInstance(issuer.getEncoded()), serialNumber, start, end, X500Name.getInstance(subject.getEncoded()), SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); if (keyUsage != 0) { x509cg.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage)); } if (ca) { x509cg.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); } for (int i = 0; i < extendedKeyUsages.size(); i++) { KeyPurposeId keyPurposeId = extendedKeyUsages.get(i); boolean critical = criticalExtendedKeyUsages.get(i); x509cg.addExtension(Extension.extendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId)); } if (!subjectAltNames.isEmpty()) { x509cg.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(subjectAltNames.toArray(new GeneralName[0])).getEncoded()); } if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) { x509cg.addExtension(Extension.nameConstraints, true, new NameConstraints( permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()]))); } X509CertificateHolder x509holder = x509cg .build(new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey)); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509c = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(x509holder.getEncoded())); if (StandardNames.IS_RI) { /* * The RI can't handle the BC EC signature algorithm * string of "ECDSA", since it expects "...WITHEC...", * so convert from BC to RI X509Certificate * implementation via bytes. */ CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded()); Certificate c = cf.generateCertificate(bais); x509c = (X509Certificate) c; } return x509c; }