List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter
public JcaX509CertificateConverter()
From source file:org.wso2.carbon.identity.certificateauthority.CAAdminService.java
License:Open Source License
protected X509Certificate signCSR(String serialNo, PKCS10CertificationRequest request, int validity, PrivateKey privateKey, X509Certificate caCert) throws CaException { try {//from w w w. j a va 2s. co m Date issuedDate = new Date(); Date expiryDate = new Date(System.currentTimeMillis() + validity * MILLIS_PER_DAY); JcaPKCS10CertificationRequest jcaRequest = new JcaPKCS10CertificationRequest(request); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(caCert, new BigInteger(serialNo), issuedDate, expiryDate, jcaRequest.getSubject(), jcaRequest.getPublicKey()); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); certificateBuilder .addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert)) .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(jcaRequest.getPublicKey())) .addExtension(Extension.basicConstraints, true, new BasicConstraints(0)) .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)) .addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey); //todo add ocsp extension int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); DistributionPointName crlEp = new DistributionPointName(new GeneralNames(new GeneralName( GeneralName.uniformResourceIdentifier, CAUtils.getServerURL() + "/ca/crl/" + tenantID))); DistributionPoint disPoint = new DistributionPoint(crlEp, null, null); certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(new DistributionPoint[] { disPoint })); AccessDescription ocsp = new AccessDescription(AccessDescription.id_ad_ocsp, new GeneralName( GeneralName.uniformResourceIdentifier, CAUtils.getServerURL() + "/ca/ocsp/" + tenantID)); ASN1EncodableVector authInfoAccessASN = new ASN1EncodableVector(); authInfoAccessASN.add(ocsp); certificateBuilder.addExtension(Extension.authorityInfoAccess, false, new DERSequence(authInfoAccessASN)); return new JcaX509CertificateConverter().setProvider("BC") .getCertificate(certificateBuilder.build(signer)); // AccessDescription ocsp = new AccessDescription(ID_AD_OCSP, // new GeneralName(GeneralName.uniformResourceIdentifier, // new DERIA5String(CAUtils.getServerURL()+"/ca/ocsp/" + tenantID)) // ); // // ASN1EncodableVector authInfoAccessASN = new ASN1EncodableVector(); // authInfoAccessASN.add(ocsp); // // certGen.addExtension(X509Extensions.AuthorityInfoAccess, false, new DERSequence(authInfoAccessASN)); // // DistributionPointName crlEP = new DistributionPointName(DNP_TYPE, new GeneralNames( // new GeneralName(GeneralName.uniformResourceIdentifier, CAUtils.getServerURL()+"/ca/crl/" + tenantID))); // // DistributionPoint[] distPoints = new DistributionPoint[1]; // distPoints[0] = new DistributionPoint(crlEP, null, null); // // certGen.addExtension(X509Extensions.CRLDistributionPoints, false, new CRLDistPoint(distPoints)); // // ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); // for (int i = 0; i != attributes.size(); i++) { // 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()); // } // } // } // X509Certificate issuedCert = certGen.generateX509Certificate(privateKey); // return issuedCert; } catch (Exception e) { throw new CaException("Error in signing the certificate", e); } }
From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.util.CertificateSigningService.java
License:Open Source License
/** * @param jcaRequest - CSR from the device * @param privateKey - Private key of CA certificate in MDM server * @param CACert - CA certificate in MDM server * @param certParameterList - Parameter list for Signed certificate generation * @return - Signed certificate for CSR from device * @throws Exception//from w w w . j a v a 2s . c om */ public static X509Certificate signCSR(JcaPKCS10CertificationRequest jcaRequest, PrivateKey privateKey, X509Certificate CACert, List certParameterList) throws CertificateGenerationException, XMLFileOperationException { String commonName = (String) certParameterList.get(FIRST_ITEM); int notBeforeDate = (Integer) certParameterList.get(SECOND_ITEM); int notAfterDate = (Integer) certParameterList.get(THIRD_ITEM); X509v3CertificateBuilder certificateBuilder; try { certificateBuilder = new JcaX509v3CertificateBuilder(CACert, BigInteger.valueOf(new SecureRandom().nextInt(Integer.MAX_VALUE)), new Date(System.currentTimeMillis() - (DAYS * notBeforeDate)), new Date(System.currentTimeMillis() + (DAYS * notAfterDate)), new X500Principal(commonName), jcaRequest.getPublicKey()); } catch (InvalidKeyException e) { throw new CertificateGenerationException("CSR's public key is invalid", e); } catch (NoSuchAlgorithmException e) { throw new CertificateGenerationException("Certificate cannot be generated", e); } try { certificateBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); } catch (CertIOException e) { throw new CertificateGenerationException("Cannot add extension(s) to signed certificate", e); } ContentSigner signer; try { signer = new JcaContentSignerBuilder(Constants.CertificateEnrollment.ALGORITHM) .setProvider(Constants.CertificateEnrollment.PROVIDER).build(privateKey); } catch (OperatorCreationException e) { throw new CertificateGenerationException("Content signer cannot be created", e); } X509Certificate signedCertificate; try { signedCertificate = new JcaX509CertificateConverter() .setProvider(Constants.CertificateEnrollment.PROVIDER) .getCertificate(certificateBuilder.build(signer)); } catch (CertificateException e) { throw new CertificateGenerationException("Signed certificate cannot generated", e); } return signedCertificate; }
From source file:org.wso2.carbon.webapp.authenticator.framework.util.TestCertificateGenerator.java
License:Open Source License
public X509Certificate generateX509Certificate() throws KeystoreException { BigInteger serialNumber = CommonUtil.generateSerialNumber(); String defaultPrinciple = "CN=" + serialNumber + ",O=WSO2,OU=Mobile,C=LK"; CommonUtil commonUtil = new CommonUtil(); Date validityBeginDate = commonUtil.getValidityStartDate(); Date validityEndDate = commonUtil.getValidityEndDate(); Security.addProvider(new BouncyCastleProvider()); try {//from www .j av a 2 s . c om KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CertificateManagementConstants.RSA, CertificateManagementConstants.PROVIDER); keyPairGenerator.initialize(CertificateManagementConstants.RSA_KEY_LENGTH, new SecureRandom()); KeyPair pair = keyPairGenerator.generateKeyPair(); X500Principal principal = new X500Principal(defaultPrinciple); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(principal, serialNumber, validityBeginDate, validityEndDate, principal, pair.getPublic()); ContentSigner contentSigner = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA) .setProvider(CertificateManagementConstants.PROVIDER).build(pair.getPrivate()); X509Certificate certificate = new JcaX509CertificateConverter() .setProvider(CertificateManagementConstants.PROVIDER) .getCertificate(certificateBuilder.build(contentSigner)); certificate.verify(certificate.getPublicKey()); List<Certificate> certificates = new ArrayList<>(); org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); certificateToStore.setCertificate(certificate); certificates.add(certificateToStore); saveCertInKeyStore(certificates); return certificate; } catch (NoSuchAlgorithmException e) { String errorMsg = "No such algorithm found when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (NoSuchProviderException e) { String errorMsg = "No such provider found when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (OperatorCreationException e) { String errorMsg = "Issue in operator creation when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (CertificateExpiredException e) { String errorMsg = "Certificate expired after generating certificate"; throw new KeystoreException(errorMsg, e); } catch (CertificateNotYetValidException e) { String errorMsg = "Certificate not yet valid when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Certificate issue occurred when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (InvalidKeyException e) { String errorMsg = "Invalid key used when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (SignatureException e) { String errorMsg = "Signature related issue occurred when generating certificate"; throw new KeystoreException(errorMsg, e); } }
From source file:org.xdi.oxauth.crypto.cert.CertificateParser.java
License:MIT License
public static X509Certificate parsePem(String pemEncodedCert) throws CertificateException { StringReader sr = new StringReader(pemEncodedCert); PEMParser pemReader = new PEMParser(sr); try {//w ww.j av a2 s. c o m X509CertificateHolder certificateHolder = ((X509CertificateHolder) pemReader.readObject()); if (certificateHolder == null) { return null; } X509Certificate cert = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateHolder); return cert; } catch (IOException ex) { throw new CertificateException(ex); } finally { IOUtils.closeQuietly(pemReader); } }
From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java
License:MIT License
public X509Certificate generateV3Certificate(KeyPair keyPair, String issuer, String signatureAlgorithm, Long expirationTime) throws CertIOException, OperatorCreationException, CertificateException { PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); // Signers name X500Name issuerName = new X500Name(issuer); // Subjects name - the same as we are self signed. X500Name subjectName = new X500Name(issuer); // Serial//w ww .j av a2 s .co m BigInteger serial = new BigInteger(256, new SecureRandom()); // Not before Date notBefore = new Date(System.currentTimeMillis() - 10000); Date notAfter = new Date(expirationTime); // Create the certificate - version 3 JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, publicKey); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); ASN1ObjectIdentifier extendedKeyUsage = new ASN1ObjectIdentifier("2.5.29.37").intern(); builder.addExtension(extendedKeyUsage, false, new DERSequence(purposes)); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(privateKey); X509CertificateHolder holder = builder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder); return cert; }
From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.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 . ja va 2 s. co m*/ * @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(); Security.addProvider(new BouncyCastleProvider()); 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(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded())); certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)); KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage }; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku)); final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").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(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[] { cert }); } catch (final Exception e) { throw new IllegalStateException("Errors during assembling root CA.", e); } return ks; }
From source file:pdfbox.SignatureVerifier.java
License:Apache License
/** * Verify a PKCS7 signature.//from ww w . j a va 2s .co m * * @param byteArray the byte sequence that has been signed * @param contents the /Contents field as a COSString * @param sig the PDF signature (the /V dictionary) * @throws CertificateException * @throws CMSException * @throws StoreException * @throws OperatorCreationException */ private SignatureResult verifyPKCS7(byte[] byteArray, COSString contents, PDSignature sig) throws CMSException, CertificateException, StoreException, OperatorCreationException { // inspiration: // http://stackoverflow.com/a/26702631/535646 // http://stackoverflow.com/a/9261365/535646 CMSProcessable signedContent = new CMSProcessableByteArray(byteArray); CMSSignedData signedData = new CMSSignedData(signedContent, contents.getBytes()); Store certificatesStore = signedData.getCertificates(); Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners(); SignerInformation signerInformation = signers.iterator().next(); Collection matches = certificatesStore.getMatches(signerInformation.getSID()); X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next(); X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder); //System.out.println("certFromSignedData: " + certFromSignedData); certFromSignedData.checkValidity(sig.getSignDate().getTime()); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); if (provider != null) { verifierBuilder.setProvider(provider); } boolean validated = false; try { validated = signerInformation.verify(verifierBuilder.build(certFromSignedData)); } catch (CMSSignerDigestMismatchException e) { System.out.println("Signature failed to validate: "); e.printStackTrace(); } return new SignatureResult(certFromSignedData, validated); }
From source file:pv181.jca.Globals.java
/** * Converts X509CertificateHolder from BouncyCastle library to X509Certificate. * @param h// w w w . j a v a 2 s .c om * @return * @throws java.security.cert.CertificateException */ public static X509Certificate getX509Certificate(X509CertificateHolder h) throws CertificateException { return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(h); }
From source file:uk.ac.cam.gpe21.droidssl.mitm.crypto.cert.CertificateAuthority.java
License:Apache License
public CertificateAuthority(Path certificateFile, Path keyFile) throws IOException, CertificateException { try (PEMParser parser = new PEMParser(Files.newBufferedReader(certificateFile, StandardCharsets.UTF_8))) { Object object = parser.readObject(); if (!(object instanceof X509CertificateHolder)) throw new IOException("Failed to read CA certificate file"); certificate = (X509CertificateHolder) object; jcaCertificate = new JcaX509CertificateConverter().getCertificate(certificate); }/*from w ww . j a v a 2 s. co m*/ try (PEMParser parser = new PEMParser(Files.newBufferedReader(keyFile, StandardCharsets.UTF_8))) { Object object = parser.readObject(); if (!(object instanceof PEMKeyPair)) throw new IOException("Failed to read CA key file"); PEMKeyPair pair = (PEMKeyPair) object; publicKey = PublicKeyFactory.createKey(pair.getPublicKeyInfo()); privateKey = PrivateKeyFactory.createKey(pair.getPrivateKeyInfo()); } }
From source file:uk.ac.cam.gpe21.droidssl.mitm.crypto.cert.CertificateGenerator.java
License:Apache License
public X509Certificate generateJca(String cn, String[] sans) { try {/*from w w w . j a v a 2 s . c o m*/ JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); X509CertificateHolder certificate = generate(cn, sans); return converter.getCertificate(certificate); } catch (CertificateException ex) { throw new CertificateGenerationException(ex); } }