[英]Custom RSA implementation in Javascript (NodeJS)
我试图将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'
部分
我在解密时出了什么问题?
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 }
使用一种在不损失精度的情况下计算功率的模数的技术,它可以正确解码。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.