RSA加密算法

信息安全

Posted by MetaNetworks on May 23, 2020
本页面总访问量

代码如下:

  • 使用Python自带RSA库
  • 使用Python自带time库进行计时
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
'''
@Author: MetaNetworks
@Date: 2020-05-23 14:04:58
@LastEditors: MetaNetworks
@LastEditTime: 2020-05-23 15:15:00
@Description: MetaNetworks' Code
'''
#rsa 公钥与私钥示例 
import rsa
import base64
import time

#生成公钥与私钥
t1 = time.time()
(public_key, private_key) = rsa.newkeys(3072)  # RSA加密
print("生成KEY耗费",time.time()-t1)


def rsaEncryption(public_key, cleartext):
	try:
		t1 = time.time()
		result = rsa.encrypt(cleartext.encode(), public_key)
		return base64.encodebytes(result)
	finally:
		t2 = time.time()
		print("加密耗时",t2-t1)
	
# RSA解密
def rsaDecryption(public_key, ciphertext):
	try:
		t1 = time.time()
		result = rsa.decrypt(base64.decodebytes(ciphertext), private_key)
		return result.decode()  #输出公钥、私钥
	finally:
		t2 = time.time()
		print("解密耗时",t2-t1)

print(public_key.save_pkcs1())
print(private_key.save_pkcs1())
cleartext : str
with open("origin_text.txt",'r') as txt:
	cleartext = txt.read()
ciphertext = rsaEncryption(public_key, cleartext) 
print("密文:")
print(ciphertext)
with open("encrypted_text.txt",'w') as txt:
	txt.write(ciphertext.decode("utf-8"))
decipher = rsaDecryption(private_key, ciphertext) 
print("明文:")
print(decipher)

with open("decrypted_text.txt",'w') as txt:
	txt.write(str(decipher))

运行结果

执行结果

耗时测试

项/时间(s)/KEY长度 1024 2048 3072
生成RSA公钥、密钥 0.4035 3.9988 54.8021
加密 0.0002 0.0004 0.0007
解密 0.0097 0.0603 0.1646