【问题标题】:Custom RSA implementation in Javascript (NodeJS)Javascript (NodeJS) 中的自定义 RSA 实现
【发布时间】:2018-10-28 17:36:21
【问题描述】:

我尝试将 RSA 的基础知识实现到一个简单的 NodeJS/javascript 文件中。

我使用c = m^e % n进行加密。
对于解密,我使用了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))
})

加密进行得很顺利。但是,解密有一些问题。它显示了我在let message = 'hello' 部分中输入的其他字符

我在解密时做错了什么?

【问题讨论】:

    标签: javascript node.js encryption rsa


    【解决方案1】:
    encrypted.forEach(char => {
      const pow = Math.pow(char, d) // c^d
      const mod = pow % n // mod n
      console.log(String.fromCharCode(mod + 64))
    })
    

    在上面的函数中,pow 太大,精度丢失。 例如,在“L”的情况下:

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

    使用一种技术计算pow的mod而不损失精度,它可以正确解码。

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

    输出:

    H
    E
    L
    L
    O
    

    【讨论】:

      猜你喜欢
      • 2014-07-02
      • 2020-04-12
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 2019-04-28
      • 1970-01-01
      相关资源
      最近更新 更多