python 使用 OpenSSL
pyOpenSSL是Python的openssl库.
通过pip安装:
pip install pyOpenSSL
产生密钥对
from OpenSSL.crypto import PKey
from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
from OpenSSL.crypto import dump_privatekey, dump_publickey
pk = PKey()
print(pk)
pk.generate_key(TYPE_RSA, 1024)
dpub = dump_publickey(FILETYPE_PEM, pk)
print(dpub)
dpri = dump_privatekey(FILETYPE_PEM, pk)
print(dpri)
运行结果:
<OpenSSL.crypto.PKey object at 0x76c3b090>
b'-----BEGIN PUBLIC KEY-----nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyNCTZuEzZrX2OaaPgcdCsd3VInPXVGyWKzCc0rUdmmrD7+czdeCgoeHuCwwkig+pGhYFYZvFNZFaEzxKmmJOTxrklBnxOk2K2mTvqsviPMFG780qG69zM+Zm+tYPy+aU4taRoPhlSY9hy2YWubKiLqUkGWXnfoJOElkGFD+O4IwsWwIDAQABn-----END PUBLIC KEY-----n'
b'-----BEGIN PRIVATE KEY-----nMIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALI0JNm4TNmtfY5pno+Bx0Kx3dUg9dUbJYrMJzStR2aasPv5zN14KCh4e4LDCSKD6kaFgVhm8U1kVoTPEnqaYk5PGuSUHE6TYraZO+qy+I8wUbvzSobr3Mz5mb61g/L5pTi1pGg+GVJj2HLZhan5sqIupSQZZd+gk4SWQYUP47gjCxbAgMBAAECgYEAhqYNvhCayNNlDmlV8O4uvVIZn5TbC2XSrRhq+0t+qtFxr0Llf+Ydec7njDswOMsyBo0z2YcXBuIs2XbZYdXhlH9AgnWWrkhRPVLN0mvs/XPpXRkQh233orznIgoz8UBuoUlcXppA/KOnSSJ2RuwVtiqAl5nQf71oRSVZ7AmKy6PLOECQQDofMyLSx9KWoQ/HSiw7w9lgX7+olyB3ybg+Hi9YdrhnyxWJ2VJoY5TTCCsREsAyF86fRSNuaF3PpU/6oYkT+6brAkEAxDnp8jAKmrfX8qKTnnNOwFJaAJBAihtrgeURPWGiCTSWR9w0S5w+AKeeGU9oEhuPaUK1rUdtqYlFMhAgjn2iYUUQJAEw9wQZdGGHV1VCtS07a1v2+vdrbe+LLP4C/ezkAAjvR0bpnHnNFVOTv5nM+win7i98ubbMckSr9xwwy6NK3s9QwJAU2wjr5kJCRnbrwW7J9M/aqFJPQu3AgoPnoL6P1RApRU8RrSxbuuv2GtqZWxC3F/nKmL4BgD1+DuptUzx6sYW64QJAC5jNhQw7nd1AzDBc4X8fkcOH1+fn3sNGT5UBZ5+1l8jy44QR0ZaDsbGKyWEizDiJVvC01eNJdnTDj99Venyyug6Q==n-----END PRIVATE KEY-----n'
签名与验签
from OpenSSL.crypto import PKey
from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
from OpenSSL.crypto import sign, verify
from OpenSSL.crypto import X509
pk = PKey()
pk.generate_key(TYPE_RSA, 1024)
signature = sign(pk, 'hello, world!', 'sha256')
print(signature)
x509 = X509()
x509.set_pubkey(pk)
verify(x509, signature, 'hello, world!', 'sha256')
结果:
b'txe1xb1rxc1}x82x9dxbexa2x97x14x88xdbxf7x19x835xeb=xc0x87xa5xe9xe7x10xcdxaax90Qx11xee;oxf4Axafxa0xfcj3Xtxd9=x10xf3xbdxe9xc3>@xc1xafxffx8dxfbtxd9x81xfaxdexa2QLxc2xf0t+_wxfex1bx86x0f\xebJ\x17
xcaxf4x11xb0lxd6x17`xfdx194xa6x0cxe3yx93Exd2x92Bx984-(xc8qxdax1e:,xd4x83jxca(jxe4xb5Gxa6(xfaxffx97xa2xabxa9xd6'
如果验签失败,会出现以下错误.
OpenSSL.crypto.Error: [('rsa routines', 'int_rsa_verify', 'bad signature')]
本文链接地址:https://const.net.cn/703.html