Python RSA簽名驗證加密解密 | Python 主題月

本文正在參加「Python主題月」,詳情查看活動連接python

1 RSA密鑰格式

經常使用的rsa密鑰有兩種格式,pkcs1pkcs8markdown

1.1 pkcs1

# 公鑰
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
# 私鑰
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
複製代碼

1.2 pkcs8

# 公鑰
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
# 私鑰
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
複製代碼

2 密鑰格式轉換

2.1 私鑰轉換

pkcs1 to pkcs8

openssl pkcs8 -topk8 -inform PEM -in private_pkcs1.pem -outform pem -nocrypt -out private_pkcs8.pem
複製代碼

pkcs8 to pkcs1

openssl pkcs8 -in private_pkcs8.pem -nocrypt -out private_plcs1.pem
複製代碼

2.2 公鑰轉換

使用pkcs8格式私鑰生成pkcs8格式公鑰app

openssl rsa -in pricate_pkcs8.pem -pubout -out public_pkcs8.pem
複製代碼

3 簽名、驗證、加密、解密

# -*- coding: utf-8 -*-
# Created: 03/03/2021
# Author: Honest1y

import base64
import Crypto.Signature.PKCS1_v1_5 as sign_PKCS1_v1_5 #用於簽名/驗籤
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5 #用於加密
from Crypto import Hash
from Crypto.PublicKey import RSA


class RsaCode(object):
    def __init__(self):
        self.public_key = "-----BEGIN PUBLIC KEY-----\nMGcw\n-----END PUBLIC KEY-----"
        self.private_key = "-----BEGIN PRIVATE KEY-----\nMIIBhQIBADANBgkqhkiG9w0BAQEFAAS\n-----END PRIVATE KEY-----"

    def sign(self, text):
        """ 私鑰簽名 :return: """
        signer_pri_obj = sign_PKCS1_v1_5.new(RSA.importKey(self.private_key))
        rand_hash = Hash.MD5.new()
        rand_hash.update(text.encode())
        signature = signer_pri_obj.sign(rand_hash)
        return base64.b64encode(signature).decode(encoding="utf-8")

    def verify(self, text, sign_result):
        """ RSA驗籤 :param signature: 簽名 :return: """
        signature = base64.b64decode(sign_result)
        verifier = sign_PKCS1_v1_5.new(RSA.importKey(self.public_key))
        _rand_hash = Hash.MD5.new()
        _rand_hash.update(text.encode())
        verify = verifier.verify(_rand_hash, signature)
        return verify


    def long_encrypt(self, msg):
        msg = msg.encode('utf-8')
        length = len(msg)
        default_length = 64
        pubobj = Cipher_pkcs1_v1_5.new(RSA.importKey(self.public_key))
        if length < default_length:
            return base64.b64encode(pubobj.encrypt(msg)).decode(encoding="utf-8")
        offset = 0
        res = []
        while length - offset > 0:
            if length - offset > default_length:
                res.append(pubobj.encrypt(msg[offset:offset + default_length]))
            else:
                res.append(pubobj.encrypt(msg[offset:]))
            offset += default_length
        byte_data = b''.join(res)
        return base64.b64encode(byte_data).decode(encoding="utf-8")

    def long_decrypt(self, msg):
        msg = base64.b64decode(msg)
        length = len(msg)
        default_length = 75
        priobj = Cipher_pkcs1_v1_5.new(RSA.importKey(self.private_key))
        if length <= default_length:
            return priobj.decrypt(msg, b'RSA').decode(encoding="utf-8")
        offset = 0
        res = []
        while length - offset > 0:
            if length - offset > default_length:
                res.append(priobj.decrypt(msg[offset:offset + default_length], b'RSA'))
            else:
                res.append(priobj.decrypt(msg[offset:], b'RSA'))
            offset += default_length
        print()
        return b''.join(res).decode('utf-8')


if __name__ == '__main__':
    text = "python rsa test"
    print("1 開始簽名")
    sign_result = RsaCode().sign(text)
    print("- 簽名結果爲: {}".format(sign_result))
    print("2 驗證簽名")
    verify_result = RsaCode().verify(text, sign_result)
    print("- 驗證結果爲: {}".format(verify_result))

    params = '{ "username": "python rsa" }'
    print("3 開始RSA加密")
    en_result = RsaCode().long_encrypt(params)
    print("- 加密結果爲: {}".format(en_result))
    print("4 開始RSA解密")
    de_result = RsaCode().long_decrypt(en_result)
    print("- 解密結果爲: {}".format(de_result))
複製代碼

4 驗證結果

1 開始簽名
- 簽名結果爲: QE+DF/YLbU/F6ARxeLGa3oJyiV2UvSxkxWuJJ8fruoKszc/v1+/Tl/4n5iHTb2q+/ODoqkvJOU2TYwjhp2AI9uOwyEkPUDai5mYc
2 驗證簽名
- 驗證結果爲: True
3 開始RSA加密
- 加密結果爲: EkaF5LsLEmpgVrfEjSB4XfMf06mE/0XQzWChVD6wrYh6k0axaWejiry6jVX+TT+T7P4Aw4VjJ2i5pnG2Xpga+xodRtFTC+LTnAuU
4 開始RSA解密
- 解密結果爲: { "username": "python rsa" }
複製代碼
相關文章
相關標籤/搜索