RSA加密

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import base64


def create_key():
    # 伪随机数生成器
    random_generator = Random.new().read
    # rsa算法生成实例
    """
    加密时支持的最大字节数与证书有一定关系。
    加密时支持的最大字节数:证书位数/8 -11(比如:2048位的证书,支持的最大加密字节数:2048/8 - 11 = 245)
    1024位的证书,加密时最大支持117个字节,解密时为128;
  2048位的证书,加密时最大支持245个字节,解密时为256。
    """
    rsa = RSA.generate(1024, random_generator)
    # rsa = RSA.generate(2048, random_generator)
    # 私钥的生成
    private_pem = rsa.exportKey()
    with open("private.pem", "wb") as f:
        f.write(private_pem)
    # 公钥的生成
    public_pem = rsa.publickey().exportKey()
    with open("public.pem", "wb") as f:
        f.write(public_pem)


def add_to_245(text):
    if len(text.encode('utf-8')) % 245:
        add = 245 - (len(text.encode('utf-8')) % 245)
    else:
        add = 0
    text = text + ('\0' * add)
    return text.encode('utf-8')


def encrypt(text):
    # 加密
    with open('public.pem', 'r', encoding='utf-8') as r:
        key = r.read()
    print('加密key长度:{}'.format(len(key)))
    rsakey = RSA.importKey(key)
    cipher = Cipher_pkcs1_v1_5.new(rsakey)  # 创建用于执行pkcs1_v1_5加密或解密的密码
    cipher_text = base64.b64encode(cipher.encrypt(text.encode('utf-8')))
    t = cipher_text.decode('utf-8')
    return t

# 解密后,去掉补足的空格用strip() 去掉
def decrypt(text):
    text = text.encode('utf-8')
    with open('private.pem', 'r', encoding='utf-8') as r:
        key = r.read()
    print('解密key长度:{}'.format(len(key)))
    rsakey = RSA.importKey(key)
    cipher = Cipher_pkcs1_v1_5.new(rsakey)  # 创建用于执行pkcs1_v1_5加密或解密的密码
    text = cipher.decrypt(base64.b64decode(text), "解密失败")
    print(text.decode('utf-8'))


if __name__ == '__main__':
    create_key()
    s = '1qaz@WSX'
    e = encrypt(s)  # 加密
    print(e)
    print(len(e))
    decrypt(e)

 

上一篇:ppk和pem文件互转


下一篇:node服务器支持https请求