import gmpy2
from gmpy2 import mpz
def generate_keypair(bits):
# 生成RSA密钥对
p = gmpy2.next_prime(gmpy2.mpz(2)**(bits//2))
q = gmpy2.next_prime(gmpy2.mpz(2)**(bits//2 + bits%2))
n = p*q
phi_n = (p-1) * (q-1)
e = 65537
d = gmpy2.invert(e, phi_n)
return (mpz(n), mpz(e)), (mpz(n), mpz(d))
def encrypt(plaintext, publickey):
# RSA加密
n, e = publickey
M = mpz(plaintext.encode('utf-8').hex(), 16)
C = gmpy2.powmod(M, e, n)
return hex(C)[2:]
def decrypt(ciphertext, privatekey):
# RSA解密
n, d = privatekey
C = mpz(ciphertext, 16)
M = gmpy2.powmod(C, d, n)
plaintexthex = hex(M)[2:]
if len(plaintexthex) % 2 == 1:
plaintexthex = '0' + plaintexthex
plaintext = bytes.fromhex(plaintexthex).decode('utf-8', 'ignore')
return plaintext
plaintext = 'hainan university!'
publickey, privatekey = generate_keypair(1024)
ciphertext = encrypt(plaintext, publickey)
decryptedplaintext = decrypt(ciphertext, privatekey)
print('明文:', plaintext)
print('密文:', ciphertext)
print('解密后的明文:', decryptedplaintext)
RSA加密代码python语言和运行操作
于 2023-06-23 19:15:46 首次发布