1. 程式人生 > >python + openssl對資料進行簽名

python + openssl對資料進行簽名

1. 基礎介紹

在資訊傳遞的過程中為了保證資料是由確定的一方傳送的,需要通過某種方式驗證資料傳送方的身份。目前大家比較常用的可能是是用openssl生成一個私鑰,然後根據私鑰生成對應的公鑰,這個過程可以通過下述兩個命令完成:

openssl genrsa -out rsa_private_key.pem 1024
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

這兩者的工作機制是,通過公鑰加密的資料只能通過對應的私鑰才能解密檢視。而通過私鑰加密的資料如果能被對應的公鑰解開則可斷定資料由該私鑰的所有者傳送。前一個機制可以用於加密訊息的傳遞,後一個則可以用於身份的確認,凡事通過公鑰A能解密的資料一定是私鑰A的所有者傳送的資料。

2. 簽名流程

這裡身份確認一般需要經過以下幾個步驟:

senderreceiver生成公鑰私鑰傳送公鑰用私鑰對資料進行簽名簽名後的資料用sender的公鑰驗證是否能解密這個資料確實是sender發的!senderreceiver

3. python簽名版

3.1 使用的工具:python3+pyopenssl+base64+openssl

  1. 先來安裝pyopenssl
$pip install pyopenssl

base64是用python內建的就可以了

3.2 簽名的程式碼

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:pengjian05
# datetime:2018/11/9 10:41 # software: PyCharm import OpenSSL.crypto as ct import base64 class Certificate: _privateKey = '' def __init__(self, private_key_content): self._privateKey = private_key_content def get_sig(self, content): """ 生成簽名 :param content: :return: """
if not content or not self._privateKey: return False pkey = ct.load_privatekey(ct.FILETYPE_PEM, self._privateKey) if pkey: signature = ct.sign(pkey, content.encode('utf8'), 'sha1') ret = base64.encodebytes(signature) return ret.decode('utf8').replace('\n', '') return False

4. php簽名版

<?php
namespace Baidu\Apm\BotMonitorsdk;

class Certificate{
    /**
     * @param string $privateKeyContent
     * @return null
     */
    public function __construct($privateKeyContent = '') {
        $this->privateKey = $privateKeyContent;
    }

    /**
     * 生成簽名
     * @param string $content
     * @return string|boolean
     */
    public function getSig($content) {
        if(!$this->privateKey || !$content) {
            return false;
        }
        
        $privateKey = openssl_pkey_get_private($this->privateKey, '');
        
        if ($privateKey) {
            $encryptedData = '';
            // 私鑰加密
            openssl_sign($content, $encryptedData, $privateKey, OPENSSL_ALGO_SHA1);
            return base64_encode($encryptedData);
        }
        return false;
    }
}