What is the correct way to add a digital signature in a pdf? in practice. Do we save the private key in our company's database because it can be used to decrypt or verify a signature later. since only the public key can be used to encrypt data. please offer some advice.
const fs = require("fs");
const path = require("path");
// display pdf buffer
const pdfBuffer = fs.readFileSync(path.join(__dirname, "test.pdf"));
// generate a rsa key pair
const { generateKeyPairSync } = require("crypto");
const { publicKey, privateKey } = generateKeyPairSync("rsa", {
modulusLength: 4096,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
cipher: "aes-256-cbc",
passphrase: "top secret",
},
});
const text = "Name of the person signing the document";
// encrypt text
const { publicEncrypt } = require("crypto");
const encryptedText = publicEncrypt(
{
key: publicKey,
},
Buffer.from(text)
);
// decrypt encrypted text using private key
const { privateDecrypt } = require("crypto");
const decryptedText = privateDecrypt(
{
key: privateKey,
passphrase: "top secret",
},
encryptedText
);
// add the encryptedText to the pdf buffer
const pdfBufferWithEncryptedText = Buffer.concat([pdfBuffer, encryptedText]);
// save the pdf buffer with encrypted text
fs.writeFileSync(
path.join(__dirname, "test-encrypted.pdf"),
pdfBufferWithEncryptedText
);