Check signatures

To check an RSA signature, raise it to the public exponent e modulo n. If the result equals the message's hash, the signature is valid.

What to build

Check a list of hash and signature pairs against a public key.

Requirements

  • Line 1 is the public key: n e.
  • Each following line is a hash h and a signature s.
  • Print valid when s^e mod n equals h, otherwise INVALID.

Input

As described.

Output

One word per pair.

Constraints

n up to 10⁹; up to 20 pairs, each value below n. Use BigInt.

Example

Input:

3233 17
3101 1227
3101 1228

Output:

valid
INVALID

Why it works

A valid signature was made as h^d mod n with the private exponent, and raising it to e undoes that because e × d = 1 (mod φ(n)); anyone without d cannot make a number that comes back to h.

Examples

Example 1 · Input
3233 17
3101 1227
3101 1228
Expected output
valid
INVALID
Example 2 · Input
3233 17
65 2790
Expected output
INVALID

Hints

Hint 1

Reuse modPow with BigInt.

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, e] = prompt().trim().split(/\s+/).map(BigInt);
let line = prompt();
while (line !== null) {
  const [h, s] = line.trim().split(/\s+/).map(BigInt);
  console.log(modPow(s, e, n) === h ? "valid" : "INVALID");
  line = prompt();
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Digital signatures and certificates →