如何在python中加密和解密消息RSA?
Posted
技术标签:
【中文标题】如何在python中加密和解密消息RSA?【英文标题】:How to encrypt and decrypt message RSA in python? 【发布时间】:2020-08-05 20:01:57 【问题描述】:我正在尝试在没有 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()
【问题讨论】:
您不会“交换”您的私钥,这违背了 RSA 的全部目的,尤其是一般的加密。 ...有人知道怎么做吗?... 您是在问是否有人知道如何发送加密消息?与发送未加密消息的方式相同。如果您需要更具体的帮助,请编辑您的问题以更具体。 @PresidentJamesMoveonPolk 谢谢你,更改和“交换”部分将在稍后进行,因为我现在的问题是加密消息和解密。 【参考方案1】:你试过rsapy吗? 只需在其 PyPI 页面上阅读其文档即可。
例子:
import rsapy
pub, pri = rsapy.genkey(2**512)
print(rsapy.encode("message", pub))
# This also works with b"message"
【讨论】:
以上是关于如何在python中加密和解密消息RSA?的主要内容,如果未能解决你的问题,请参考以下文章
使用 RSA 在 JS 中加密消息并在 Python 中解密