List of usage examples for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder
public JcaContentSignerBuilder(String signatureAlgorithm)
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
License:Open Source License
public X509Certificate generateCertificateFromCSR(PrivateKey privateKey, PKCS10CertificationRequest request, String issueSubject) throws KeystoreException { CommonUtil commonUtil = new CommonUtil(); Date validityBeginDate = commonUtil.getValidityStartDate(); Date validityEndDate = commonUtil.getValidityEndDate(); X500Name certSubject = new X500Name(CertificateManagementConstants.DEFAULT_PRINCIPAL); //X500Name certSubject = request.getSubject(); Attribute attributes[] = request.getAttributes(); // if (certSubject == null) { // certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL); // } else { // org.bouncycastle.asn1.x500.RDN[] rdn = certSubject.getRDNs(); //// w ww. j a v a 2 s. com // if (rdn == null || rdn.length == 0) { // certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL); // } // } RDN[] certUniqueIdRDN; BigInteger certUniqueIdentifier; // IMPORTANT: "Serial-Number" of the certificate used when creating it, is set as its "Alias" to save to // keystore. if (request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER).length != 0) { // if certificate attribute "UNIQUE_IDENTIFIER" exists use its hash as the "Serial-Number" for the // certificate. certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER); certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode()); } else if (request.getSubject().getRDNs(BCStyle.SERIALNUMBER).length != 0) { // else if certificate attribute "SERIAL_NUMBER" exists use its hash as the "Serial-Number" for the // certificate. certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.SERIALNUMBER); certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode()); } else { // else get the BigInteger Value of the integer that is the current system-time in millis as the // "Serial-Number". certUniqueIdentifier = CommonUtil.generateSerialNumber(); } X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder( new X500Name(issueSubject), certUniqueIdentifier, validityBeginDate, validityEndDate, certSubject, request.getSubjectPublicKeyInfo()); ContentSigner sigGen; X509Certificate issuedCert; try { certificateBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); if (attributes != null) { ASN1Encodable extractedValue = getChallengePassword(attributes); if (extractedValue != null) { certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, true, extractedValue); } } sigGen = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA) .setProvider(CertificateManagementConstants.PROVIDER).build(privateKey); issuedCert = new JcaX509CertificateConverter().setProvider( CertificateManagementConstants.PROVIDER).getCertificate( certificateBuilder.build(sigGen)); org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>(); certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); certificate.setCertificate(issuedCert); certificates.add(certificate); saveCertInKeyStore(certificates); } catch (CertIOException e) { String errorMsg = "Certificate Input output issue occurred when generating generateCertificateFromCSR"; throw new KeystoreException(errorMsg, e); } catch (OperatorCreationException e) { String errorMsg = "Operator creation issue occurred when generating generateCertificateFromCSR"; throw new KeystoreException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Certificate issue occurred when generating generateCertificateFromCSR"; throw new KeystoreException(errorMsg, e); } return issuedCert; }
From source file:org.wso2.carbon.certificate.mgt.core.util.CSRGenerator.java
License:Open Source License
/** * Generate the desired CSR for signing/*from w ww . j a v a2s .c o m*/ * * @param sigAlg * @param keyPair * @return */ public byte[] generateCSR(String sigAlg, KeyPair keyPair) { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outStream); try { PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder( new X500Principal("CN=Requested Test Certificate"), keyPair.getPublic()); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner signer = csBuilder.build(keyPair.getPrivate()); PKCS10CertificationRequest csr = p10Builder.build(signer); return csr.getEncoded(); } catch (OperatorCreationException ex) { log.error("Error while Key generation operation", ex); } catch (IOException ex) { log.error("Error while generating CSR,ex"); } return new byte[0]; }
From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java
License:Open Source License
/** * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its * PublicKey for future payload encryption. * * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if * there is an error creating a self-sign certificate to present to the * server (whilst trying to get the CSR signed) */// w ww . ja va 2 s .c om public void beginEnrollmentFlow() throws AgentCoreOperationException { Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = generateKeyPair(); this.privateKey = keyPair.getPrivate(); this.publicKey = keyPair.getPublic(); if (log.isDebugEnabled()) { log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n"); } PKCS10CertificationRequest certSignRequest = generateCertSignRequest(); /** * ----------------------------------------------------------------------------------------------- * Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request. * In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this. * ----------------------------------------------------------------------------------------------- */ X500Name issuer = new X500Name("CN=Temporary Issuer"); BigInteger serial = new BigInteger(32, new SecureRandom()); Date fromDate = new Date(); Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L)); // Build the self-signed cert using BC, sign it with our private key (self-signed) X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate, certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo()); ContentSigner sigGen; X509Certificate tmpCert; try { sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate()); tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certBuilder.build(sigGen)); } catch (OperatorCreationException e) { String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } /** * ----------------------------------------------------------------------------------------------- */ this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest); this.serverPublicKey = initPublicKeyOfServer(); if (log.isDebugEnabled()) { log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey() + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n"); } }
From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java
License:Open Source License
/** * This method creates the PKCS10 Certificate Sign Request which is to be sent to the SCEP Server using the * generated PublicKey of the client. The certificate parameters used here are the ones from the AgentManager * which are the values read from the configurations file. * * @return the PKCS10CertificationRequest object created using the client specific configs and the generated * PublicKey/*from w ww .j av a 2 s . c o m*/ * @throws AgentCoreOperationException if an error occurs when creating a content signer to sign the CSR. */ private PKCS10CertificationRequest generateCertSignRequest() throws AgentCoreOperationException { // Build the CN for the cert we are requesting. X500NameBuilder nameBld = new X500NameBuilder(BCStyle.INSTANCE); nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getDeviceName()); nameBld.addRDN(BCStyle.O, AgentManager.getInstance().getAgentConfigs().getDeviceOwner()); nameBld.addRDN(BCStyle.OU, AgentManager.getInstance().getAgentConfigs().getDeviceOwner()); nameBld.addRDN(BCStyle.UNIQUE_IDENTIFIER, AgentManager.getInstance().getAgentConfigs().getDeviceId()); X500Name principal = nameBld.build(); JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(SIGNATURE_ALG) .setProvider(PROVIDER); ContentSigner contentSigner; try { contentSigner = contentSignerBuilder.build(this.privateKey); } catch (OperatorCreationException e) { String errorMsg = "Could not create content signer with private key."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } // Generate the certificate signing request (csr = PKCS10) PKCS10CertificationRequestBuilder reqBuilder = new JcaPKCS10CertificationRequestBuilder(principal, this.publicKey); return reqBuilder.build(contentSigner); }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager.java
License:Open Source License
/** * This method creates the PKCS10 Certificate Sign Request which is to be sent to the SCEP Server using the * generated PublicKey of the client. The certificate parameters used here are the ones from the AgentManager * which are the values read from the configurations file. * * @return the PKCS10CertificationRequest object created using the client specific configs and the generated * PublicKey/* w w w. ja v a 2 s. co m*/ * @throws AgentCoreOperationException if an error occurs when creating a content signer to sign the CSR. */ private PKCS10CertificationRequest generateCertSignRequest() throws AgentCoreOperationException { // Build the CN for the cert that's being requested. X500NameBuilder nameBld = new X500NameBuilder(BCStyle.INSTANCE); nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getTenantDomain()); nameBld.addRDN(BCStyle.O, AgentManager.getInstance().getAgentConfigs().getDeviceOwner()); nameBld.addRDN(BCStyle.OU, AgentManager.getInstance().getAgentConfigs().getDeviceOwner()); nameBld.addRDN(BCStyle.UNIQUE_IDENTIFIER, AgentManager.getInstance().getAgentConfigs().getDeviceId()); nameBld.addRDN(BCStyle.SERIALNUMBER, AgentManager.getInstance().getAgentConfigs().getDeviceId()); X500Name principal = nameBld.build(); JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(SIGNATURE_ALG) .setProvider(PROVIDER); ContentSigner contentSigner; try { contentSigner = contentSignerBuilder.build(this.privateKey); } catch (OperatorCreationException e) { String errorMsg = "Could not create content signer with private key."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } // Generate the certificate signing request (csr = PKCS10) PKCS10CertificationRequestBuilder reqBuilder = new JcaPKCS10CertificationRequestBuilder(principal, this.publicKey); return reqBuilder.build(contentSigner); }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java
License:Open Source License
/** * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its * PublicKey for future payload encryption. * * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if * there is an error creating a self-sign certificate to present to the * server (whilst trying to get the CSR signed) *///from w w w . j a va2 s .com public void beginEnrollmentFlow() throws AgentCoreOperationException { Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = generateKeyPair(); this.privateKey = keyPair.getPrivate(); this.publicKey = keyPair.getPublic(); if (log.isDebugEnabled()) { log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n"); } PKCS10CertificationRequest certSignRequest = generateCertSignRequest(); /** * ----------------------------------------------------------------------------------------------- * Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request. * In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this. * ----------------------------------------------------------------------------------------------- */ X500Name issuer = new X500Name("CN=Temporary Issuer"); BigInteger serial = new BigInteger(32, new SecureRandom()); Date fromDate = new Date(); Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L)); // Build the self-signed cert using BC, sign it with our private key (self-signed) X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate, certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo()); ContentSigner sigGen; X509Certificate tmpCert; try { sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate()); tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certBuilder.build(sigGen)); } catch (OperatorCreationException e) { String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } /** * ----------------------------------------------------------------------------------------------- */ this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest); this.serverPublicKey = initPublicKeyOfServer(); storeCertificateToStore(AgentConstants.DEVICE_CERT_ALIAS, SCEPCertificate); storeKeyToKeyStore(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS, this.privateKey, SCEPCertificate); if (log.isDebugEnabled()) { log.info(AgentConstants.LOG_APPENDER + "SCEPCertificate, DevicePrivateKey, ServerPublicKey was saved to device keystore [" + AgentConstants.DEVICE_KEYSTORE + "]"); log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey() + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n"); } }
From source file:org.wso2.carbon.device.mgt.mobile.windows.api.services.enrollment.util.CertificateSigningService.java
License:Open Source License
/** * Implement certificate signing task using CSR received from the device and the MDM server key * store./*w ww . j a v a2 s . c o m*/ * @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 CertificateGenerationException * @throws WAPProvisioningException */ public static X509Certificate signCSR(JcaPKCS10CertificationRequest jcaRequest, PrivateKey privateKey, X509Certificate caCert, List certParameterList) throws CertificateGenerationException, WAPProvisioningException { String commonName = (String) certParameterList.get(PropertyIndex.COMMON_NAME_INDEX.getValue()); int notBeforeDays = (Integer) certParameterList.get(PropertyIndex.NOT_BEFORE_DAYS_INDEX.getValue()); int notAfterDays = (Integer) certParameterList.get(PropertyIndex.NOT_AFTER_DAYS_INDEX.getValue()); X509v3CertificateBuilder certificateBuilder; X509Certificate signedCertificate; try { ContentSigner signer; BigInteger serialNumber = BigInteger.valueOf(new SecureRandom().nextInt(Integer.MAX_VALUE)); Date notBeforeDate = new Date(System.currentTimeMillis() - (MILLI_SECONDS * notBeforeDays)); Date notAfterDate = new Date(System.currentTimeMillis() + (MILLI_SECONDS * notAfterDays)); certificateBuilder = new JcaX509v3CertificateBuilder(caCert, serialNumber, notBeforeDate, notAfterDate, new X500Principal(commonName), jcaRequest.getPublicKey()); //Adding extensions to the signed certificate. 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)); signer = new JcaContentSignerBuilder(PluginConstants.CertificateEnrolment.ALGORITHM) .setProvider(PluginConstants.CertificateEnrolment.PROVIDER).build(privateKey); signedCertificate = new JcaX509CertificateConverter() .setProvider(PluginConstants.CertificateEnrolment.PROVIDER) .getCertificate(certificateBuilder.build(signer)); } catch (InvalidKeyException e) { throw new CertificateGenerationException("CSR's public key is invalid", e); } catch (NoSuchAlgorithmException e) { throw new CertificateGenerationException("Certificate cannot be generated", e); } catch (CertIOException e) { throw new CertificateGenerationException("Cannot add extension(s) to signed certificate", e); } catch (OperatorCreationException e) { throw new CertificateGenerationException("Content signer cannot be created", e); } catch (CertificateException e) { throw new CertificateGenerationException("Signed certificate cannot be generated", e); } return signedCertificate; }
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 {/*w ww . j av a2 s . c om*/ 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 www .ja va 2 s . co m */ 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 ww w . ja v a2 s .c o m*/ 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); } }