python實現openssl命令的sha1,hmac, base64加密

一段shell腳本,使用openssl命令對簽名進行了加密,需要用python將之實現出來

password=echo -en "$xxxx" | openssl dgst -sha1 -hmac $apiKey -binary | openssl enc -base64

先來了解一下openssl指令

openssl的對稱加密算法指令主要用來對數據進行加密和解密處理,openssl基本上爲所有其支持的對稱加密算法都提供了指令的方式的應用,這些應用指令的名字基本上都是以對稱加密算法本身的名字加上位數、加密模式或者其他屬性組合而成。以下標黑體的是本次使用到的參數。

xlzh@cmos:~/test$ openssl dgst –
unknown option ‘-‘
options are
-c to output the digest with separating colons //輸出的摘要信息以分號隔離,和-hex同時使用
-r to output the digest in coreutils format //指定輸出的格式
-d to output debug info //輸出BIO調試信息
-hex output as hex dump //以16進制打印輸出結果
-binary output in binary form //輸出二進制結果
-hmac arg set the HMAC key to arg //指定hmac的key
-non-fips-allow allow use of non FIPS digest //允許使用不符合fips標準的摘要算法
-sign file sign digest using private key in file //執行簽名操作,後面指定私鑰文件
-verify file verify a signature using public key in file //執行驗證操作,後面指定公鑰文件,與prverfify不能同時使用
-prverify file verify a signature using private key in file //執行驗證操作,後面指定密鑰文件,與verfify不能同時使用
-keyform arg key file format (PEM or ENGINE) //指定密鑰文件格式,pem或者engine
-out filename output to filename rather than stdout //指定輸出文件,默認標準輸出
-signature file signature to verify //指定簽名文件,在驗證簽名時使用
-sigopt nm:v signature parameter //簽名參數
-hmac key create hashed MAC with key //製作一個hmac 使用key
-mac algorithm create MAC (not neccessarily HMAC) //製作一個mac
-macopt nm:v MAC algorithm parameters or key //mac算法參數或者key
-engine e use engine e, possibly a hardware device. //使用硬件或者三方加密庫
-md4 to use the md4 message digest algorithm //摘要算法使用md4
-md5 to use the md5 message digest algorithm //摘要算法使用md5
-ripemd160 to use the ripemd160 message digest algorithm //摘要算法使用ripemd160
-sha to use the sha message digest algorithm //摘要算法使用sha
-sha1 to use the sha1 message digest algorithm //摘要算法使用sha1
-sha224 to use the sha224 message digest algorithm //摘要算法使用sha223
-sha256 to use the sha256 message digest algorithm //摘要算法使用sha256
-sha384 to use the sha384 message digest algorithm //摘要算法使用sha384
-sha512 to use the sha512 message digest algorithm //摘要算法使用sha512
-whirlpool to use the whirlpool message digest algorithm //摘要算法使用whirlpool

HMAC,散列消息鑑別碼,基於密鑰的Hash算法認證協議。實現原理爲:利用已經公開的Hash函數和私有的密鑰,來生成固定長度的消息鑑別碼;Hash-based message authentication code,利用哈希算法,以一個密鑰和一個消息爲輸入,生成一個消息摘要作爲輸出。 HMAC 算法可用於驗證在應用程序之間傳遞或存儲在潛在易受攻擊位置的信息的完整性。基本思想是生成與共享密鑰組合的實際數據的加密散列。然後,可以使用所得到的散列來檢查所發送或存儲的消息以確定信任級別,而不發送祕密密鑰

SHA1、MD5等Hash算法是比較常用的不可逆Hash簽名計算方法;

BASE64,將任意序列的8字節字符轉換爲人眼無法直接識別的符號編碼的一種方法;

以下是python代碼完成以上shell腳本的相同內容

password=echo -en "$xxxx" | openssl dgst -sha1 -hmac $apiKey -binary | openssl enc -base64

import hmac
import hashlib
import base64
import hmac

data = tx_date
tx_pass = hmac.new(settings.TX_KEY, data, hashlib.sha1).digest().encode(‘base64’).rstrip()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章