Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dotnet/mvc/PkiSuiteAspNetMvcSample/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -119,5 +119,5 @@
</script>
<script type="text/javascript" src="https://cdn.lacunasoftware.com/pki-suite-samples/runtime.29926b5c8448d756.js"></script>
<script type="text/javascript" src="https://cdn.lacunasoftware.com/pki-suite-samples/polyfills.b6a2ec357e891889.js"></script>
<script type="text/javascript" src="https://cdn.lacunasoftware.com/pki-suite-samples/main.3c1234946d8e0bef.js"></script>
<script type="text/javascript" src="https://cdn.lacunasoftware.com/pki-suite-samples/main.43928010b5333845.js"></script>
}
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@
</script>
<script th:fragment="scripts" type="text/javascript" src="https://cdn.lacunasoftware.com/pki-suite-samples/runtime.29926b5c8448d756.js"></script>
<script th:fragment="scripts" type="text/javascript" src="https://cdn.lacunasoftware.com/pki-suite-samples/polyfills.b6a2ec357e891889.js"></script>
<script th:fragment="scripts" type="text/javascript" src="https://cdn.lacunasoftware.com/pki-suite-samples/main.3c1234946d8e0bef.js"></script>
<script th:fragment="scripts" type="text/javascript" src="https://cdn.lacunasoftware.com/pki-suite-samples/main.43928010b5333845.js"></script>
<!-- endregion -->

