RSA解密在Javascript中是如何工作的?

nhjlsmyf  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(137)

我按照wikipedia的例子来实现它,我使用mathjs来解决Math库的无限问题。我上次检查时加密的值与wikipedias相同,但解密不起作用。我不打算使用我的实现。这只是为了学习目的。

import { lcm } from './lcm.js';
import { create, all } from 'mathjs';

// instantiate math.js
const config = {};
const math = create(all, config);

// choose two large prime numbers
const p = 61;
const q = 53;

// calculate n
const n = p * q;

// compute least common multiple of p - 1 and q - 1
const phi = lcm(p - 1, q - 1);
console.log(`phi(n) = ${phi}`);

// choose a number e such that 1 < e < phi(n) and gcd(e, phi(n)) = 1
const e = 17;

// calculate d such that d * e = 1 mod phi(n)
const d = math.invmod(e, phi);
console.log(`d = ${d}`)

// print public key
console.log(`Public key: (${e}, ${n})`);

function encryptMessage(message) {
    // encrypt message using public key
    const encryptedMessage = math.mod(math.pow(math.bignumber(message), math.bignumber(e)), math.bignumber(n));

    // print encrypted message
    console.log(`Encrypted message: ${encryptedMessage}`);
    return encryptedMessage;
}

function decryptMessage(message) {
    console.log(message, d, n)
    // decrypt message using private key
    const decryptedMessage = math.mod(math.pow(math.bignumber(message), math.bignumber(d)), math.bignumber(n));
    console.log(math.pow(math.bignumber(message), math.bignumber(d)))

    // print decrypted message
    console.log(`Decrypted message: ${decryptedMessage}`);
}

// encrypt and decrypt message
decryptMessage(encryptMessage(12));

我期望输出是12,但它不是。你能帮我弄清楚为什么吗?

efzxgjgh

efzxgjgh1#

试试这边
//计算d使得d*e=1 mod phi(n)

const d = math.modInv(e, phi);

相关问题