You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中RSA解密实现异常,请求排查原因

RSA解密失败问题排查与修复

问题根源

你错误地使用**最小公倍数(lcm)**计算RSA所需的欧拉函数φ(n)。当p和q是不同素数时,正确的φ(n)计算公式应为:

φ(n) = (p - 1) * (q - 1)

在维基百科的示例中,p=61、q=53,正确的φ(n)是60*52=3120,而你用lcm算出的是780。错误的φ(n)导致计算出的私钥指数d不满足d*e ≡ 1 mod φ(n)的核心条件,因此解密无法得到原始明文。

修复后的代码

import { create, all } from 'mathjs';

// 初始化math.js
const config = {};
const math = create(all, config);

// 选择两个素数
const p = 61;
const q = 53;

// 计算n
const n = p * q;

// 计算正确的欧拉函数φ(n)
const phi = (p - 1) * (q - 1);
console.log(`phi(n) = ${phi}`);

// 选择公钥指数e(满足1<e<φ(n)且gcd(e,φ(n))=1)
const e = 17;

// 计算私钥指数d,满足d*e ≡1 mod φ(n)
const d = math.invmod(e, phi);
console.log(`d = ${d}`);

// 输出公钥
console.log(`Public key: (${e}, ${n})`);

function encryptMessage(message) {
    const encryptedMessage = math.mod(math.pow(math.bignumber(message), math.bignumber(e)), math.bignumber(n));
    console.log(`Encrypted message: ${encryptedMessage}`);
    return encryptedMessage;
}

function decryptMessage(message) {
    const decryptedMessage = math.mod(math.pow(math.bignumber(message), math.bignumber(d)), math.bignumber(n));
    console.log(`Decrypted message: ${decryptedMessage}`);
    return decryptedMessage;
}

// 测试加密解密
decryptMessage(encryptMessage(12));

验证结果

运行修复后的代码:

  • 加密12得到2690(与维基示例一致)
  • 解密2690得到12,符合预期

内容的提问来源于stack exchange,提问作者Felkru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:12:52