python - 如何在python中加密和解密消息RSA?
问题描述
我正在尝试在没有 Crypto 库的情况下在 python 中编写 RSA 加密和解密,简而言之,我已经生成了公钥(e,N)和私钥(d,N)来与消息交换,但我不知道该怎么做。消息我要发送也是关键:b'gAAAAABenIFsZD5Oa7GPNKPV7yBHSKasuzpMzYPPoXbEqX3cbxO_9-3eP9UdKOXsrQmLSesKkaeKk9VZXI6Qx-iWS8tglsxbRwjgdAWPZKQa8NLyH1ICKJgEihrc-9ybO6WgV_jASgHH0zg4mdEP8XhxQmg6-S96HA=='
有人知道如何用我的公钥加密消息并用私钥解密吗?
import random
def gcd(a, b): # gdc to find proper e
if (b == 0):
return a
else:
return gcd(b, a % b)
def isPrime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False;
break
else:
return True
else:
return False;
def pGenerator():
p = 0
while p == 0:
pn = random.randint(0, 40)
if (isPrime(pn)):
p = pn
break
return p
def qGenerator(p):
q = 0
while q == 0:
pn = random.randint(0, 40)
if (isPrime(pn) and pn != p and pn <p):
q = pn
break
return q
def eGenerator( fiN):
e = 0
while e == 0:
pn = random.randint(0, fiN)
if (gcd(pn, fiN) == 1):
e = pn
break
return e
def start():
p = pGenerator()
print(p)
q = qGenerator(p)
print(q)
N = p * q
fiN = (p - 1) * (q - 1)
print(fiN)
e = eGenerator(fiN)
d=multiplicative_inverse(e,fiN)
c=encrypt(e, N, "d")
decrypt(d,N,c)
print(c)
def encrypt(e,n, plaintext):
#Unpack the key into it's components
key=e
#Convert each letter in the plaintext to numbers based on the character using a^b mod m
cipher = [(ord(char) ** key) % n for char in plaintext]
#Return the array of bytes
return cipher
def multiplicative_inverse(e, phi):
d = 0
x1 = 0
x2 = 1
y1 = 1
temp_phi = phi
while e > 0:
temp1 = temp_phi / e
temp2 = temp_phi - temp1 * e
temp_phi = e
e = temp2
x = x2 - temp1 * x1
y = d - temp1 * y1
x2 = x1
x1 = x
d = y1
y1 = y
if temp_phi == 1:
return d + phi
start()
解决方案
你试过rsapy吗?只需在其 PyPI 页面上阅读其文档即可。
例子:
import rsapy
pub, pri = rsapy.genkey(2**512)
print(rsapy.encode("message", pub))
# This also works with b"message"
推荐阅读
- python - Discord.py sudo all 命令没有响应
- web - 如何通过托管网站/本地主机上的一键连接 colab 文件?
- python - 如何从文件中获取特定的字符串?
- mysql - 计算应付给每个用户的金额
- file - 如何从 SMB 和 HTTP 文件的导出中检查 Wireshark 上的合法文档
- flutter - AnimatedCrossFade 状态不变
- ml - 从 ML 中的给定列表中删除中间元素
- python - Requests-html 导致 OSError: [Errno 8] 调用 html.render() 时执行格式错误
- php - 在同一页面上使用 PHP 检查用户 html 表单信息
- node.js - PassportJS 调用成功函数但不重定向