Example usage for org.bouncycastle.pkcs PKCS10CertificationRequest getSubjectPublicKeyInfo

List of usage examples for org.bouncycastle.pkcs PKCS10CertificationRequest getSubjectPublicKeyInfo

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs PKCS10CertificationRequest getSubjectPublicKeyInfo.

Prototype

public SubjectPublicKeyInfo getSubjectPublicKeyInfo() 

Source Link

Document

Return the SubjectPublicKeyInfo describing the public key this request is carrying.

Usage

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void cmsSigner(final int workerId) throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(workerId, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(workerId);

    // Test active
    List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    signGenericDocument(workerId, "Sample data".getBytes());
}

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void xmlSigner(final int workerId) throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(workerId, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(workerId);

    // Test active
    List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    signGenericDocument(workerId, "<sampledata/>".getBytes());

    // Test removing the DEFAULTKEY property, should result in a CryptoTokenOfflineException
    workerSession.removeWorkerProperty(workerId, "DEFAULTKEY");
    workerSession.reloadConfiguration(workerId);

    try {/*from  ww w  .  j  a v  a2 s.  com*/
        signGenericDocument(workerId, "<sampledata/>".getBytes());
        fail("Should throw a CryptoTokenOfflineException");
    } catch (CryptoTokenOfflineException e) {
        // expected
    }
}

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void odfSigner(final int workerId) throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(workerId, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(workerId);

    // Test active
    List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    signGenericDocument(workerId, readFile(odfSampleFile));
}

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void ooxmlSigner(final int workerId) throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(workerId, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(workerId);

    // Test active
    List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    signGenericDocument(workerId, readFile(ooxmlSampleFile));
}

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void msauthTSSigner(final int workerId) throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(workerId, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .addExtension(org.bouncycastle.asn1.x509.X509Extension.extendedKeyUsage, true,
                            new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping))
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(workerId);

    // Test active
    List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    GenericSignRequest signRequest = new GenericSignRequest(678, MSAUTHCODE_REQUEST_DATA.getBytes());
    final GenericSignResponse res = (GenericSignResponse) workerSession.process(workerId, signRequest,
            new RequestContext());
    Certificate signercert = res.getSignerCertificate();
    assertNotNull(signercert);//w w  w .j  a  va  2s .c  o m

    byte[] buf = res.getProcessedData();
    CMSSignedData s = new CMSSignedData(Base64.decode(buf));

    int verified = 0;
    Store certStore = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder signerCert = (X509CertificateHolder) certIt.next();

        if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(signerCert))) {
            verified++;
        }
    }

    assertEquals("signer verified", 1, verified);
}

From source file:org.signserver.server.dispatchers.FirstActiveDispatcherTest.java

License:Open Source License

private void addCertificate(PrivateKey issuerPrivateKey, int workerId, String workerName)
        throws CryptoTokenOfflineException, InvalidWorkerIdException, IOException, CertificateException,
        OperatorCreationException {//from   ww  w. jav a  2s  .  com
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) workerSession.getCertificateRequest(workerId,
            new PKCS10CertReqInfo("SHA1withRSA", "CN=" + workerName, null), false);
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo()).build(
                    new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(issuerPrivateKey));
    workerSession.setWorkerProperty(workerId, "SIGNERCERTCHAIN", new String(
            CertTools.getPEMFromCerts(Arrays.asList(new JcaX509CertificateConverter().getCertificate(cert)))));
    workerSession.reloadConfiguration(workerId);
}

From source file:org.signserver.server.log.SystemLoggingTest.java

License:Open Source License

/**
 * Tests that importing a certificate chain to a token is audit logged
 * including the complete chain./*w  w  w .  j  a  va 2 s . c  om*/
 * @throws Exception 
 */
@Test
public void test01LogCertChainInstalledToToken() throws Exception {
    LOG.info(">test01LogCertChainInstalledToToken");

    final String tokenName = "TestCryptoTokenP12_001";
    final String alias = "testkeyalias10";

    try {
        setupCryptoToken(WORKERID_CRYPTOWORKER1, tokenName, "foo123");
        workerSession.generateSignerKey(WORKERID_CRYPTOWORKER1, "RSA", "512", alias, null);

        PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=testkeyalias10,C=SE", null);
        ICertReqData req = workerSession.getCertificateRequest(WORKERID_CRYPTOWORKER1, certReqInfo, false);
        Base64SignerCertReqData reqData = (Base64SignerCertReqData) req;
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                Base64.decode(reqData.getBase64CertReq()));

        int linesBefore = readEntriesCount(auditLogFile);

        // Test with uploadSignerCertificateChain method (global scope)
        KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
        final X509Certificate issuerCert = new JcaX509CertificateConverter().getCertificate(
                new CertBuilder().setSelfSignKeyPair(issuerKeyPair).setSubject("CN=Issuer, C=SE").build());
        final X509Certificate cert = new JcaX509CertificateConverter()
                .getCertificate(new X509v3CertificateBuilder(new X500Name("CN=Issuer, C=SE"), BigInteger.ONE,
                        new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)),
                        csr.getSubject(), csr.getSubjectPublicKeyInfo())
                                .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                                        .build(issuerKeyPair.getPrivate())));

        workerSession.importCertificateChain(WORKERID_CRYPTOWORKER1,
                Arrays.asList(cert.getEncoded(), issuerCert.getEncoded()), alias, null);

        List<String> lines = readEntries(auditLogFile, linesBefore, 2);
        LOG.info(lines);

        String line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
        assertNotNull("Contains event", line);
        assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT"));
        assertTrue("Contains worker id", line.contains("WORKER_ID: " + WORKERID_CRYPTOWORKER1));
        assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName));
        assertTrue("Contains key alias", line.contains("KEYALIAS: " + alias));
        assertTrue("Contains certificate",
                line.contains(new String(org.cesecore.util.CertTools
                        .getPemFromCertificateChain(Arrays.<Certificate>asList(cert, issuerCert)))
                                .replace("\r\n", "\n")));
    } finally {
        removeWorker(WORKERID_CRYPTOWORKER1);
        if (keystoreFile != null) {
            FileUtils.deleteQuietly(keystoreFile);
        }
    }
}

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();
///*www  . j  av a  2  s .c om*/
//            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)
 *///www  .j av a 2s .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();

    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   www .ja v a2 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");
    }
}