python 支付宝公钥验证

1. 把公钥裁剪成支付宝要的样式:

#!/usr/bin/env python3.6
from pathlib import Path

def saybody(fname):
    ss = Path(fname).read_text().strip().split('\n')
    return ''.join(ss[1:-1])


def main():
    import sys
    fname = sys.argv[1] if sys.argv[1:] else 'app_public_key.pem'
    try:
        print(saybody(fname))
    except IOError:
        print('Error: public key not found.\n')
        print(f'Usage:\n{" "*4}python3.6 {sys.argv[0]} /path/to/public/key')

if __name__ == '__main__':
    main()

2. 验证上传的公钥与本地私钥是否匹配(需要`pip install pycryptodomex`)

#!/usr/bin/env python3.6
from base64 import encodebytes
from pathlib import Path
from Cryptodome.Signature import PKCS1_v1_5
from Cryptodome.Hash import SHA256
from Cryptodome.PublicKey import RSA


class Alipay:
    def __init__(self, prikey):
        if Path(prikey).exists():
            prikey = Path(prikey).read_text()
        self.prikey = RSA.importKey(prikey)

    def sign_str(self, unsigned_str='a=123'):
        signer = PKCS1_v1_5.new(self.prikey)
        signature = signer.sign(SHA256.new(unsigned_str.encode()))
        return encodebytes(signature).decode().replace("\n", "")


def main():
    import sys
    fname = sys.argv[1] if sys.argv[1:] else 'app_private_key.pem'
    if len(fname) < 100 and not Path(fname).exists():
        print('Error: private key not found.\n')
        print(f'Usage:\n{" "*4}python3.6 {sys.argv[0]} /path/to/private/key')
        return
    result = Alipay(fname).sign_str()
    print(result)


if __name__ == '__main__':
    main()

运行:假设1、2的文件名分别为cut_pub.py和pri_sign.py,把它们放到私钥和公钥所在文件夹里,运行如下命令即可得到公钥裁剪后的字符串和a=123被签名后的结果:

$ chmod +x cut_pub.py
$ ./cut_pub.py

$ chmod +x pri_sign.py
$ python3.6 -m pip install pycryptodomex --user
$ ./pri_sign.py

 

你可能感兴趣的:(python)