List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter
public JcaX509CertificateConverter()
From source file:org.texai.x509.X509Utils.java
License:Open Source License
/** Generates an intermediate CA certificate, that is to be used to sign end-use certificates. * * @param myPublicKey the public key for this certificate * @param issuerPrivateKey the issuer's private key * @param issuerCertificate the issuer's certificate, which is either the root CA certificate or another intermediate * CA certificate//from www . jav a 2s . c o m * @param pathLengthConstraint the maximum number of CA certificates that may follow this certificate in a certification * path. (Note: One end-entity certificate will follow the final CA certificate in the path. The last certificate in a path * is considered an end-entity certificate, whether the subject of the certificate is a CA or not.) * @return an intermediate CA certificate * * @throws CertificateParsingException when the certificate cannot be parsed * @throws CertificateEncodingException when the certificate cannot be encoded * @throws NoSuchProviderException when an invalid provider is given * @throws NoSuchAlgorithmException when an invalid algorithm is given * @throws SignatureException when the an invalid signature is present * @throws InvalidKeyException when the given key is invalid * @throws IOException if an input/output error occurs while processing the serial number file */ public static X509Certificate generateIntermediateX509Certificate(final PublicKey myPublicKey, final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, int pathLengthConstraint) throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { //Preconditions assert myPublicKey != null : "myPublicKey must not be null"; assert issuerPrivateKey != null : "issuerPrivateKey must not be null"; assert issuerCertificate != null : "issuerCertificate must not be null"; //final X500Name issuer = new X500Name(issuerCertificate.getSubjectX500Principal().getName()); final X500Name issuer = new X500Name( StringUtils.reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())); final UUID intermediateUUID = UUID.randomUUID(); // provide items to X500Principal in reverse order final X500Principal x500Principal = new X500Principal( "UID=" + intermediateUUID + ", DC=IntermediateCertificate, CN=texai.org"); final X500Name subject = new X500Name(x500Principal.getName()); SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(myPublicKey.getEncoded())); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, getNextSerialNumber(), // serial new Date(System.currentTimeMillis() - 10000L), // notBefore, new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter, subject, publicKeyInfo); // see http://www.ietf.org/rfc/rfc3280.txt // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); // Add authority key identifier x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate)); // Add subject key identifier x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey)); // add basic constraints x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical new BasicConstraints(pathLengthConstraint)); // is a CA certificate with specified certification path length // add key usage final KeyUsage keyUsage = new KeyUsage( // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on // certificates KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation // information KeyUsage.cRLSign); x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical keyUsage); X509Certificate x509Certificate; try { final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM) .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey); final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); x509Certificate = makeCanonicalX509Certificate( jcaX509CertificateConverter.getCertificate(x509CertificateHolder)); } catch (CertificateException | OperatorCreationException ex) { throw new TexaiException(ex); } //Postconditions try { x509Certificate.checkValidity(); x509Certificate.verify(issuerCertificate.getPublicKey()); } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException ex) { throw new TexaiException(ex); } return x509Certificate; }
From source file:org.texai.x509.X509Utils.java
License:Open Source License
/** Generates a signed end-use certificate that cannot be used to sign other certificates, but can be used for authentication * and for message signing./*from w w w . j a va 2 s . com*/ * * @param myPublicKey the public key for this certificate * @param issuerPrivateKey the issuer's private key * @param issuerCertificate the issuer's certificate * @param uid the subject UID * @param domainComponent the domain component, e.g. TexaiLauncher or NodeRuntime * @return a signed end-use certificate * * @throws CertificateParsingException when the certificate cannot be parsed * @throws CertificateEncodingException when the certificate cannot be encoded * @throws NoSuchProviderException when an invalid provider is given * @throws NoSuchAlgorithmException when an invalid algorithm is given * @throws SignatureException when the an invalid signature is present * @throws InvalidKeyException when the given key is invalid * @throws IOException if an input/output error occurs while processing the serial number file */ public static X509Certificate generateX509Certificate(final PublicKey myPublicKey, final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid, final String domainComponent) throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { //Preconditions assert myPublicKey != null : "myPublicKey must not be null"; assert issuerPrivateKey != null : "issuerPrivateKey must not be null"; assert issuerCertificate != null : "issuerCertificate must not be null"; assert uid != null : "uid must not be null"; final String x500PrincipalString; // provide items to X500Principal in reverse order if (domainComponent == null || domainComponent.isEmpty()) { x500PrincipalString = "UID=" + uid + ", CN=texai.org"; } else { x500PrincipalString = "UID=" + uid + ", DC=" + domainComponent + " ,CN=texai.org"; } final X500Principal x500Principal = new X500Principal(x500PrincipalString); LOGGER.info("issuer: " + issuerCertificate.getIssuerX500Principal().getName()); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( new X500Name(StringUtils .reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())), // issuer, getNextSerialNumber(), // serial new Date(System.currentTimeMillis() - 10000L), // notBefore, new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter, new X500Name(x500Principal.getName()), // subject, new SubjectPublicKeyInfo(ASN1Sequence.getInstance(myPublicKey.getEncoded()))); // publicKeyInfo // see http://www.ietf.org/rfc/rfc3280.txt // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); // Add authority key identifier x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate)); // Add subject key identifier x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey)); // add basic constraints x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical new BasicConstraints(false)); // is not a CA certificate // add key usage final KeyUsage keyUsage = new KeyUsage( // the digitalSignature usage indicates that the subject public key may be used with a digital signature // mechanism to support security services other than non-repudiation, certificate signing, or revocation // information signing KeyUsage.digitalSignature | // the nonRepudiation usage indicates that the subject public key may be used to verify digital signatures // used to provide a non-repudiation service which protects against the signing entity falsely denying some // action, excluding certificate or CRL signing KeyUsage.nonRepudiation | // the keyEncipherment usage indicates that the subject public key may be used for key transport, e.g. the // exchange of efficient symmetric keys in SSL KeyUsage.keyEncipherment | // the dataEncipherment usage indicates that the subject public key may be used for enciphering user data, // other than cryptographic keys KeyUsage.dataEncipherment | // the keyAgreement usage indicates that the subject public key may be used for key agreement, e.g. when a // Diffie-Hellman key is to be used for key management KeyUsage.keyAgreement | // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on // certificates KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation // information KeyUsage.cRLSign | // see http://www.docjar.com/html/api/sun/security/validator/EndEntityChecker.java.html - bit 0 needs to set for SSL // client authorization KeyUsage.encipherOnly); x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical keyUsage); X509Certificate x509Certificate; try { final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM) .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey); final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); x509Certificate = makeCanonicalX509Certificate( jcaX509CertificateConverter.getCertificate(x509CertificateHolder)); } catch (CertificateException | OperatorCreationException ex) { throw new TexaiException(ex); } //Postconditions try { x509Certificate.checkValidity(); x509Certificate.verify(issuerCertificate.getPublicKey()); } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException ex) { throw new TexaiException(ex); } assert x509Certificate.getKeyUsage()[0] : "must have digital signature key usage"; return x509Certificate; }
From source file:org.texai.x509.X509Utils.java
License:Open Source License
/** Generates a self-signed certificate to use as a CA root certificate. * * @param keyPair the root public/private key pair * @return a self-signed CA root certificate * * @throws CertificateEncodingException when the certificate cannot be encoded * @throws NoSuchProviderException when an invalid provider is given * @throws NoSuchAlgorithmException when an invalid algorithm is given * @throws SignatureException when the an invalid signature is present * @throws InvalidKeyException when the given key is invalid * @throws IOException if an input/output error occurs while processing the serial number file *//*from ww w. jav a2s . c o m*/ protected static X509Certificate generateRootX509Certificate(final KeyPair keyPair) throws CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { //Preconditions assert keyPair != null : "keyPair must not be null"; final UUID rootUUID = UUID.randomUUID(); // provide items to X500Principal in reverse order final X500Principal rootX500Principal = new X500Principal( "UID=" + rootUUID + ", O=Texai Certification Authority, CN=texai.org"); final X500Name subject = new X500Name(rootX500Principal.getName()); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( new X500Name(rootX500Principal.getName()), // issuer, getNextSerialNumber(), // serial new Date(System.currentTimeMillis() - 10000L), // notBefore, new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter, subject, new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()))); // publicKeyInfo // see http://www.ietf.org/rfc/rfc3280.txt // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); // Add subject key identifier x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyPair.getPublic())); // add basic constraints x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical new BasicConstraints(true)); // is a CA certificate with an unlimited certification path length final KeyUsage keyUsage = new KeyUsage( // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on // certificates KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation // information KeyUsage.cRLSign); // add key usage x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical keyUsage); X509Certificate rootX509Certificate; try { final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM) .setProvider(BOUNCY_CASTLE_PROVIDER).build(keyPair.getPrivate()); final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); rootX509Certificate = jcaX509CertificateConverter.getCertificate(x509CertificateHolder); } catch (CertificateException | OperatorCreationException ex) { throw new TexaiException(ex); } //Postconditions try { rootX509Certificate.checkValidity(); rootX509Certificate.verify(keyPair.getPublic()); return rootX509Certificate; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException | CertificateException ex) { throw new TexaiException(ex); } }
From source file:org.vesalainen.security.cert.X509Generator.java
License:Open Source License
/** * Create a signed X.509 Certificate/*from ww w.j a v a2 s .c o m*/ * @param subjectDN the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param issuerDN Signers X.509 Distinguished Name, eg "CN=Test, L=London, C=GB" * @param pair the KeyPair * @param privkey Signers private key * @param days how many days from now the Certificate is valid for * @param signingAlgorithm the signing algorithm, e.g. "SHA1withRSA" * @return * @throws java.security.cert.CertificateException */ public X509Certificate generateCertificate(String subjectDN, String issuerDN, KeyPair pair, PrivateKey privkey, int days, String signingAlgorithm) throws CertificateException { if (privkey == null) { privkey = pair.getPrivate(); } X500Name issuer; if (issuerDN == null) { issuer = new X500Name(RFC4519Style.INSTANCE, subjectDN); } else { issuer = new X500Name(RFC4519Style.INSTANCE, issuerDN); } long now = System.currentTimeMillis(); BigInteger serial = BigInteger.probablePrime(64, new SecureRandom(Primitives.writeLong(now))); X500Name subject = new X500Name(RFC4519Style.INSTANCE, subjectDN); PublicKey publicKey = pair.getPublic(); byte[] encoded = publicKey.getEncoded(); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(encoded); X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, new Date(now - 86400000l), new Date(now + days * 86400000l), subject, subjectPublicKeyInfo); X509CertificateHolder holder = builder.build(createSigner(privkey, signingAlgorithm)); return new JcaX509CertificateConverter().getCertificate(holder); }
From source file:org.votingsystem.signature.smime.SMIMESignedValidator.java
License:Open Source License
/** * verify that the sig is correct and that it was generated when the * certificate was current(assuming the cert is contained in the message). *///from ww w . j a v a 2s. c om public static boolean isValidSignature(SMIMESigned smimeSigned) throws Exception { // certificates and crls passed in the signature Store certs = smimeSigned.getCertificates(); // SignerInfo blocks which contain the signatures SignerInformationStore signers = smimeSigned.getSignerInfos(); log.info("signers.size(): " + signers.size()); Collection c = signers.getSigners(); Iterator it = c.iterator(); boolean result = false; // check each signer while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getMatches(signer.getSID()); log.info("Collection matches: " + certCollection.size()); Iterator certIt = certCollection.iterator(); X509Certificate cert = new JcaX509CertificateConverter().setProvider(ContextVS.PROVIDER) .getCertificate((X509CertificateHolder) certIt.next()); log.info("SubjectDN: " + cert.getSubjectDN() + " - Not before: " + cert.getNotBefore() + " - Not after: " + cert.getNotAfter() + " - SigningTime: " + getSigningTime(signer)); if (signer .verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(ContextVS.PROVIDER).build(cert))) { log.info("signature verified"); result = true; } else { log.info("signature failed!"); result = false; } } return result; }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
License:Open Source License
public X509Certificate generateX509Certificate() throws KeystoreException { CommonUtil commonUtil = new CommonUtil(); Date validityBeginDate = commonUtil.getValidityStartDate(); Date validityEndDate = commonUtil.getValidityEndDate(); Security.addProvider(new BouncyCastleProvider()); try {/*from ww w . j a v a 2 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(CertificateManagementConstants.DEFAULT_PRINCIPAL); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( principal, CommonUtil.generateSerialNumber(), 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)); // cert.checkValidity(); certificate.verify(certificate.getPublicKey()); List<org.wso2.carbon.certificate.mgt.core.bean.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.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(); ///*from w ww . j a v a 2 s . co m*/ // 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.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) */// ww w.j a va2 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.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 ww w. j a v a2s.co m*/ 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.//from ww w . j a va 2 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; }