Last active
September 11, 2023 08:51
-
-
Save wuriyanto48/32738d48682302562fcc86bebc16b48b to your computer and use it in GitHub Desktop.
[NodeJs] RSA Digital signature to PDF file with QRCODE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
dependencies: