使用Python实现RSA算法

2023-03-27 00:00:00 python rsa 算法

RSA算法是一种公钥加密算法,具有很高的安全性和广泛的应用。下面是一个使用Python实现RSA算法的例子:

生成公钥和私钥

import random

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)

def gen_keypair(p, q):
    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 = mod_inverse(e, phi)
    return ((e, n), (d, n))

def mod_inverse(a, m):
    for x in range(1, m):
        if (a * x) % m == 1:
            return x
    return None

p = 61
q = 53
public_key, private_key = gen_keypair(p, q)
print("公钥:", public_key)
print("私钥:", private_key)

加密和解密

def encrypt(pk, plaintext):
    key, n = pk
    cipher = [(ord(char) ** key) % n for char in plaintext]
    return cipher

def decrypt(pk, ciphertext):
    key, n = pk
    plain = [chr((char ** key) % n) for char in ciphertext]
    return ''.join(plain)

message = "pidancode.com"
encrypted_message = encrypt(public_key, message)
print("加密后的密文:", encrypted_message)
decrypted_message = decrypt(private_key, encrypted_message)
print("解密后的明文:", decrypted_message)

这里使用字符串 "pidancode.com" 进行加密和解密。

相关文章