RSA加密代码python语言和运行操作

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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值