首页 > 解决方案 > 如何在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()

标签: pythonrsa

解决方案


你试过rsapy吗?只需在其 PyPI 页面上阅读其文档即可。

例子:

import rsapy
pub, pri = rsapy.genkey(2**512)
print(rsapy.encode("message", pub))
# This also works with b"message"

推荐阅读