Node.js Sign Reference

Node.js

Sign Object

সাইন ক্লাস Node.js এর ক্রিপ্টো মডিউলের অংশ। এটি ক্রিপ্টোগ্রাফিক ডিজিটাল স্বাক্ষর তৈরি করার একটি উপায় প্রদান করে। সাইন ইভেন্টগুলি crypto.createSign() পদ্ধতি ব্যবহার করে তৈরি করা হয়।

ডিজিটাল স্বাক্ষর আপনাকে একটি বার্তার সত্যতা এবং অখণ্ডতা যাচাই করার অনুমতি দেয়, এটি নিশ্চিত করে যে এটি একটি পরিচিত প্রেরক দ্বারা তৈরি করা হয়েছে এবং ট্রানজিটে পরিবর্তন করা হয়নি৷

Import Crypto Module

// Import the crypto module
const crypto = require('crypto');

// Create a Sign object
const sign = crypto.createSign('RSA-SHA256');

Sign Methods

পদ্ধতি ব্যাখ্যা
sign.update(data[, inputEncoding]) প্রদত্ত ডেটা দিয়ে সাইন কন্টেন্ট আপডেট করে। যদি ইনপুট এনকোডিং প্রদান করা হয়, ডেটা নির্দিষ্ট এনকোডিং ব্যবহার করে একটি স্ট্রিং; অন্যথায়, ডেটা একটি বাফার, টাইপডঅ্যারে বা ডেটাভিউ। এই পদ্ধতিটি নতুন ডেটা সহ একাধিকবার কল করা যেতে পারে।
sign.sign(privateKey[, outputEncoding]) sign.update() . privateKey PEM- buffer, 'private' KeyObject . outputEncoding , ; , Buffer .

Basic Sign Example

নিম্নলিখিত উদাহরণটি ব্যাখ্যা করে কিভাবে একটি বার্তার একটি ডিজিটাল স্বাক্ষর তৈরি করতে হয়:

const crypto = require('crypto');
const fs = require('fs');

// Generate a keypair for this example
function generateKeyPair() {
  return crypto.generateKeyPairSync('rsa', {
    modulusLength: 2048,
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'pkcs8',
      format: 'pem'
    }
  });
}

// For this example, generate keys in memory
// In a real application, you would load existing keys from storage
const { privateKey, publicKey } = generateKeyPair();

// Message to sign
const message = 'This is a message to be signed';

// Create a Sign object
const sign = crypto.createSign('SHA256');

// Update with the message
sign.update(message);

// Sign the message with the private key
const signature = sign.sign(privateKey, 'hex');

console.log('Message:', message);
console.log('Signature:', signature);

// We'll save these for the verification example
fs.writeFileSync('message.txt', message);
fs.writeFileSync('signature.hex', signature);
fs.writeFileSync('public_key.pem', publicKey);

Signing with Different Algorithms

সাইন ক্লাস প্রদত্ত ক্রিপ্টোর উপর নির্ভর করে বিভিন্ন স্বাক্ষর অ্যালগরিদম সমর্থন করে:

const crypto = require('crypto');

// Generate key pairs for different algorithms
function generateRSAKeyPair() {
  return crypto.generateKeyPairSync('rsa', {
    modulusLength: 2048,
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'pkcs8',
      format: 'pem'
    }
  });
}

function generateECKeyPair() {
  return crypto.generateKeyPairSync('ec', {
    namedCurve: 'prime256v1',
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'sec1',
      format: 'pem'
    }
  });
}

// Generate different key pairs
const rsaKeys = generateRSAKeyPair();
const ecKeys = generateECKeyPair();

// Message to sign
const message = 'Message to sign with different algorithms';

// Function to sign with a specific algorithm
function signWithAlgorithm(algorithm, privateKey, message) {
  try {
    const sign = crypto.createSign(algorithm);
    sign.update(message);
    return sign.sign(privateKey, 'hex');
  } catch (error) {
    return `Error: ${error.message}`;
  }
}

// Test various signature algorithms
console.log(`Message: "${message}"`);
console.log('-----------------------------------------------');

// RSA signatures with different hash algorithms
console.log('RSA-SHA256:', signWithAlgorithm('SHA256', rsaKeys.privateKey, message));
console.log('RSA-SHA384:', signWithAlgorithm('SHA384', rsaKeys.privateKey, message));
console.log('RSA-SHA512:', signWithAlgorithm('SHA512', rsaKeys.privateKey, message));

console.log('-----------------------------------------------');

// ECDSA signatures
console.log('ECDSA-SHA256:', signWithAlgorithm('SHA256', ecKeys.privateKey, message));
console.log('ECDSA-SHA384:', signWithAlgorithm('SHA384', ecKeys.privateKey, message));

স্বাক্ষর অ্যালগরিদম আপনার Node.js সংস্করণ এবং ইনস্টল করা OpenSSL সংস্করণের উপর নির্ভর করে। সাধারণ স্বাক্ষর অ্যালগরিদম অন্তর্ভুক্ত:

অ্যালগরিদম ব্যাখ্যা মূল প্রকার
RSA-SHA256 SHA-256 হ্যাশ সহ RSA স্বাক্ষর RSA
RSA-SHA384 SHA-384 হ্যাশ সহ RSA স্বাক্ষর RSA
RSA-SHA512 SHA-512 হ্যাশ সহ RSA স্বাক্ষর RSA
RSA-PSS-SHA256 SHA-256 হ্যাশ সহ RSA-PSS স্বাক্ষর RSA
ECDSA-SHA256 SHA-256 হ্যাশ সহ ECDSA স্বাক্ষর EC
ECDSA-SHA384 SHA-384 হ্যাশ সহ ECDSA স্বাক্ষর EC
Ed25519 Curve25519 ব্যবহার করে EdDSA স্বাক্ষর Ed25519
Ed448 Curve448 ব্যবহার করে EdDSA স্বাক্ষর Ed448

Signing with Multiple Updates

স্বাক্ষর গণনা করার আগে একটি সাইন অবজেক্ট একাধিক ডেটার সাথে আপডেট করা যেতে পারে:

const crypto = require('crypto');

// Generate a keypair for this example
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

// Create a Sign object
const sign = crypto.createSign('SHA256');

// Update with multiple pieces of data
sign.update('First part of the message. ');
sign.update('Second part of the message. ');
sign.update('Third part of the message.');

// Create the signature
const signature = sign.sign(privateKey, 'hex');

console.log('Combined message: First part of the message. Second part of the message. Third part of the message.');
console.log('Signature:', signature);

// You can achieve the same result with a single update
const singleSign = crypto.createSign('SHA256');
singleSign.update('First part of the message. Second part of the message. Third part of the message.');
const singleSignature = singleSign.sign(privateKey, 'hex');

console.log('Single update signature matches multiple updates?', singleSignature === signature);

Signing Files

আপনি একটি ফাইলের বিষয়বস্তুর জন্য একটি ডিজিটাল স্বাক্ষর তৈরি করতে পারেন:

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);
  });

Using Different Types of Keys

সাইন ক্লাস ব্যক্তিগত কীগুলির বিভিন্ন বিন্যাসের সাথে কাজ করতে পারে:

const crypto = require('crypto');

// Message to sign
const message = 'Message to sign with different key formats';

// Function to sign with different key formats
function signWithKey(privateKey, keyFormat) {
  try {
    const sign = crypto.createSign('SHA256');
    sign.update(message);
    return {
      format: keyFormat,
      signature: sign.sign(privateKey, 'hex')
    };
  } catch (error) {
    return {
      format: keyFormat,
      error: error.message
    };
  }
}

// Generate a new RSA key pair
const { privateKey: pemPrivateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

console.log(`Message: "${message}"`);

// 1. Sign with PEM-encoded private key (string)
console.log('\n1. PEM-encoded private key (string):');
console.log(signWithKey(pemPrivateKey, 'PEM string'));

// 2. Sign with PEM-encoded private key (buffer)
console.log('\n2. PEM-encoded private key (buffer):');
console.log(signWithKey(Buffer.from(pemPrivateKey), 'PEM buffer'));

// 3. Sign with KeyObject
console.log('\n3. KeyObject:');
const keyObject = crypto.createPrivateKey(pemPrivateKey);
console.log(signWithKey(keyObject, 'KeyObject'));

// 4. Sign with PassThrough crypto engine (if available)
try {
  // Note: This might not be available in all Node.js versions/configurations
  console.log('\n4. Private key with engine:');
  const engineKey = {
    key: pemPrivateKey,
    padding: crypto.constants.RSA_PKCS1_PADDING
  };
  console.log(signWithKey(engineKey, 'Key with options'));
} catch (error) {
  console.log('\n4. Private key with engine:');
  console.log({ format: 'Key with options', error: error.message });
}

// 5. Sign with JSON Web Key (JWK)
// Note: This requires conversion, as Node.js doesn't directly support JWK for sign
console.log('\n5. JWK (requires conversion):');
try {
  // This is a simplified example - actual JWK handling would be more complex
  const pemToJwk = require('pem-jwk').pem2jwk; // You would need to install this package
  const jwk = pemToJwk(pemPrivateKey);
  console.log({ format: 'JWK', note: 'JWK needs to be converted to PEM or KeyObject first' });
} catch (error) {
  console.log({ format: 'JWK', note: 'Example requires pem-jwk package' });
}

Complete Sign and Verify Example

এই উদাহরণটি একটি ডিজিটাল স্বাক্ষর তৈরি এবং যাচাই করার সম্পূর্ণ প্রক্রিয়াটি ব্যাখ্যা করে:

const crypto = require('crypto');

// Generate a keypair
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

// Original message
const message = 'This is the original message to sign and verify';
console.log(`Original message: "${message}"`);

// Sign the message
function signMessage(message, privateKey) {
  const sign = crypto.createSign('SHA256');
  sign.update(message);
  return sign.sign(privateKey, 'hex');
}

const signature = signMessage(message, privateKey);
console.log(`Signature: ${signature}`);

// Verify the message (using the Verify class)
function verifySignature(message, signature, publicKey) {
  const verify = crypto.createVerify('SHA256');
  verify.update(message);
  return verify.verify(publicKey, signature, 'hex');
}

// Verify the original message
const isValidOriginal = verifySignature(message, signature, publicKey);
console.log(`Original message verification: ${isValidOriginal}`);

// Try to verify a tampered message
const tamperedMessage = message + ' with some tampering';
const isValidTampered = verifySignature(tamperedMessage, signature, publicKey);
console.log(`Tampered message verification: ${isValidTampered}`);

// Try to use a different public key
const { publicKey: differentPublicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

const isValidDifferentKey = verifySignature(message, signature, differentPublicKey);
console.log(`Verification with different public key: ${isValidDifferentKey}`);

DSA and ECDSA Signatures

এই উদাহরণটি ডিজিটাল স্বাক্ষরের জন্য DSA এবং ECDSA-এর ব্যবহারকে চিত্রিত করে:

const crypto = require('crypto');

// Message to sign
const message = 'Message for DSA and ECDSA signatures';

// Generate ECDSA key pair
function generateECKeyPair(curveName = 'prime256v1') {
  return crypto.generateKeyPairSync('ec', {
    namedCurve: curveName,
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'sec1', // or 'pkcs8'
      format: 'pem'
    }
  });
}

// Function to sign and verify with a specific algorithm and key pair
function testSignatureAlgorithm(algorithm, keyType, keyPair, message) {
  try {
    // Sign the message
    const sign = crypto.createSign(algorithm);
    sign.update(message);
    const signature = sign.sign(keyPair.privateKey, 'hex');
    
    // Verify the signature
    const verify = crypto.createVerify(algorithm);
    verify.update(message);
    const isValid = verify.verify(keyPair.publicKey, signature, 'hex');
    
    return {
      algorithm: `${keyType}-${algorithm}`,
      signatureLength: signature.length / 2, // Convert hex to bytes
      isValid
    };
  } catch (error) {
    return {
      algorithm: `${keyType}-${algorithm}`,
      error: error.message
    };
  }
}

// Test ECDSA with different curves
const curves = ['prime256v1', 'secp384r1', 'secp521r1'];

console.log(`Message: "${message}"`);
console.log('\nECDSA Signatures:');

curves.forEach(curve => {
  const ecKeyPair = generateECKeyPair(curve);
  
  // Test with different hash algorithms
  const hashAlgos = ['SHA256', 'SHA384', 'SHA512'];
  
  hashAlgos.forEach(hashAlgo => {
    const result = testSignatureAlgorithm(hashAlgo, `ECDSA-${curve}`, ecKeyPair, message);
    console.log(result);
  });
});

// Test EdDSA if available
try {
  console.log('\nEdDSA Signatures:');
  
  // Ed25519
  const ed25519KeyPair = crypto.generateKeyPairSync('ed25519', {
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'pkcs8',
      format: 'pem'
    }
  });
  
  // Sign with Ed25519
  const sign = crypto.createSign('SHA512'); // Hash algorithm is ignored for Ed25519
  sign.update(message);
  const signature = sign.sign(ed25519KeyPair.privateKey, 'hex');
  
  // Verify with Ed25519
  const verify = crypto.createVerify('SHA512');
  verify.update(message);
  const isValid = verify.verify(ed25519KeyPair.publicKey, signature, 'hex');
  
  console.log({
    algorithm: 'Ed25519',
    signatureLength: signature.length / 2,
    isValid
  });
} catch (error) {
  console.log({
    algorithm: 'Ed25519',
    error: error.message
  });
}

Signing with OpenSSL Options

নির্দিষ্ট OpenSSL বিকল্পগুলির সাথে উন্নত স্বাক্ষর:

const crypto = require('crypto');

// Generate RSA key pair
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
});

// Message to sign
const message = 'Message to sign with different options';

// Function to sign with specific options
function signWithOptions(algorithm, message, privateKey, options = {}) {
  try {
    // Create private key with options
    const keyWithOptions = {
      key: privateKey,
      ...options
    };
    
    // Sign the message
    const sign = crypto.createSign(algorithm);
    sign.update(message);
    return sign.sign(keyWithOptions, 'hex');
  } catch (error) {
    return `Error: ${error.message}`;
  }
}

console.log(`Message: "${message}"`);
console.log('\nRSA Signatures with Different Options:');

// 1. Standard PKCS#1 v1.5 padding (default)
console.log('\n1. Standard PKCS#1 v1.5 padding:');
const sig1 = signWithOptions('SHA256', message, privateKey);
console.log(sig1);

// 2. PSS padding
console.log('\n2. PSS padding:');
const sig2 = signWithOptions('SHA256', message, privateKey, {
  padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
  saltLength: 32
});
console.log(sig2);

// 3. Different salt lengths with PSS padding
console.log('\n3. PSS padding with different salt lengths:');
[20, 32, 48].forEach(saltLength => {
  try {
    const sigSalt = signWithOptions('SHA256', message, privateKey, {
      padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
      saltLength
    });
    console.log(`Salt length ${saltLength}: ${sigSalt.substring(0, 64)}...`);
  } catch (error) {
    console.log(`Salt length ${saltLength}: Error - ${error.message}`);
  }
});

// 4. Try to use no padding (will likely fail for signatures)
console.log('\n4. No padding (expect error):');
const sig4 = signWithOptions('SHA256', message, privateKey, {
  padding: crypto.constants.RSA_NO_PADDING
});
console.log(sig4);

Security Best Practices

ডিজিটাল স্বাক্ষর ব্যবহার করার সময় এই নিরাপত্তার সর্বোত্তম অনুশীলনগুলি বিবেচনা করুন:

শক্তিশালী কী ব্যবহার করুন:RSA-এর জন্য, কমপক্ষে 2048 বিট ব্যবহার করুন। ECDSA এর জন্য, prime256v1 (P-256) বা শক্তিশালী বক্ররেখা ব্যবহার করুন।
আধুনিক স্বাক্ষর অ্যালগরিদম ব্যবহার করুন:PKCS#1 v1.5 এর চেয়ে RSA-PSS পছন্দ করুন এবং আরও ভালো পারফরম্যান্সের জন্য ECDSA বা EdDSA বিবেচনা করুন।
ব্যক্তিগত কী রক্ষা করুন:ব্যক্তিগত কীগুলি নিরাপদে সংরক্ষণ করতে, আপনি একটি হার্ডওয়্যার সুরক্ষা মডিউল (এইচএসএম) বা একটি কী ব্যবস্থাপনা পরিষেবা ব্যবহার করতে পারেন।
শক্তিশালী হ্যাশ অ্যালগরিদম ব্যবহার করুন:মৌলিক হ্যাশ ফাংশনের জন্য সর্বদা SHA-256 বা শক্তিশালী ব্যবহার করুন।
স্বাক্ষর করার আগে ডেটা যাচাই করুন:নিশ্চিত করুন যে আপনি যে ডেটাতে স্বাক্ষর করেছেন তা দূষিত সামগ্রীতে স্বাক্ষর করা এড়ানোর উদ্দেশ্যে করা হয়েছে৷
বল চক্র নোট করুন:আপনার স্বাক্ষর কীগুলি নিয়মিত আপডেট করুন, বিশেষ করে দীর্ঘমেয়াদী অ্যাপ্লিকেশনের জন্য।
কী অবজেক্ট ব্যবহার করুন:যদি সম্ভব হয়, ভাল নিরাপত্তার জন্য KeyObject API ব্যবহার করুন এবং সংবেদনশীল কী অবজেক্টকে সরাসরি অ্যাক্সেসযোগ্য হতে বাধা দিন।

Common Use Cases for Digital Signatures

Code Signing

সফ্টওয়্যার প্যাকেজ, এক্সিকিউটেবল ফাইল বা স্ক্রিপ্টগুলি তাদের সত্যতা এবং অখণ্ডতা যাচাই করতে স্বাক্ষর করা

Document Signing

পিডিএফ এবং অন্যান্য নথিগুলির জন্য আইনত বাধ্যতামূলক বৈদ্যুতিন স্বাক্ষর তৈরি করুন

JWT Signing

নিরাপদ প্রমাণীকরণ এবং অনুমোদনের জন্য JSON ওয়েব টোকেন (JWTs) স্বাক্ষর করা

API Authentication

API ক্লায়েন্টদের পরিচয় যাচাই করা এবং অনুরোধের অখণ্ডতা নিশ্চিত করা

Certificate Signing

একটি PKI সিস্টেমে সার্টিফিকেট চেইন তৈরি এবং যাচাই করা

Secure Communication

সুরক্ষিত যোগাযোগ প্রোটোকলগুলিতে বার্তাগুলির প্রমাণীকরণ

অনুশীলন করুন

Node.js SHA256 Sign .

crypto.createSign('SHA256', privateKey)
✗ ভুল! "crypto.createSign()" পদ্ধতিতে একটি কী প্রয়োজন হয় না, এটি শুধুমাত্র একটি স্বাক্ষর তৈরি করার সময় প্রয়োজন হয়
crypto.createSign('SHA256')
✓ ঠিক আছে! "crypto.createSign('SHA256')" হল সঠিক পদ্ধতি যা Node.js-এ SHA256 অ্যালগরিদম দিয়ে একটি সাইন ইভেন্ট তৈরি করতে ব্যবহৃত হয়
crypto.makeSign('SHA256')
✗ ভুল! "crypto.makeSign()" Node.js-এ একটি বৈধ পদ্ধতি নয়
crypto.newSign('SHA256')
✗ ভুল! "crypto.newSign()" Node.js-এ একটি বৈধ পদ্ধতি নয়