一整套RSA文件加密算法源代码
时间: 2023-08-21 07:20:13 浏览: 134
RSA加密算法源码
3星 · 编辑精心推荐
以下是Python实现的一整套RSA文件加密算法源代码:
```python
import os
import random
import math
def is_prime(n):
"""判断一个数是否为素数"""
if n < 2:
return False
for i in range(2, int(math.sqrt(n))+1):
if n % i == 0:
return False
return True
def gcd(a, b):
"""计算a和b的最大公约数"""
while b != 0:
a, b = b, a % b
return a
def extended_gcd(a, b):
"""计算a和b的最大公约数以及贝祖等式中的x和y"""
if b == 0:
return (a, 1, 0)
else:
d, x, y = extended_gcd(b, a % b)
return (d, y, x - (a // b) * y)
def generate_keypair(p, q):
"""生成公钥和私钥"""
n = p * q
phi = (p - 1) * (q - 1)
e = random.randint(1, phi-1)
while gcd(e, phi) != 1:
e = random.randint(1, phi-1)
d = extended_gcd(e, phi)[1]
if d < 0:
d += phi
return ((e, n), (d, n))
def encrypt_file(filename, public_key):
"""使用公钥加密文件"""
e, n = public_key
with open(filename, 'rb') as f:
plaintext = f.read()
ciphertext = [pow(byte, e, n) for byte in plaintext]
with open(filename + '.enc', 'wb') as f:
for byte in ciphertext:
f.write(byte.to_bytes((byte.bit_length()+7)//8, 'big'))
def decrypt_file(filename, private_key):
"""使用私钥解密文件"""
d, n = private_key
with open(filename, 'rb') as f:
ciphertext = []
while True:
byte = f.read(1)
if not byte:
break
ciphertext.append(int.from_bytes(byte, 'big'))
plaintext = [pow(byte, d, n) for byte in ciphertext]
with open(os.path.splitext(filename)[0], 'wb') as f:
for byte in plaintext:
f.write(byte.to_bytes((byte.bit_length()+7)//8, 'big'))
if __name__ == '__main__':
p = 61
q = 53
if not (is_prime(p) and is_prime(q)):
raise ValueError('p和q必须是素数!')
public_key, private_key = generate_keypair(p, q)
filename = 'test.txt'
with open(filename, 'w') as f:
f.write('Hello, World!')
encrypt_file(filename, public_key)
decrypt_file(filename + '.enc', private_key)
with open(filename, 'r') as f:
original_text = f.read()
with open(os.path.splitext(filename)[0], 'r') as f:
decrypted_text = f.read()
print('公钥:', public_key)
print('私钥:', private_key)
print('原始文本:', original_text)
print('解密后的文本:', decrypted_text)
```
在这个示例中,我们使用61和53两个素数生成RSA加密算法的公钥和私钥,并使用公钥加密一个文本文件,然后使用私钥解密该文件。注意,为了简化示例,我们使用了ASCII码来表示字符,但在实际应用中,我们应该使用更安全的加密方式来保护敏感信息。
阅读全文