下面是一个使用JavaScript实现RSA算法的例子:

// 导入jsbn库,该库提供了实现RSA算法所需的大数运算的功能
const BigInteger = require('jsbn').BigInteger;

// 生成RSA密钥对
function generateRSAKeyPair() {
  // 随机生成两个大素数 p 和 q
  const p = BigInteger.probablePrime(512, new SecureRandom());
  const q = BigInteger.probablePrime(512, new SecureRandom());

  // 计算 n = p * q
  const n = p.multiply(q);

  // 计算 φ(n) = (p - 1) * (q - 1)
  const phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

  // 随机选择一个整数 e 作为公钥,要求 1 < e < φ(n),且 e 和 φ(n) 互质
  const e = BigInteger.probablePrime(512, new SecureRandom());

  // 计算 d = e^(-1) mod φ(n),即 e 关于模 φ(n) 的乘法逆元
  const d = e.modInverse(phi);

  // 返回公钥和私钥
  return {
    publicKey: {
      e: e.toString(16),
      n: n.toString(16)
    },
    privateKey: {
      d: d.toString(16),
      n: n.toString(16)
    }
  };
}

// 使用公钥加密
function encryptRSA(plaintext, publicKey) {
  const e = new BigInteger(publicKey.e, 16);
  const n = new BigInteger(publicKey.n, 16);

  // 将明文转换为大整数
  const m = new BigInteger(plaintext);

  // 加密算法:c = m^e mod n
  const c = m.modPow(e, n);

  // 返回密文
  return c.toString(16);
}

// 使用私钥解密
function decryptRSA(ciphertext, privateKey) {
  const d = new BigInteger(privateKey.d, 16);
  const n = new BigInteger(privateKey.n, 16);

  // 将密文转换为大整数
  const c = new BigInteger(ciphertext, 16);

  // 解密算法:m = c^d mod n
  const m = c.modPow(d, n);

  // 返回解密后的明文
  return m.toString();
}

// 测试代码
const plaintext = 'Hello, RSA!';
const keyPair = generateRSAKeyPair();
console.log('公钥:', keyPair.publicKey);
console.log('私钥:', keyPair.privateKey);

const ciphertext = encryptRSA(plaintext, keyPair.publicKey);
console.log('密文:', ciphertext);

const decryptedText = decryptRSA(ciphertext, keyPair.privateKey);
console.log('解密后的明文:', decryptedText);

这段代码实现了RSA算法的生成密钥对、加密和解密功能。首先调用generateRSAKeyPair()生成RSA密钥对,然后使用公钥加密明文,最后使用私钥解密密文

给我个JS RSA算法例子

原文地址: http://www.cveoy.top/t/topic/iDkQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录