Skip to content

Instantly share code, notes, and snippets.

@matfish2
Last active November 19, 2022 07:11
Show Gist options
  • Save matfish2/c5d52e918bfab8f3c1b09c56f03e123b to your computer and use it in GitHub Desktop.
Save matfish2/c5d52e918bfab8f3c1b09c56f03e123b to your computer and use it in GitHub Desktop.
Get Digital Certificate from Node.js Server + Return to PSPDFKit's `signDocument` method
async function digitallySignDocument({fileContents}) {
const blob = new Blob([fileContents], {type: 'application/pdf'});
const formData = new FormData();
formData.append("file", blob);
let {data} = await axios.post('node-server-url.com', formData, {
'Content-Type': 'multipart/form-data'
})
return this.stringToArrayBuffer(data)
}
const express = require('express')
const busboy = require('connect-busboy')
const forge = require('node-forge')
const fs = require('fs')
const app = express()
let signed;
app.use(busboy())
app.post('/', function (req, res) {
req.pipe(req.busboy);
req.busboy.on('file', function (field, file) {
file.on('data', (pdfBuffer) => {
signed = generatePKCS7(pdfBuffer)
})
.on('close', () => {
res.send(signed)
})
})
})
app.listen(3000, function () {
console.log('Server is listening on port 3000');
});
// Takes a PDF ArrayBuffer and returns a digital signature
function generatePKCS7(buffer) {
const certificatePem = fs.readFileSync('./certs/cert.pem')
const privateKeyPem = fs.readFileSync('./certs/private-key.pem')
const certificate = forge.pki.certificateFromPem(
certificatePem
);
const privateKey = forge.pki.privateKeyFromPem(privateKeyPem);
const p7 = forge.pkcs7.createSignedData();
p7.content = new forge.util.ByteBuffer(buffer)
p7.addCertificate(certificate);
p7.addSigner({
key: privateKey,
certificate: certificate,
digestAlgorithm: forge.pki.oids.sha256,
authenticatedAttributes: [
{
type: forge.pki.oids.contentType,
value: forge.pki.oids.data
},
{
type: forge.pki.oids.messageDigest
},
{
type: forge.pki.oids.signingTime,
value: new Date()
}
]
});
p7.sign({detached: true});
return forge.asn1.toDer(p7.toAsn1()).getBytes()
}
try {
await instance.signDocument(null, digitallySignDocument)
} catch (e) {
console.error('Unable to digitally sign');
return;
}
// Converts binary string returned from Node.js to array buffer
function stringToArrayBuffer(binaryString) {
const buffer = new ArrayBuffer(binaryString.length);
let bufferView = new Uint8Array(buffer);
for (let i = 0, len = binaryString.length; i < len; i++) {
bufferView[i] = binaryString.charCodeAt(i);
}
return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment