📄 rsa-encrypt.js
字号:
///////////////////////////////////////////////////////////////////
// RSA Public-Key Encryption Script
// --------------------------------
//
// This JScript code shows an example of RSA public-key encryption
// with artificially small parameters.
//
// The example is taken from Handbook of Applied Cryptography (8.2,
// p287), by A. Menezes, P. van Oorschot, and S. Vanstone, CRC
// Press, 1996.
//
// Summary: B encrypts a message m for A, which A decrypts.
//
// 1. Key generation. A should do the following:
//
// (a) Choose two primes p, q.
// (b) Compute n = pq and f = (p-1)(q-1).
// (c) Choose e and find d such that ed = 1 (mod f).
//
// A's public key is the pair (n, e), while A's private key is d.
//
// 2. Encryption. B should do the following:
//
// (a) Obtain A's authentic public key (n, e).
// (b) Represent the message as an integer m in the interval [0, n-1].
// (c) Compute c = m^e mod n.
// (d) Send the ciphertext c to A.
//
// 3. Decryption. To recover plaintext m from c, A should do the
// following:
//
// (a) Use the private key d to recover m = c^d mod n.
//
///////////////////////////////////////////////////////////////////
var strHexP, strHexQ, strHexP1, strHexQ1
var strHexN, strHexF, strHexE, strHexD
var strHexC, strHexMB, strHexMA
//
// 1. Key generation
//
// (a) A chooses the primes p = 2357, q = 2551.
strHexP = "09 35"
strHexQ = "09 f7"
strHexP1 = "09 34"
strHexQ1 = "09 f6"
//
// (b) A computes n = pq = 6012707 and f = (p-1)(q-1) = 6007800.
strHexN = Hpmbmath.Multiply(strHexP, strHexQ)
strHexF = Hpmbmath.Multiply(strHexP1, strHexQ1)
//
// (c) A chooses e = 3674911 and finds d = 422191 such that
// ed = 1 (mod f).
strHexE = "38 13 1f"
strHexD = Hpmbmath.ModInverse(strHexE, strHexF)
//
// 2. Encryption
//
// (a) To encrypt a message m = 5234673
strHexMB = "4f df f1"
//
// (b) B computes c = m^e mod n = 5234673^3674911 mod 6012707 =
// 3650502
strHexC = Hpmbmath.ModPow(strHexMB, strHexE, strHexN)
//
// (c) B sends c to A.
//
// 3. Decryption
//
// (a) To encrypt c, A computes c^d mod n = 3650502^422191 mod
// 6012707 = 5234673
strHexMA = Hpmbmath.ModPow(strHexC, strHexD, strHexN)
// If all go well, strHexMA and strHexMB should have same value
Hpmbmath.Output("MB = " + strHexMB)
Hpmbmath.Output("MA = " + strHexMA)
Hpmbmath.Output("\r\nMA should be same as MB.")
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -