python实现RSA算法

import gmpy2
from gmpy2 import mpz
import binascii

rs = gmpy2.random_state()

#生成大素数(0-2^1024位)
def create_prime():
    p = gmpy2.mpz_urandomb(rs,1024)         #随机生成一个0~2^1024位的数
    while not gmpy2.is_prime(p):            #判断生成的数是否是素数
        p = gmpy2.mpz_urandomb(rs,1024)     
    return p

#生成密钥e,d
def get_e_d(phi):
    e = gmpy2.mpz_random(rs,phi)            
    while gmpy2.gcd(e,phi) != 1:
        e = gmpy2.mpz_random(rs,phi)        #随机生成一个0~phi的,与phi互素的数
    d = gmpy2.invert(e,phi)                 #生成d
    return e,d

#rsa加密
def encrypt(plain_text,e,n):
    m = mpz(binascii.hexlify(plain_text.encode('utf-8')), 16)
    cipher_text = gmpy2.powmod(m,e,n)
    return cipher_text

#rsa解密
def decrypt(cipher_text,d,n):
    m = gmpy2.powmod(cipher_text,d,n)
    plain_text = binascii.unhexlify(format(m, 'x')).decode('utf-8')
    return plain_text

if __name__ == '__main__':
    p = create_prime()
    q = create_prime()
    n = p * q
    phi = (p-1)*(q-1)
    e,d = get_e_d(phi)
    plain_text = input("请输入明文:")
    cipher_text = encrypt(plain_text,e,n)
    print("RSA加密后的密文是:%x"%cipher_text)
    plain_text1 = decrypt(cipher_text,d,n)
    print("RSA解密后的明文是:{}".format(plain_text1))

猜你喜欢

转载自blog.csdn.net/weixin_43790779/article/details/105999977