热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

rsa加解密及加签验签

加密要用到Crypto安装包pipinstallCrypto新建两个模块rsautils.py,rsatest.py直接上代码,rsautils.py#!usrbinenv

加密要用到Crypto安装包 pip install Crypto

新建两个模块rsautils.py, rsatest.py直接上代码,
rsautils.py


#!/usr/bin/env python3
# coding=utf-8
# Author: Luosu201803
"""
create_rsa_key() - 创建RSA密钥
my_encrypt_and_decrypt() - 测试加密解密功能
rsa_sign() & rsa_signverify() - 测试签名与验签功能
"""

import base64
import json
from Crypto.Hash import SHA1
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
# 需要安装pycrypto rsa
from rsa_test import to_para, to_decrypt

pubkey = '''-----BEGIN RSA PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCaqlxNJpDUjMLGlzLglAub6SLZDP8HxfpHzqg
kecuVRpQ4OOlIOHSFGGHSRUyQ5F18vMzMcTWWzGaxV+bVHC8E0q9w1hUeUu954gn01wt6vK3N82o
D/N0R9ZbireOGZB/weaW8cw8jUHjc/j9N4o1pV+vcOYUsU2xt5vXRwFEGQIDAQAB
-----END RSA PUBLIC KEY-----'''

privatekey = '''-----BEGIN RSA PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIJqqXE0mkNSMwsaXMuCUC5vpItk
M/wfF+kfOqCR5y5VGlDg46Ug4dIUYYdJFTJDkXXy8zMxxNZbMZrFX5tUcLwTSr3DWFR5S73niCfT
XC3q8rc3zagP83RH1luKt44ZkH/B5pbxzDyNQeNz+P03ijWlX69w5hSxTbG3m9dHAUQZAgMBAAEC
gYBFUhKcpLw2enO9PBcE6VBbTmZk3S8wnQpllH7iKIt8OioRwWffNtoxgznP4g3NONMRocCZfqPE
2JZGUREfjEObP/jnPQFRd7r/XOwsWT80pbpBdo4csGnenbq5FVR1Ren0i1lyHeIdm+mZR3BuPoMN
QbAha+3ggYBaSvEgfLGRrQJBANWrKQ7YHQRTf1JKDEeIQYT6Xuc1WVPZ9oNQg+G1yYK3vSxHAqEj
7pj7OYXETb7fPBsOYb3Z3OyRAJBnQhwbV+sCQQCcQSGBALdwLL6aGKfMJiEc2VTCY4//K04L8dB1
NSlzWYZSLMkfP7X+KKgdcmWQRx6Dwm6hKIIOWjQBi+CikzcLAkEAtszhqp6AbMQWyMsrKEPNcjxV
109QJiny+jN3MTK6vQf/Y5M5D63TIrTEaMoijaslHCy4uJlcplQD/IcrCyrlkwJABXA640uMFupn
w+NBy9gz5NYnnhBrDZ2LPN0wvTOZertN8oQ+h8jm4660kznNESV4iWt2AEPxquA22SruKZpoGwJB
ALrT5IiJs5RJs3/uxjlDyg1A9NABkU9EM4xzvSxWHVSS0orF/sH/218OphjH/D8GTFMfmySqpJVs
ZHd+IzzVa54=
-----END RSA PRIVATE KEY-----'''


def create_rsa_key(password="123456"):
"""
创建RSA密钥,步骤说明:
1、从 Crypto.PublicKey 包中导入 RSA,创建一个密码(此密码不是RSA秘钥对)
2、生成 1024/2048 位的 RSA 密钥对(存储在私钥文件和公钥文件)
3、调用 RSA 密钥实例的 exportKey 方法(传入"密码"、"使用的 PKCS 标准"、"加密方案"这三个参数)得到私钥。
4、将私钥写入磁盘的文件。
5、使用方法链调用 publickey 和 exportKey 方法生成公钥,写入磁盘上的文件。
"""
key = RSA.generate(1024)
encrypted_key = key.exportKey(passphrase=password, pkcs=8, protection="scryptAndAES128-CBC")
# encrypted_key = key.exportKey(pkcs=1)
# print('encrypted_key:', encrypted_key)
with open("my_private_rsa_key.pem", "wb") as f:
f.write(encrypted_key)
with open("my_rsa_public.pem", "wb") as f:
f.write(key.publickey().exportKey())


def encrypt_and_decrypt_test(message, password="123456"):
# 加载公钥用于加密
key = pubkey
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(message))
print('%s 对应的密文是:' % message.decode("utf8"), cipher_text)
# 加载私钥用于解密
key = privatekey
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
text = cipher.decrypt((base64.b64decode(cipher_text)), password)
print('解密后原文是:', text.decode("utf8"))


def rsa_sign(message, password="123456"):
# 读取私钥信息用于加签
private_key = RSA.importKey(open("my_private_rsa_key.pem").read(), passphrase=password)
hash_obj = SHA1.new(message)
# print(pkcs1_15.new(private_key).can_sign()) #check wheather object of pkcs1_15 can be signed
# base64编码打印可视化
signature = base64.b64encode(pkcs1_15.new(private_key).sign(hash_obj))
return signature


def rsa_signverify(message, signature):
# 读取公钥信息用于验签
public_key = RSA.importKey(open("my_rsa_public.pem").read())
# message做“哈希”处理,RSA签名这么要求的
hash_obj = SHA1.new(message)
try:
# 因为签名被base64编码,所以这里先解码,再验签
pkcs1_15.new(public_key).verify(hash_obj, base64.b64decode(signature))
print('The signature is valid.')
return True
except (ValueError, TypeError):
print('The signature is invalid.')


if __name__ == '__main__':
message = "英文".encode("utf8")
create_rsa_key()
encrypt_and_decrypt_test(message)
dict_body = {'certificate_no': '2019042955452554', 'auth_code': '456789'}
encrypt_message = to_para(str(dict_body))
print("dict_body字典进行解密:%s" % to_decrypt(to_para(str(dict_body))))
biz_cOntent= {'partner': 'diannei', 'request_id': '201904232025123456', '': '', 'request_type': 'Q01'}
signature = rsa_sign(message)
biz_content['sign'] = str(signature)
print('signature:', signature)
body_map = {'encrypt_message': encrypt_message}
dict_map = {'head': json.dumps(biz_content), 'body': json.dumps(body_map)}
print(dict_map)
print(rsa_signverify(message, signature))


rsatest.py


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

# 需要安装pycrypto rsa
pubkey = '''-----BEGIN RSA PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCaqlxNJpDUjMLGlzLglAub6SLZDP8HxfpHzqg
kecuVRpQ4OOlIOHSFGGHSRUyQ5F18vMzMcTWWzGaxV+bVHC8E0q9w1hUeUu954gn01wt6vK3N82o
D/N0R9ZbireOGZB/weaW8cw8jUHjc/j9N4o1pV+vcOYUsU2xt5vXRwFEGQIDAQAB
-----END RSA PUBLIC KEY-----'''

privatekey = '''-----BEGIN RSA PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIJqqXE0mkNSMwsaXMuCUC5vpItk
M/wfF+kfOqCR5y5VGlDg46Ug4dIUYYdJFTJDkXXy8zMxxNZbMZrFX5tUcLwTSr3DWFR5S73niCfT
XC3q8rc3zagP83RH1luKt44ZkH/B5pbxzDyNQeNz+P03ijWlX69w5hSxTbG3m9dHAUQZAgMBAAEC
gYBFUhKcpLw2enO9PBcE6VBbTmZk3S8wnQpllH7iKIt8OioRwWffNtoxgznP4g3NONMRocCZfqPE
2JZGUREfjEObP/jnPQFRd7r/XOwsWT80pbpBdo4csGnenbq5FVR1Ren0i1lyHeIdm+mZR3BuPoMN
QbAha+3ggYBaSvEgfLGRrQJBANWrKQ7YHQRTf1JKDEeIQYT6Xuc1WVPZ9oNQg+G1yYK3vSxHAqEj
7pj7OYXETb7fPBsOYb3Z3OyRAJBnQhwbV+sCQQCcQSGBALdwLL6aGKfMJiEc2VTCY4//K04L8dB1
NSlzWYZSLMkfP7X+KKgdcmWQRx6Dwm6hKIIOWjQBi+CikzcLAkEAtszhqp6AbMQWyMsrKEPNcjxV
109QJiny+jN3MTK6vQf/Y5M5D63TIrTEaMoijaslHCy4uJlcplQD/IcrCyrlkwJABXA640uMFupn
w+NBy9gz5NYnnhBrDZ2LPN0wvTOZertN8oQ+h8jm4660kznNESV4iWt2AEPxquA22SruKZpoGwJB
ALrT5IiJs5RJs3/uxjlDyg1A9NABkU9EM4xzvSxWHVSS0orF/sH/218OphjH/D8GTFMfmySqpJVs
ZHd+IzzVa54=
-----END RSA PRIVATE KEY-----'''


# 加密
def to_para(plain):
rsa_key = RSA.importKey(pubkey)
x = rsa.encrypt(plain.encode(), rsa_key)
cipher_text = base64.b64encode(x).decode()
return cipher_text


# 解密
def to_decrypt(plain):
rsa_privkey = RSA.importKey(privatekey)
cipher = Cipher_pkcs1_v1_5.new(rsa_privkey)
x = cipher.decrypt(base64.b64decode(plain), "ERROR")
print(x.decode())
return x.decode()


def ByteToHex(bins):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
return ''.join(["%02X" % x for x in bins]).strip()


def HexToByte(hexStr):
"""
Convert a string hex byte values into a byte string. The Hex Byte values may
or may not be space separated.
"""
return bytes.fromhex(hexStr)


def hex_to_str(s):
return ''.join([chr(int(b, 16)) for b in [s[i:i + 2] for i in range(0, len(s), 2)]])


if __name__ == '__main__':
v = '182895d57f87530e854d9842ff02edaefc66fa1cca66c8f352111b6c5fbf22a9f057e5b74523cdd03f76424064df2c38ce45a68dd5492246e6b832c1b4edaacd8fb4e6050bed5a1a27ae7894d38b62e8453cd77fdbce3529d831e0278ac9e8ad3b8d6002ca82380b5ac61e7a19f773003136d64902c58f2ad563d04ce701c565'
b = bytes.fromhex(v)
k = base64.b64encode(b)
print(to_decrypt(k))
 

推荐阅读
author-avatar
爱心永溢真情永远
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有