簡體   English   中英

如何在Python中計算RSA私鑰

[英]How to calculate RSA private key in Python

我正在創建一個加密和解密數據的程序。 我需要計算密鑰,但我無法弄清楚如何將代數更改為可以在python中使用的表達式。

我嘗試使用代數但我無法弄明白。 我正在使用python 3.6.1

def genkey():
    p = 3 #prime 1
    q = 11 #prime 2
    n = p * q# pubkey part 1
    z = (p-1)*(q-1)# 20
    k = 7 #coprime to z and pub key part 2
    #j = ?
    return (n,k,j)

j應該等於3,公式是

我使用預先計算的數字進行測試

鏈接到網站

對於RSA:

我將從我自己的學士論文中提供一些算法和代碼

  • p和q,兩個素數
  • n = p * q, n是公鑰的一部分
  • epublic exponent應該與n Euler函數互為,對於素數是(p-1)(q-1)

查找公共指數的代碼:

def find_public_key_exponent(euler_function):
    """
    find_public_key_exponent(euler_function)

    Finds public key exponent needed for encrypting.
    Needs specific number in order to work properly.

    :param euler_function: the result of euler function for two primes.
    :return:               public key exponent, the element of public key.
    """

    e = 3

    while e <= 65537:
        a = euler_function
        b = e

        while b:
            a, b = b, a % b

        if a == 1:
            return e
        else:
            e += 2

    raise Exception("Cant find e!")
  • 接下來我們需要歐拉函數(n)和e的模乘法逆,它等於d ,我們的最后一個組成部分:
def extended_euclidean_algorithm(a, b):
    """
    extended_euclidean_algorithm(a, b)

    The result is the largest common divisor for a and b.

    :param a: integer number
    :param b: integer number
    :return:  the largest common divisor for a and b
    """

    if a == 0:
        return b, 0, 1
    else:
        g, y, x = extended_euclidean_algorithm(b % a, a)
        return g, x - (b // a) * y, y


def modular_inverse(e, t):
    """
    modular_inverse(e, t)

    Counts modular multiplicative inverse for e and t.

    :param e: in this case e is a public key exponent
    :param t: and t is an Euler function
    :return:  the result of modular multiplicative inverse for e and t
    """

    g, x, y = extended_euclidean_algorithm(e, t)

    if g != 1:
        raise Exception('Modular inverse does not exist')
    else:
        return x % t

公鑰: (n, e) 私鑰: (n, d)

加密: <number> * e mod n = <cryptogram>

解密: <cryptogram> * d mon n = <number>

還有一些限制因此密碼應該是安全的,但它將適用於我提供的條件。

當然,你需要找到獲得大質數的方法,閱讀主要測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM