作者: Great Eagle 最近小E在学习计算机网络,对其中的RSA加密算法产生了兴趣。然而书中并没有对此算法进行介绍,只是一笔带过。于是,小E来请教老师。 游戏 


























算法面试题提示:不知道如何计算27^27 mod 55的读者,请移步《超级次方取模问题》。 













点评:本文介绍了RSA算法的工作机理。与此相关的一种攻击叫做中间人攻击,而https协议中的数字签名机制就是来应对这种攻击的。本文不再对中间人攻击展开介绍,有兴趣的读者可以自行阅读相关资料。另外,值得一提的是,假如未来量子计算机得到普及,那么RSA算法将不再安全,使用量子计算机能够在秒级时间内分解大整数。关于未来,让我们一起期待吧! 代码实现 Talk is cheap.Show me the code. 1//返回a的p次方对n取模的值 2function superPow(a, p, n) { 3 let b = String(p).split('').map(item => Number(item)); 4 5 function powMod(x, y) { 6 let res = 1; 7 for(let i = 0; i < y; i++) { 8 res = res * x % n; 9 } 10 return res; 11 } 12 13 let res = 1; 14 a %= n; 15 for(let i = b.length - 1; i >= 0; i--) { 16 res = powMod(a, b[i]) * res % n; 17 a = powMod(a, 10); 18 } 19 return res; 20} 21 22//以p=5,q=11,n=55,r=40,e=3,d=27为例 23const e = 3, 24 d = 27, 25 n = 55; 26 27//返回加密后的数组 28function encrypt(arr) { 29 return arr.map(item => superPow(item, e, n)); 30} 31 32//对加密的数组进行解密,返回解密后的数组 33function decrypt(arr) { 34 return arr.map(item => superPow(item, d, n)); 35} 36 37console.log(encrypt([3, 4, 5, 6, 7])); //[27, 9, 15, 51, 13] 38console.log(decrypt([27, 9, 15, 51, 13])); //[3, 4, 5, 6, 7]
温馨提示:可左右滑动 复制代码请前往https://blog.csdn.net/Great_Eagle/article/details/85255334
|