大整数模rsa运算加解密代码
时间: 2023-08-28 12:04:37 浏览: 120
以下是基于Python的RSA加解密代码,包括大整数模运算:
```python
import math
import random
# 生成指定位数的质数
def generate_prime(n):
while True:
p = random.randint(2**(n-1), 2**n-1)
if is_prime(p):
return p
# 判断一个数是否为质数
def is_prime(n):
if n == 2 or n == 3:
return True
if n < 2 or n % 2 == 0:
return False
if n < 9:
return True
if n % 3 == 0:
return False
r = int(math.sqrt(n))
f = 5
while f <= r:
if n % f == 0:
return False
if n % (f+2) == 0:
return False
f += 6
return True
# 扩展欧几里得算法
def extended_gcd(a, b):
if b == 0:
return a, 1, 0
gcd, x1, y1 = extended_gcd(b, a % b)
x = y1
y = x1 - (a // b) * y1
return gcd, x, y
# 生成公钥和私钥
def generate_key_pair(n):
p = generate_prime(n)
q = generate_prime(n)
while p == q:
q = generate_prime(n)
n = p * q
phi = (p-1) * (q-1)
e = random.randint(2, phi-1)
gcd, d, _ = extended_gcd(e, phi)
while gcd != 1:
e = random.randint(2, phi-1)
gcd, d, _ = extended_gcd(e, phi)
if d < 0:
d += phi
return (e, n), (d, n)
# 加密
def encrypt(plaintext, public_key):
e, n = public_key
ciphertext = []
for c in plaintext:
m = ord(c)
c = pow(m, e, n)
ciphertext.append(c)
return ciphertext
# 解密
def decrypt(ciphertext, private_key):
d, n = private_key
plaintext = ""
for c in ciphertext:
m = pow(c, d, n)
plaintext += chr(m)
return plaintext
# 测试
if __name__ == "__main__":
# 生成公钥和私钥
public_key, private_key = generate_key_pair(1024)
print("公钥:", public_key)
print("私钥:", private_key)
# 加密
plaintext = "Hello, RSA!"
print("明文:", plaintext)
ciphertext = encrypt(plaintext, public_key)
print("密文:", ciphertext)
# 解密
decrypted_plaintext = decrypt(ciphertext, private_key)
print("解密后的明文:", decrypted_plaintext)
```
在这个代码中,我们使用了Python内置的`pow()`函数来进行大整数模运算,它的第三个参数是模数。在RSA加解密中,模数为两个质数的积,因此我们在生成公钥和私钥时需要先生成两个质数。在加密时,我们将每个字符的ASCII码转换成整数,然后进行加密运算;在解密时,我们将密文还原成整数,然后进行解密运算并将结果转换成字符。
阅读全文