這篇文章帶給大家的內容是關於Crypto演算法庫是什麼? Crypto演算法庫的詳解,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
安裝與使用
Crypto 演算法庫在 python 中最初叫 pycrypto,這個作者有點懶,好幾年沒有更新,後來就有大佬寫了個替代庫 pycryptodome。這個函式庫目前只支援 python3,安裝也很簡單pip install pycryptodome就行了!詳細的用法可以看看官方文件
常見對稱密碼在Crypto.Cipher 庫下,主要有:DES 3DES AES RC4 Salsa20
非對稱密碼在Crypto.PublicKey 庫下,主要有:RSA ECC DSA
雜湊密碼在Crypto.Hash 函式庫下,常用的有:MD5 SHA-1 SHA-128 SHA-256
隨機數在Crypto.Random 函式庫下
實用小工具在Crypto.Util 函式庫下
數字簽名在Crypto.Signature 庫下
對稱密碼AES
注意:python3 和python2 在字串方面有個明顯的區別- python3 中有位元組字串b'byte',python2 中沒有位元組
。由於這個函式庫是在 python3 下的,所以加解密用的都是位元組!
使用這個函式庫來加解密特別簡單,記住這四個步驟:
#匯入所需函式庫
from Crypto.Cipher import AES
- #初始化key
key = b'this_is_a_key'實例化加上解密物件
aes = AES.new(key,AES.MODE_ECB)
text_enc = aes.encrypt(b'helloworld')
from Crypto.Cipher import AES
import base64
key = bytes('this_is_a_key'.ljust(16,' '),encoding='utf8')
aes = AES.new(key,AES.MODE_ECB)
# encrypt
plain_text = bytes('this_is_a_plain'.ljust(16,' '),encoding='utf8')
text_enc = aes.encrypt(plain_text)
text_enc_b64 = base64.b64encode(text_enc)
print(text_enc_b64.decode(encoding='utf8'))
# decrypt
msg_enc = base64.b64decode(text_enc_b64)
msg = aes.decrypt(msg_enc)
print(msg.decode(encoding='utf8'))
注意:key和明文是需要填入指定位數的,可以使用ljust或zfill之類的填充,也可以用Util中的pad( )函數填充! 對稱密碼DESfrom Crypto.Cipher import DES
import base64
key = bytes('test_key'.ljust(8,' '),encoding='utf8')
des = DES.new(key,DES.MODE_ECB)
# encrypt
plain_text = bytes('this_is_a_plain'.ljust(16,' '),encoding='utf8')
text_enc = des.encrypt(plain_text)
text_enc_b64 = base64.b64encode(text_enc)
print(text_enc_b64.decode(encoding='utf8'))
# decrypt
msg_enc = base64.b64decode(text_enc_b64)
msg = des.decrypt(msg_enc)
print(msg.decode(encoding='utf8'))
非對稱密碼RSA這個函式庫的RSA 主要是用來
產生
讀取
公鑰檔案/私鑰檔案
from Crypto.PublicKey import RSA rsa = RSA.generate(2048) # 返回的是密钥对象 public_pem = rsa.publickey().exportKey('PEM') # 生成公钥字节流 private_pem = rsa.exportKey('PEM') # 生成私钥字节流 f = open('public.pem','wb') f.write(public_pem) # 将字节流写入文件 f.close() f = open('private.pem','wb') f.write(private_pem) # 将字节流写入文件 f.close() # -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArreg3IX19DbszqSdBKhR 9cm495XAk9PBQJwHiwjKv6S1Tk5h7xL9/fPZIITy1M1k8LwuoSJPac/zcK6rYgMb DT9tmVLbi6CdWNl5agvUE2WgsB/eifEcfnZ9KiT9xTrpmj5BJql9H+znseA1AzlP iTukrH1frD3SzZIVnq/pBly3QbsT13UdUhbmIgeqTo8wL9V0Sj+sMFOIZY+xHscK IeDOv4/JIxw0q2TMTsE3HRgAX9CXvk6u9zJCH3EEzl0w9EQr8TT7ql3GJg2hJ9SD biebjImLuUii7Nv20qLOpIJ8qR6O531kmQ1gykiSfqj6AHqxkufxTHklCsHj9B8F 8QIDAQAB -----END PUBLIC KEY----- -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEArreg3IX19DbszqSdBKhR9cm495XAk9PBQJwHiwjKv6S1Tk5h 7xL9/fPZIITy1M1k8LwuoSJPac/zcK6rYgMbDT9tmVLbi6CdWNl5agvUE2WgsB/e ifEcfnZ9KiT9xTrpmj5BJql9H+znseA1AzlPiTukrH1frD3SzZIVnq/pBly3QbsT 13UdUhbmIgeqTo8wL9V0Sj+sMFOIZY+xHscKIeDOv4/JIxw0q2TMTsE3HRgAX9CX vk6u9zJCH3EEzl0w9EQr8TT7ql3GJg2hJ9SDbiebjImLuUii7Nv20qLOpIJ8qR6O 531kmQ1gykiSfqj6AHqxkufxTHklCsHj9B8F8QIDAQABAoI... -----END RSA PRIVATE KEY-----###讀取公/私鑰檔案加解密:###
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 import base64 def rsa_encrypt(plain): with open('public.pem','rb') as f: data = f.read() key = RSA.importKey(data) rsa = PKCS1_v1_5.new(key) cipher = rsa.encrypt(plain) return base64.b64encode(cipher) def rsa_decrypt(cipher): with open('private.pem','rb') as f: data = f.read() key = RSA.importKey(data) rsa = PKCS1_v1_5.new(key) plain = rsa.decrypt(base64.b64decode(cipher),'ERROR') # 'ERROR'必需 return plain if __name__ == '__main__': plain_text = b'This_is_a_test_string!' cipher = rsa_encrypt(plain_text) print(cipher) plain = rsa_decrypt(cipher) print(plain)###注意: RSA 有兩種填色方式,一種是 PKCS1_v1_5,另一種是 PKCS1_OAEP######Hash演算法######和 hashlib 函式庫的用法類似,先實例化某個Hash 演算法,再用update( ) 調用就可以了! ######特定栗子:###
from Crypto.Hash import SHA1,MD5 sha1 = SHA1.new() sha1.update(b'sha1_test') print(sha1.digest()) # 返回字节串 print(sha1.hexdigest()) # 返回16进制字符串 md5 = MD5.new() md5.update(b'md5_test') print(md5.hexdigest())###數位簽章######發送髮用私鑰簽名,驗證方用公鑰驗證###
from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA # 签名 message = 'To be signed' key = RSA.import_key(open('private_key.der').read()) h = SHA256.new(message) signature = pkcs1_15.new(key).sign(h) # 验证 key = RSA.import_key(open('public_key.der').read()) h = SHA.new(message) try: pkcs1_15.new(key).verify(h, signature): print "The signature is valid." except (ValueError, TypeError): print "The signature is not valid."###隨機數#### ##和 random 庫類似。第一個函數很常用###
import Crypto.Random import Crypto.Random.random print(Crypto.Random.get_random_bytes(4)) # 得到n字节的随机字节串 print(Crypto.Random.random.randrange(1,10,1)) # x到y之间的整数,可以给定step print(Crypto.Random.random.randint(1,10)) # x到y之间的整数 print(Crypto.Random.random.getrandbits(16)) # 返回一个最大为N bit的随机整数###其它功能######常用到Util 中的###pad()###函數來填充金鑰###
from Crypto.Util.number import * from Crypto.Util.Padding import * # 按照规定的几种类型 pad,自定义 pad可以用 ljust()或者 zfill() str1 = b'helloworld' pad_str1 = pad(str1,16,'pkcs7') # 填充类型默认为'pkcs7',还有'iso7816'和'x923' print(unpad(pad_str1,16)) # number print(GCD(11,143)) # 最大公约数 print(bytes_to_long(b'hello')) # 字节转整数 print(long_to_bytes(0x41424344)) # 整数转字节 print(getPrime(16)) # 返回一个最大为 N bit 的随机素数 print(getStrongPrime(512)) # 返回强素数 print(inverse(10,5)) # 求逆元 print(isPrime(1227)) # 判断是不是素数###### ###
以上是Crypto演算法庫是什麼? Crypto演算法庫的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的關鍵特性包括:1.語法簡潔易懂,適合初學者;2.動態類型系統,提高開發速度;3.豐富的標準庫,支持多種任務;4.強大的社區和生態系統,提供廣泛支持;5.解釋性,適合腳本和快速原型開發;6.多範式支持,適用於各種編程風格。

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3漢化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。