</body>
Expand Down
1 change: 1 addition & 0 deletions node_modules/amplia-client
Submodule amplia-client added at 085de2
2 changes: 1 addition & 1 deletion nodejs/expressmvc/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"start": "nodemon ./bin/www"
},
"dependencies": {
"amplia-client": "^1.2.0",
"amplia-client": "1.3.1",
"body-parser": "~1.18.3",
"cloudhub-client": "^1.0.0",
"debug": "~2.6.9",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// pass the certificate information to server to communicate with Amplia. It is
// only an example, feel free to alter it to meet your application's needs.
// -----------------------------------------------------------------------------
var authCloudHubForm = (function () {
var cpfForm = (function () {

// Auxiliary global variable.
var formElements = null;
Expand Down
2 changes: 2 additions & 0 deletions nodejs/expressmvc/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ router.use("/download", require("./download"));
router.use("/", require("./home"));
router.use("/issue-cert-server-amplia", require("./issue-cert-server-amplia"));
router.use("/issue-cert-user-amplia", require("./issue-cert-user-amplia"));
router.use("/issue-cert-hosted-amplia", require("./issue-cert-hosted-amplia"));
router.use("/list-cert-select2", require("./list-cert-select2"));
router.use("/list-cert-jquery", require("./list-cert-jquery"));
router.use("/merge-cades-express", require("./merge-cades-express"));
Expand All @@ -43,6 +44,7 @@ router.use("/open-pades-express", require("./open-pades-express"));
router.use("/open-pades-restpki", require("./open-pades-restpki"));
router.use("/pades-server-key-express", require("./pades-server-key-express"));
router.use("/pades-signature-express", require("./pades-signature-express"));
router.use("/pades-hosted-key-express", require("./pades-hosted-key-express"));
router.use("/pades-signature-restpki", require("./pades-signature-restpki"));
router.use(
"/pades-wo-communication-restpki",
Expand Down
109 changes: 109 additions & 0 deletions nodejs/expressmvc/routes/issue-cert-hosted-amplia.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
const express = require('express');
const {PkiBrazilCertificateParameters, CreateOrderRequest, CertificateKinds, CreateKeyRequest} = require('amplia-client');
const uuidv4 = require('uuid/v4');
const {Config} = require('../config');
const {StorageMock} = require('../storage-mock');
const {Util} = require('../util.js');
const {KeyMedia, KeyTypes } = require('amplia-client/lib/enums');

let router = express.Router();

/**
* GET /issue-cert-hosted-amplia
*
* Renders issue certificate page, containing the form to be filled with the
* information to be used on certificate generation.
*/
router.get('/', (req, res, _next) => {
res.render('issue-cert-hosted-amplia');
});


/**
* POST /issue-cert-hosted-amplia
*
* Receives issueForm POST request, containing two parameters:
* - The subject name;
* - The CPF number.
*/
router.post('/', async (req, res, next) => {
try {

// Get Amplia configuration from config/{env}.js file, containing common
// parameters to generate the certificate.
const CONFIG = Config.getInstance().get('amplia');

// Get an instance of the AmpliaClient, responsible to connect with Amplia
// and perform the requests.
const client = Util.getAmpliaClient();

// Create an order request.
const request = new CreateOrderRequest({

// Set the certificate authority's id. This authority will generate your
// certificate. You can have a default CAId per application, in that case,
// there is no need to set this parameter.
caId: CONFIG['caId'],

// Set the certificate validity. We encapsulated the validity date
// definition on the getTwoYearsFromNowDate() method. We used the
// Util.formatDate() date method to parse to "MM-DD-YYYY" pattern accepted
// on Amplia.
validityEnd: Util.getTwoYearsFromNowDate(),

// Set the kind of the certificate.
kind: CertificateKinds.PUBLIC_KEY,

// Set the certificate parameters class with the desired parameters to
// your certificate. In this sample we'll use the PKI-BRAZIL standards.
parameters: new PkiBrazilCertificateParameters({

// Set the subject name.
name: req.body.subjectName,

// Set the CPF number.
cpf: req.body.cpf
})
});

// Create an order of issuing certificate on Amplia.
let order = await client.createOrder(request);

// Get an instance of the Key Generator class, responsible for generate
// a private key and the corresponding CSR.
var create = new CreateKeyRequest({
keyType:KeyTypes.RSA,
name : `${uuidv4()}`,
});

var key = await client.createRSAKey(create);

// Call Amplia in order to issue the certificate referred by the
// created order's id.
let cert = await client.issueCertificate(order.getId(),null, null, key.id);

// Get certificate's id, that will be used to identify the certificate
// on the "app-data" folder.
let certId = cert.getId();


// Store the key encrypted using a local key.
// WARNING: It is highly RECOMMENDED to ENCRYPT the key before storing
// in your database.
StorageMock.storeSync(key.rsaPublicParameters.modulus, certId, '.json');

// Store certificate.
StorageMock.storeSync(cert.getContentRaw(), certId, '.cer');

// Render complete page. We pass the certId responsible for locate the
// key and certificate files.
res.render('issue-cert-hosted-amplia/complete', {
certId: certId
});

} catch (err) {
next(err);
}
});

module.exports = router;
157 changes: 157 additions & 0 deletions nodejs/expressmvc/routes/pades-hosted-key-express.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
const express = require("express");
const path = require("path");
const uuidv4 = require("uuid/v4");
const {
PadesSignatureStarter,
StandardSignaturePolicies,
SignatureFinisher,
} = require("pki-express");
const {
PadesVisualElementsExpress,
} = require("../pades-visual-elements-express");
const {
PaginatedSearchParams,
SignHashRequest,
PaginatedSearchResponse,
CertificateSummary,
PaginationOrders,
} = require("amplia-client");
const { Config } = require("../config");
const { Util } = require("../util");
const { StorageMock } = require("../storage-mock");
const { result } = require("lodash");

const router = express.Router();
const APP_ROOT = process.cwd();

/**
* GET /pades-server-key-express
*
* This route only renders the signature page.
*/
router.get("/", async (req, res, next) => {
// Get parameters from url
const { fileId } = req.query;

// Verify if the provided fileId exists.
if (!StorageMock.existsSync({ fileId: fileId })) {
const notFound = new Error("The fileId was not found");
notFound.status = 404;
next(notFound);
return;
}
res.render('pades-hosted-key-express', { fileId })
});

router.post('/start', async (req, res, next) => {

const { fileId } = req.query;
const cpf = req.body.cpf;

// Get an instantiate of the PadesSignatureStarter class, responsible for
// receiving the signature elements and start the signature process.
const signer = new PadesSignatureStarter();

// Set PKI default options (see util.js).
Util.setPkiDefaults(signer);

// Get an instance of the AmpliaClient, responsible to connect with Amplia
// and perform the requests.
const client = Util.getAmpliaClient();

let params = new PaginatedSearchParams();
params.setOrder(PaginationOrders.DESC);
params.setLimit(1);
params.setQ(cpf.replace(/[.-]/g,""))

//Using the list certificate we colect the certificates
let listCert = await client.listCertificates(params, true);

let certificateResult = listCert.getItems()[0];

//Here we call the getCertificate function in order to get the certificate content
const cert = await client.getCertificate(certificateResult.getId(), true);

// Set signature policy.
signer.signaturePolicy = StandardSignaturePolicies.PADES_BASIC_WITH_LTV;

// Set PDF to be signed.
signer.setPdfToSignFromPathSync(StorageMock.getDataPath(fileId));

// Set a file reference for the stamp file. Note that this file can be
// referenced later by "fref://{alias}" at the "url" field on the
// visual representation (see public/vr.json or
// getVisualRepresentation() method).
signer.addFileReferenceSync("stamp", StorageMock.getPdfStampPath());

// Set the visual representation. We provided a dictionary that
// represents the visual representation JSON model.
signer.setVisualRepresentationSync(
PadesVisualElementsExpress.getVisualRepresentation()
);

// Set Base64-encoded certificate's content to signature starter.
signer.setCertificateFromBase64Sync(cert._contentBase64);

// Start the signature process.
let startResult = await signer.start()

const digestAlgorithm = Util.formatDigestAlgorithm(
startResult.digestAlgorithm
);

//Set the request using the response from the signer.start wich which has the
// hash to be signed and the digestAlgorithm.
let request = new SignHashRequest({
hash: startResult.toSignHash,
digestAlgorithm: digestAlgorithm,
});

//Now select the certificate to sign by passing his key and the request.
const signature = await client.signHashWithKey(
certificateResult.getKeyId(),
request
);

// Get an instance of the PadesSignatureFinisher class, responsible for
// completing the signature process.
const signatureFinisher = new SignatureFinisher();

// Set PKI default options (see util.js).
Util.setPkiDefaults(signatureFinisher);

// Set PDF to be signed. It's the same file we used on "start" step.
signatureFinisher.setFileToSignFromPathSync(
StorageMock.getDataPath(fileId)
);

// Set transfer file.
signatureFinisher.setTransferFileFromPathSync(startResult.transferFile);

// Set signature.
signatureFinisher.signature = signature.signature;

// Generate path for output file and add the signature finisher.
StorageMock.createAppDataSync(); // Make sure the "app-data" folder exists.
const outputFile = `${uuidv4()}.pdf`;
signatureFinisher.outputFile = path.join(APP_ROOT, 'app-data', outputFile);

// Complete the signature process.
const getCert = true;
signatureFinisher
.complete(getCert)
.then((result) => {
// After complete the signature, render the result page, passing the
// outputFile containing the signed file.
const certificate = result;
// Render the result page.
res.render("pades-hosted-key-express/complete", {
signedPdf: outputFile,
signer: certificate,
});
})
.catch((err) => next(err));

});

module.exports = router;
4 changes: 4 additions & 0 deletions nodejs/expressmvc/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,10 @@ class Util {
return array;
}

static formatDigestAlgorithm(digestAlgorithm) {
return digestAlgorithm.replace('-', '');
}

static formatDate(date) {
let day = date.getDate().toString();
let month = (date.getMonth() + 1).toString();
Expand Down
8 changes: 7 additions & 1 deletion nodejs/expressmvc/views/home/index.pug
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ block scripts
issueCertUser: {
amplia: '/check-amplia-api-key?rc=issue-cert-user'
},
issueCertHosted: {
amplia: '/check-amplia-api-key?rc=issue-cert-hosted'
},
listCert: {
select2: '/list-cert-select2',
jquery: '/list-cert-jquery'
Expand All @@ -36,6 +39,9 @@ block scripts
express: '/check-pki-express?rc=merge-server-files&fwd=merge-cades'
// restpki: ''
},
padesHostedKey: {
express: '/check-pki-express?rc=upload&fwd=pades-hosted-key'
},
printerFriendlyCms: {
express: '/check-pki-express?rc=upload&fwd=printer-version-cades'
// restpki: ''
Expand Down Expand Up @@ -124,4 +130,4 @@ block scripts

script(type='text/javascript', src='https://cdn.lacunasoftware.com/pki-suite-samples/runtime.29926b5c8448d756.js')
script(type='text/javascript', src='https://cdn.lacunasoftware.com/pki-suite-samples/polyfills.b6a2ec357e891889.js')
script(type='text/javascript', src='https://cdn.lacunasoftware.com/pki-suite-samples/main.3c1234946d8e0bef.js')
script(type='text/javascript', src='https://cdn.lacunasoftware.com/pki-suite-samples/main.43928010b5333845.js')
21 changes: 21 additions & 0 deletions nodejs/expressmvc/views/issue-cert-hosted-amplia/complete.pug
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
extends ../layout

block content

h2 Issue a certificate storing the private key on the server

p The certificate was successfully issued!

h3 Actions:

label
| Get public certificate file:
br
a(href=`/download/cert?fileId=${certId}`, target='_blank', class='btn btn-primary') Download

br
br
label
| Use the certificate to sign a PDF using:
br
a(href=`/upload?rc=pades-hosted-key-express`, class='btn btn-primary') PKI Express
Loading