[RSA algorithm] Python generates public and private keys

RSA algorithm overview

RSA encryption algorithm is an asymmetric encryption algorithm proposed by three mathematicians Rivest, Shamir and Adleman in 1977. Its security is based on the prime factorization problem, which is to decompose a large composite number into the product of two prime numbers. The RSA algorithm is widely used in fields such as digital signatures, key agreement, and data encryption.

Encryption and decryption of RSA algorithm
Encryption process:
  1. Select two different large prime numbers p and q, and calculate their product n=p*q;
  2. Calculate the Euler function phi(n)=(p-1)*(q-1);
  3. Choose an encryption index e, 1<e<phi(n), and e and phi(n) are relatively prime;
  4. Calculate the decryption index d so that (d*e) mod phi(n)=1;
  5. Convert plaintext M into integer m, 0≤m<n;
  6. Encrypt m to obtain ciphertext c=ciphertext, c=m^e mod n.
Decryption process:

Using the decryption index d and modulus n, decrypt the ciphertext c to obtain the plaintext M, M=c^d mod n.

Requirements: Generate two prime numbers with more than 5 digits; and generate public and private keys from them.

In order to generate two prime numbers with more than 5 digits, you can use a random number generator and check whether each generated number is prime. For example, we can use the random and sympy libraries in Python to achieve this:

import random
from sympy import isprime

# 生成第一个5位以上的素数
p1 = random.randint(10000, 99999)
while not isprime(p1):
    p1 = random.randint(10000, 99999)

# 生成第二个5位以上的素数
p2 = random.randint(10000, 99999)
while not isprime(p2) or p2 == p1:
    p2 = random.randint(10000, 99999)

# 计算n和phi_n
n = p1 * p2
phi_n = (p1 - 1) * (p2 - 1)

# 找到满足条件的公钥e
e = 65537
while phi_n % e == 0 or not isprime(e):
    e += 2

# 计算私钥d
d = pow(e, -1, phi_n)

# 输出结果
print("第一个素数:", p1)
print("第二个素数:", p2)
print("公钥:({0}, {1})".format(n, e))
print("私钥:({0}, {1})".format(n, d))

The public key consists of the modulus n and the encryption exponent e, and the private key consists of the modulus n and the decryption exponent d. In this process, we used Euler's theorem to calculate the phi_n value, which is an important property of the RSA encryption algorithm.

Guess you like

Origin blog.csdn.net/weixin_52049271/article/details/130765860