RSA加密及签名


RSA加密及签名

RSA加密及签名

CSDN

51CTO博客

'''
使用函数库Crypto或cryptography完成RSA算法相关操作
包括密钥的生成、导入导出;
加密和解密;
签名和验证;
'''
from Crypto.Util.number import *
from Crypto.PublicKey import RSA

from Crypto.Signature import PKCS1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Sig_pk

from Crypto.Hash import SHA
import base64 


# 生成密钥,对message进行加密和签名
# plaintext数据类型为字节串,如
# plaintext = 'pycryptdemo is easy to learn. 你觉得呢?'.encode()
# 返回值为密钥,密文,签名
# 密钥使用'pem'格式,密钥、密文、签名直接使用调用函数的输出
def enc_sign(plaintext):
    # begin
    # 生成密钥(2048bit)
    m = bytes_to_long(plaintext)
    key = RSA.generate(2048)

    f = open('private.pem', 'wb')
    f.write(key.export_key('PEM'))
    f.close()

    f = open('public.pem', 'wb')
    f.write(key.publickey().exportKey('PEM'))
    f.close()

    # 加密
    f = open('public.pem', 'r')
    key = RSA.import_key(f.read())
    n = key.n
    e = key.e
    c = pow(m, e, n)
    ciphertext = long_to_bytes(c)

    # 签名
    f = open('private.pem', 'r')
    private_key = RSA.import_key(f.read())
    key = private_key
    # 根据sha算法处理签名内容
    hash_value = SHA.new(plaintext)
    # 私钥进行签名
    signer = PKCS1_v1_5.new(private_key)
    signature = signer.sign(hash_value)
    # base64 加密随便
    signature = base64.b64encode(signature).decode()

    return key.export_key('PEM'), ciphertext, signature
    ''''''
    # signature = PKCS1_v1_5.new(key)
    # hash_val = SHA.new(plaintext)
    # re = signature.sign(hash_val)
    # result = base64.b64encode(re)
    # red = result.decode()
    ''''''


# 进行解密和签名验证
# 输入为enc_sign的输出
# 输出为明文和验证结果
# 明文数据类型为字符串,验证结果为布尔值

def dec_ver(key, ciphertext, signature):
    # begin
    # 导入密钥
    key = RSA.import_key(key)
    # 解密
    n = key.n
    d = key.d
    c = bytes_to_long(ciphertext)
    m = pow(c, d, n)
    pt = long_to_bytes(m)
    # 验证签名
    # 先解码
    signature = base64.b64decode(signature.encode())
    f = open('public.pem', 'r')
    public_key = RSA.import_key(f.read())
    # 验证签名
    # 将签名之前的内容进行hash处理
    hash_value = SHA.new(pt)
    verifier = Sig_pk.new(public_key)
    result = verifier.verify(hash_value, signature)
    # end
    return pt, result

# 测试程序类似下面代码,会检测解密是否正确,签名验证是否正确
if __name__ == '__main__':
    plaintext = 'pycryptdemo is easy to learn. 你觉得呢?'.encode()
    key, ciphertext, signature = enc_sign(plaintext)
    print('==================================================')
    pt, result = dec_ver(key, ciphertext, signature)
    print('==================================================')
    if (pt == plaintext) and result:
        print('success')

文章作者: hengxinyan
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 hengxinyan !
  目录