Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Last active September 11, 2023 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wuriyanto48/32738d48682302562fcc86bebc16b48b to your computer and use it in GitHub Desktop.
Save wuriyanto48/32738d48682302562fcc86bebc16b48b to your computer and use it in GitHub Desktop.
[NodeJs] RSA Digital signature to PDF file with QRCODE
const fs = require('fs');
const qrcode = require('qrcode');
const { rsa, rsaSign } = require('crypsi');
const { PDFDocument } = require('pdf-lib');
const main = () => {
return new Promise((resolve, reject) => {
const privateKeyData = fs.readFileSync('private_key_pkcs8.key');
const publicKeyData = fs.readFileSync('public.key');
const pdfBuffer = fs.readFileSync('pdf_file.pdf');
// sign pdf file
const signature = rsaSign.
signWithPSSSha256(rsa.loadPrivateKey(privateKeyData), pdfBuffer);
// save signature to database
console.log(signature);
// create short version of signature
const signatureShort = signature.substring(0, 40);
console.log(signatureShort);
// append with your verification routes HTTP REST API
const apiURL = 'https://api.yoursite.com/verify-signature';
// create qr code
qrcode.toBuffer(`${apiURL}/${signatureShort}`, async (err, qrData) => {
if (err) {
reject(err);
return;
}
try {
const pdfDoc = await PDFDocument.load(pdfBuffer);
const firstPage = pdfDoc.getPages()[0];
// Get the width and height of the first page
const { width, height } = firstPage.getSize();
const qrImage = await pdfDoc.embedPng(qrData);
const qrDims = qrImage.scale(0.5);
firstPage.drawImage(qrImage, {
x: 25,
y: 25,
width: qrDims.width,
height: qrDims.height,
opacity: 0.90,
});
const pdfBufferOutput = await pdfDoc.save();
fs.writeFile('pdf_file_out.pdf', pdfBufferOutput, 'binary', (err) => {
if (err) {
reject(err);
return;
}
resolve('ok');
});
} catch(e) {
reject(r);
return;
}
});
});
};
main().then(r => console.log(r)).catch(e => console.log(e));
@wuriyanto48
Copy link
Author

dependencies:

npm install --save qrcode
npm install --save pdf-lib
npm install --save crypsi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment