Digital Signature Simulator - Problem

Implement a digital signature system that can sign messages with a private key and verify signatures with a public key.

Your task is to create a simplified RSA-based digital signature simulator with the following operations:

  • generateKeys(keySize) - Generate RSA public/private key pair
  • signMessage(message, privateKey) - Sign a message using private key
  • verifySignature(message, signature, publicKey) - Verify signature using public key

For this problem, you'll implement the verification function that takes a message, its signature, and a public key, then returns true if the signature is valid, false otherwise.

The signature verification process involves:

  1. Hash the original message using SHA-256
  2. Decrypt the signature using the public key
  3. Compare the decrypted hash with the computed message hash

Input & Output

Example 1 — Valid Signature
$ Input: message = "Hello", signature = 12345, publicKey = {"n": 65537, "e": 3}
Output: true
💡 Note: The signature was created using the corresponding private key. When we hash "Hello" and decrypt the signature 12345 with public key (n=65537, e=3), the hashes match, confirming authenticity.
Example 2 — Invalid Signature
$ Input: message = "Hello", signature = 54321, publicKey = {"n": 65537, "e": 3}
Output: false
💡 Note: The signature 54321 was not created with the corresponding private key. When decrypted, it produces a hash that doesn't match the hash of "Hello", indicating forgery.
Example 3 — Different Message
$ Input: message = "Goodbye", signature = 98765, publicKey = {"n": 65537, "e": 3}
Output: false
💡 Note: Even if the signature was valid for a different message, it fails verification for "Goodbye" because the message hash doesn't match the decrypted signature hash.

Constraints

  • 1 ≤ message.length ≤ 1000
  • 1 ≤ signature ≤ 1018
  • publicKey contains valid RSA parameters n and e
  • 1 ≤ n ≤ 1018
  • 1 ≤ e ≤ 106

Visualization

Tap to expand
INPUTALGORITHMRESULTMessage"Hello"Signature12345Public Keyn: 65537e: 31Hash MessageCompute SHA-256hash of "Hello"2Decrypt SignatureUse RSA public key:12345^3 mod 655373Compare HashesMessage hash ==Decrypted hash?INVALIDHashes don't matchMessage: hash_msgDecrypt: hash_sighash_msg ≠ hash_sigKey Insight:Digital signatures work because only the private key can create signatures that decrypt correctly with the public keyTutorialsPoint - Digital Signature Simulator | Hash-then-Decrypt Verification
Asked in
Amazon 25 Microsoft 18 Google 15 Meta 12
23.4K Views
Medium Frequency
~35 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen