1

I've tried to implement the basics of RSA into a simple NodeJS / javascript file.

For encrypting I've used c = m^e % n.
For decrypting I've used m = c^d % n.

const p = 7; // choice prime
const q = 13; // choice prime
const n = p * q;
const e = 5; // choice
const Ke = [e, n]; // the private key
const d = 29; // choice
const Kd = [d, n]; // the public key

let message = 'hello'
let encrypted = []

message = message.toUpperCase()

for (let i = 0; i < message.length; i++) {
  const char = message.charCodeAt(i) - 64 // m
  const pow = Math.pow(char, e) // m^e
  const mod = pow % n // mod n
  encrypted[i] = mod
}

encrypted.forEach(char => {
  const pow = Math.pow(char, d) // c^d
  const mod = pow % n // mod n
  console.log(String.fromCharCode(mod + 64))
})

The encrypting goes well. However, the decrypting has some issues. It shows other characters then I've put in in the let message = 'hello' part

What am I doing wrong with decrypting?

1 Answer 1

2
encrypted.forEach(char => {
  const pow = Math.pow(char, d) // c^d
  const mod = pow % n // mod n
  console.log(String.fromCharCode(mod + 64))
})

In above function, pow is too large and precision is lost. For example, in the case of 'L':

{ char: 38, d: 29, pow: 6.512148596632774e+45, mod: 81 }

Using a technique to calculate the mod of pow without losing precision, it can decode correctly.

encrypted.forEach(char => {
  let mod = 1
  for (let i = 0; i < d; i++) {
    mod = (mod * char) % n
  }
  console.log(String.fromCharCode(mod + 64))
})

output:

H
E
L
L
O
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.