【python RAS验签】RSA生成公钥和私钥,并验签

1、RSA加密解密过程
公钥加密,私钥解密

2、RSA验签过程

私钥产生签名,公钥验证签名

1.服务端产生公钥和私钥
私钥,去掉换行,空格,头部,利用阿里的工具转成pkcs8给客户端
2.客户端用私钥对需要验签的参数,得到签名,用base64工具类加密一次
把需要验签的参数和签名传到服务端
3.服务端直接用python产生的公钥(不做任何处理),验证参数和解密之后的签名,看是否通过

python 自动生成公钥和私钥:

# -*- coding:utf-8 -*-
import rsa
import base64


# 生成RSA公钥和秘钥,经过base64转码
(pubkey, privkey) = rsa.newkeys(512)

# 经过base64编码
# pubkey = base64.encodebytes(pubkey.save_pkcs1())
# privkey = base64.encodebytes(privkey.save_pkcs1())


# 原始
pubkey = pubkey.save_pkcs1()
privkey =privkey.save_pkcs1()
print(pubkey)
print(privkey)


# 给java的pkcs1
privkey=str(privkey).replace('\\n','').replace("b'-----BEGIN RSA PRIVATE KEY-----",'').replace("-----END RSA PRIVATE KEY-----'",'').replace(' ','')
print(privkey)

pythonRSA验签:

import rsa
import base64

privkey_str= base64.decodebytes(b'LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlCUEFJQkFBSkJBSnFaOTkzZ28xMTE3\nZkNxVDJQZ3Jkc3VyYTRyNkR2UlM5dzZubm5UaHNvOVF5bWxjYzFFClRFYy9xWDRjbGNaZll3YVls\nNWcycnZkNWcvcmFKcGs2bjQwQ0F3RUFBUUpBUHhQQXlMc2xqRFZZYmsvZWNsNnkKTUhJOEZJci9o\ncUJmTml5SWlpWWVWQXJESGdGL3JjQnp3WkNKeUlCZk1MNkcySnR2WUxRYXpVdG5lbXg2MFFXSQo5\nUUlqQUw0UjRZR3hjTndoSmt4ei85YXdlbmV5ZGNySUc4Q0svOU5WNGFpaFVVOG1aNnNDSHdEUU9v\nSVlzRXVuCnJoL3JaK3JvUUZXL2JFaUl4YnRvS3NxQ3Njc3IvYWNDSXdDME1kZU5VV0FpRWZ0eE4v\nZ3czWmI5cTk4b3BKWksKOEh5aEt5YUk3SWRkZHBlSkFoNGVlc0g2VFN2MTBuWVhwakZyWjZkbGly\nc2ZVaG81aURIMmFZSDg0WGNDSWpiWgpHUzBYYzJRUC92cS9VUDFiT1pOeWJ0TlVGY0NuWGwrQjlp\nSEtOcGNCcGZnPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=\n')
print(privkey_str)
privkey = rsa.PrivateKey.load_pkcs1(privkey_str)

pubkey_str= base64.decodebytes(b'LS0tLS1CRUdJTiBSU0EgUFVCTElDIEtFWS0tLS0tCk1FZ0NRUUNhbWZmZDRLTmRkZTN3cWs5ajRL\nM2JMcTJ1SytnNzBVdmNPcDU1MDRiS1BVTXBwWEhOUkV4SFA2bCsKSEpYR1gyTUdtSmVZTnE3M2VZ\nUDYyaWFaT3ArTkFnTUJBQUU9Ci0tLS0tRU5EIFJTQSBQVUJMSUMgS0VZLS0tLS0K\n')
print(pubkey_str)
pubkey = rsa.PublicKey.load_pkcs1(pubkey_str)


message = b'Go left at the blue tree'
hash = rsa.compute_hash(message, 'SHA-1')
signature = rsa.sign_hash(hash, privkey, 'SHA-1')
#
print(signature)


message = b'Go left at the blue tree'

# signature=b'v\xd1J\xd4{-m\x83CK\xd9\x9a\xc3>22\x02\x07n\xb8LGwK\x96\x88D\xde\xe7""\x98\x1d\x92\xb0l\x8b\x1f\xd8\xc1\xa0\x10\xae\xe3L\xb0s\xe6<\xbf<\x05\x94\x03z\xae\x83VK\xe7s\x11\xf5J'
r = rsa.verify(message, signature, pubkey)
print(r)

你可能感兴趣的:(数据科学--python)