如何在Python中使用RSA私钥加密数据?

2024-10-01 09:17:42 发布

您现在位置:Python中文网/ 问答频道 /正文

注意:我正在利用Python2.7上的VisualStudio执行加密操作

Q1:我要做的操作是让程序根据从公钥接收的密文来检查和破译私钥公式

Q2:在文档中,它描述了需要一种算法来计算明文代码。然而,文件中没有具体说明如何根据模量计算该方程。我试图找出如何为我的rsa函数编写privateKeyCheck,因此一旦它运行publickey,它就会验证密文

RSA_Functions.py

class RSA:
def isPrime(n):

    # Corner case
    if (n <= 1):
        return False

    # Check from 2 to n-1
    for i in range(2, n):
        if (n % i == 0):
            return False

    return True

def modulus(p, q):
    return p * q

def eulerTotient(p, q):
    return (p - 1) * (q - 1)

def findFactors(x):
    factorList = []
    for i in range(1, x + 1):
        if x % i == 0:
            factorList.append(i)
    return factorList

def publicKeyCheck(plist, qlist, keylist):
    for i in keylist:
        if i in plist and i != 1:
            print('invalid public key')

        elif i in qlist and i != 1:
            print('invalid public key')
        else:
            print(' public key is valid')
            break

如上所述,对于方程,我们创建了两个质数(pq),用于比较eulerotient和公钥的因子,以确保它们与eulerotient没有共同因子,并创建了一个PublicKeyCheck以查看它是否与RSA匹配

from RSAFunctions import RSA

print('Welcome to the RSA Algorithm Simulator.')
print('First you will need to select two Prime numbers.')

#step one generate two prime numbers
p = int(input('\nEnter a prime number(p) : '))
q = int(input('Enter a prime number(q) : '))

print("\nChecking to see if inputs are valid: ")
print(RSA.isPrime(p))
print(RSA.isPrime(q))

print("\nNow printing the Modulus:")
print(RSA.modulus(p, q))

print("\nNow printing the eulerTotient:")
print(RSA.eulerTotient(p, q))

publicKey = int(
    input(
        "\nPlease Enter a small two digit number that has no 
common factors with the eulertotient: "
    ))

factorseuler = RSA.findFactors(RSA.eulerTotient(p, q))
factorsKey = RSA.findFactors(publicKey)

print('\nVeryifying public Key:')

RSA.publicKeyCheck(factorsKey)

Tags: thetokeyinforreturnifdef