利用rsa对文本加密的python实现
以下是一个简单的RSA加密和解密的Python实现:
import random
import math
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def mod_inverse(a, m):
if gcd(a, m) != 1:
return None
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
return u1 % m
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def generate_keypair(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError("Both numbers must be prime.")
elif p == q:
raise ValueError("p and q cannot be equal")
# n = pq
n = p * q
# phi(n) = (p-1)(q-1)
phi = (p - 1) * (q - 1)
# Choose an integer e such that e and phi(n) are coprime
e = random.randrange(1, phi)
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)
# Calculate d such that ed = 1 (mod phi(n))
d = mod_inverse(e, phi)
# Return public and private keypair
# Public key is (e, n)
# Private key is (d, n)
return ((e, n), (d, n))
def encrypt(public_key, plaintext):
# Unpack the key into its components
key, n = public_key
# Convert each letter in the plaintext to numbers based on the character using a^b mod m
cipher = [pow(ord(char), key, n) for char in plaintext]
# Return the array of bytes
return cipher
def decrypt(private_key, ciphertext):
# Unpack the key into its components
key, n = private_key
# Generate the plaintext based on the ciphertext and key using a^b mod m
plain = [chr(pow(char, key, n)) for char in ciphertext]
# Return the array of bytes as a string
return ''.join(plain)
# Example usage
p = 61
q = 53
public, private = generate_keypair(p, q)
print("Public key:", public)
print("Private key:", private)
message = "hello, world"
encrypted_msg = encrypt(public, message)
print("Encrypted message:", ''.join(map(str, encrypted_msg)))
decrypted_msg = decrypt(private, encrypted_msg)
print("Decrypted message:", decrypted_msg)
在此示例中,我们使用generate_keypair函数生成RSA公钥和私钥。然后,我们使用encrypt函数将文本加密为数字数组,使用decrypt函数将加密的数字数组解密为文本。在此示例中,我们使用61和53作为p和q的值,但您可以使用不同的值来生成不同的密钥
原文地址: https://www.cveoy.top/t/topic/f2o5 著作权归作者所有。请勿转载和采集!