以下是RSA加密的Python实现:

import random
import math

def is_prime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i+2) == 0:
            return False
        i += 6
    return True

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

def multiplicative_inverse(e, phi):
    def gcd_extended(a, b):
        if a == 0:
            return (b, 0, 1)
        else:
            gcd, x, y = gcd_extended(b % a, a)
            return (gcd, y - (b // a) * x, x)
    gcd, x, y = gcd_extended(e, phi)
    if gcd != 1:
        return None
    else:
        return x % phi

def generate_keypair(p, q):
    if not (is_prime(p) and is_prime(q)):
        raise ValueError('Both numbers must be prime.')
    elif p == q:
        raise ValueError('p and q cannot be equal.')
    n = p * q
    phi = (p-1) * (q-1)
    e = random.randrange(1, phi)
    g = gcd(e, phi)
    while g != 1:
        e = random.randrange(1, phi)
        g = gcd(e, phi)
    d = multiplicative_inverse(e, phi)
    return (n, e, d)

def encrypt(plaintext, n, e):
    cipher = [pow(ord(char), e, n) for char in plaintext]
    return cipher

def decrypt(ciphertext, n, d):
    plain = [chr(pow(char, d, n)) for char in ciphertext]
    return ''.join(plain)

if __name__ == '__main__':
    p = int(input('Enter a prime number (p): '))
    q = int(input('Enter another prime number (q): '))
    e = int(input('Enter a number (e) for encryption: '))

    n, _, d = generate_keypair(p, q)

    print('Public key (n, e): ({}, {})'.format(n, e))
    print('Private key (n, d): ({}, {})'.format(n, d))

    plaintext = input('Enter a message to encrypt: ')
    ciphertext = encrypt(plaintext, n, e)
    print('Encrypted message: ', ''.join(map(str,ciphertext)))

    decrypted = decrypt(ciphertext, n, d)
    print('Decrypted message: ', decrypted)

在这个实现中,我们首先定义了一些辅助函数,如判断素数、求最大公约数、求模反元素等。然后,我们实现了生成密钥对、加密和解密函数。

在主程序中,我们首先让用户输入两个素数 p 和 q,以及一个用于加密的公钥 e。然后,我们使用 generate_keypair 函数生成 RSA 密钥对,并输出公钥和私钥。接着,我们让用户输入要加密的文本,使用 encrypt 函数加密,再使用 decrypt 函数解密,最终输出解密后的明文。

需要注意的是,这个实现中加密和解密的时候,我们使用了一些 Python 的内置函数,比如 pow、ord 和 chr。其中,pow(x, y, z) 表示计算 x 的 y 次方对 z 取模的结果。ord(char) 表示获取字符 char 的 ASCII 码值。chr(n) 表示获取 ASCII 码值为 n 的字符。

RSA加密算法的Python实现:导入RSA密钥进行文本加密

原文地址: https://www.cveoy.top/t/topic/osKl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录