RSA算法是一种非对称密码算法。不对称实际上意味着它在两个不同的键上工作,即。 公钥 和 私钥。 正如它的名字所描述的,公钥是给每个人的,私钥是私有的。
非对称加密的一个例子:
- 客户端(例如浏览器)将其公钥发送到服务器并请求一些数据。
- 服务器使用客户端的公钥加密数据,并发送加密数据。
- 客户端接收该数据并对其进行解密。
由于这是不对称的,所以即使第三方拥有浏览器的公钥,除了浏览器之外没有其他人可以解密数据。
这个主意! RSA的思想基于这样一个事实:很难对大整数进行因式分解。公钥由两个数字组成,其中一个数字是两个大素数的乘积。私钥也是由相同的两个素数派生的。因此,如果有人能分解这个大数字,私钥就会被泄露。因此,加密强度完全取决于密钥大小,如果我们将密钥大小增加一倍或三倍,加密强度将以指数方式增加。RSA密钥的长度通常为1024或2048位,但专家认为1024位密钥可能在不久的将来被破解。但到目前为止,这似乎是一项不可行的任务。
让我们了解RSA算法背后的机制:
- >>生成公钥:
- 一个整数。
- 不是n的一个因素。
- 1
Φ(n) [Φ(n)如下所述],现在让我们考虑它等于3。
>>生成私钥:
现在我们已经准备好了–公钥(n=3127和e=3)和私钥(d=2011)
现在我们将加密 “嗨” :
现在我们将解密 1394 :
下面是针对小值的RSA算法的C实现:
// C program for RSA asymmetric cryptographic // algorithm. For demonstration values are // relatively small compared to practical // application #include<stdio.h> #include<math.h> // Returns gcd of a and b int gcd( int a, int h) { int temp; while (1) { temp = a%h; if (temp == 0) return h; a = h; h = temp; } } // Code to demonstrate RSA algorithm int main() { // Two random prime numbers double p = 3; double q = 7; // First part of public key: double n = p*q; // Finding other part of public key. // e stands for encrypt double e = 2; double phi = (p-1)*(q-1); while (e < phi) { // e must be co-prime to phi and // smaller than phi. if (gcd(e, phi)==1) break ; else e++; } // Private key (d stands for decrypt) // choosing d such that it satisfies // d*e = 1 + k * totient int k = 2; // A constant value double d = (1 + (k*phi))/e; // Message to be encrypted double msg = 20; printf ( "Message data = %lf" , msg); // Encryption c = (msg ^ e) % n double c = pow (msg, e); c = fmod (c, n); printf ( "Encrypted data = %lf" , c); // Decryption m = (c ^ d) % n double m = pow (c, d); m = fmod (m, n); printf ( "Original Message Sent = %lf" , m); return 0; } // This code is contributed by Akash Sharan. |
输出:
Message data = 12.000000 Encrypted data = 3.000000 Original Message Sent = 12.000000
本文由 莫希特·古普塔(Mohit Gupta_OMG) .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。