Signing is hashing the message, then raising the hash to the private exponent d modulo n. The signer checks the result with e before sending it.
What to build
Hash and sign each message with a toy RSA private key, and check each signature with the public exponent.
Requirements
- Line 1 is n d e.
- The toy hash of a message: start at 0, and for each character set h = (h × 31 + code) mod n.
- The signature is s = h^d mod n.
- For each message print
hash h signature s check valid(orcheck INVALIDif s^e mod n is not h, which means the key is wrong).
Input
Line 1: n d e. Each following line: a message.
Output
One line per message.
Constraints
n up to 10⁹; messages of 1 to 200 characters. Use BigInt for the powers.
Example
Input:
3233 2753 17
Result: CSE-2101 passed
Output:
hash 3101 signature 1227 check valid
Why it works
Raising to d and then to e returns the hash when d and e form a key pair, so the check line confirms the signature will verify; a mismatched d shows up at once as INVALID.
Examples
3233 2753 17 Result: CSE-2101 passed
hash 3101 signature 1227 check valid
3233 2753 17 Result: CSE-2101 failed A
hash 2705 signature 1981 check valid hash 65 signature 588 check valid
Hints
Hint 1
Compute the hash with ordinary numbers (h × 31 stays well inside safe numbers when h < 10⁹), then switch to BigInt for the power.
Hint 2
The lesson's example: n 3233, d 2753, message "Result: CSE-2101 passed" gives hash 3101 and signature 1227.
Solution
Show one correct solution (try it yourself first)
function modPow(b, e, m) {
let result = 1n % m;
b %= m;
while (e > 0n) {
if (e & 1n) result = (result * b) % m;
b = (b * b) % m;
e >>= 1n;
}
return result;
}
const [n, d, e] = prompt().trim().split(/\s+/).map(BigInt);
const nn = Number(n);
let line = prompt();
while (line !== null) {
let h = 0;
for (let k = 0; k < line.length; k++) h = (h * 31 + line.charCodeAt(k)) % nn;
const s = modPow(BigInt(h), d, n);
console.log(`hash ${h} signature ${s} check ${modPow(s, e, n) === BigInt(h) ? "valid" : "INVALID"}`);
line = prompt();
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step