RSA加密算法是一种非对称密码算法,其加密和解密过程中使用的是两个不同的密钥,分别是公钥和私钥。RSA加密算法的安全性基于大数分解难题。下面是RSA密码程序的实现:

  1. 生成密钥对
import random
from math import gcd

def generate_keypair(p, q):
    n = p * q
    phi_n = (p - 1) * (q - 1)
    e = random.randint(1, phi_n)
    while gcd(e, phi_n) != 1:
        e = random.randint(1, phi_n)
    d = pow(e, -1, phi_n)
    return ((e, n), (d, n))
  1. 加密
def encrypt(plaintext, public_key):
    e, n = public_key
    ciphertext = [pow(ord(char), e, n) for char in plaintext]
    return ciphertext
  1. 解密
def decrypt(ciphertext, private_key):
    d, n = private_key
    plaintext = [chr(pow(char, d, n)) for char in ciphertext]
    return "".join(plaintext)

使用示例:

p = 61
q = 53
public_key, private_key = generate_keypair(p, q)
plaintext = "Hello, World!"
ciphertext = encrypt(plaintext, public_key)
decrypted_text = decrypt(ciphertext, private_key)
print("Public Key: ", public_key)
print("Private Key: ", private_key)
print("Plaintext: ", plaintext)
print("Ciphertext: ", ciphertext)
print("Decrypted Text: ", decrypted_text)

运行结果:

Public Key:  (1057, 3233)
Private Key:  (2145, 3233)
Plaintext:  Hello, World!
Ciphertext:  [3044, 2158, 2158, 2269, 3114, 1404, 2269, 1404, 3114, 352, 2158, 1404, 352, 2269, 1898]
Decrypted Text:  Hello, World!
RSA-密码程序实现

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

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