const crypto = require('crypto');
const fs = require('fs');
// Function to sign a file
function signFile(filePath, privateKey, algorithm = 'SHA256') {
return new Promise((resolve, reject) => {
// Create Sign object
const sign = crypto.createSign(algorithm);
// Create read stream
const readStream = fs.createReadStream(filePath);
// Handle stream events
readStream.on('data', (data) => {
sign.update(data);
});
readStream.on('end', () => {
// Create signature
const signature = sign.sign(privateKey, 'hex');
resolve(signature);
});
readStream.on('error', (error) => {
reject(error);
});
});
}
// Generate a keypair for this example
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
// Save the public key for verification
fs.writeFileSync('public_key_file.pem', publicKey);
// Example usage (adjust file path as needed)
const filePath = 'example_to_sign.txt';
// Create a test file if it doesn't exist
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, 'This is a test file for digital signature.\n'.repeat(100));
console.log(`Created test file: ${filePath}`);
}
// Sign the file
signFile(filePath, privateKey)
.then(signature => {
console.log(`File: ${filePath}`);
console.log(`Signature: ${signature}`);
// Save the signature for later verification
fs.writeFileSync(`${filePath}.sig`, signature);
console.log(`Signature saved to: ${filePath}.sig`);
})
.catch(error => {
console.error('Error signing file:', error.message);
});