久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

python des,aes,rsa加解密的實現

瀏覽:4日期:2022-06-29 16:54:17
AES加解密

AES 只是個基本算法,實現 AES 有幾種模式,主要有 ECB、CBC、CFB 和 OFB CTR,直接上代碼,此處為AES加密中的CBC模式,EBC模式與CBC模式相比,不需要iv。

import base64from Crypto.Cipher import AESfrom binascii import b2a_hex, a2b_hex unpad = lambda s: s[:-ord(s[len(s) - 1:])]class AES3: def __init__(self, key): self.key = key self.mode = AES.MODE_CBC self.iv = self.key def _pad(self, text): key_len = len(self.key) pad = text + (key_len - len(text) % key_len) * chr(key_len - len(text) % key_len) return pad def _unpad(self, text): pad = ord(text[-1:]) return text[0:-pad] # 加密函數 def encrypt(self, text): length = 16 count = len(text) if count % length != 0: add = length - (count % length) else: add = 0 text = text + (’0’ * add) cryptor = AES.new(self.key.encode('utf8'), self.mode, self.iv.encode('utf8')) self.ciphertext = cryptor.encrypt(bytes(text, encoding='utf8')) # AES加密時候得到的字符串不一定是ascii字符集的,輸出到終端或者保存時候可能存在問題,使用base64編碼 return base64.b64encode(b2a_hex(self.ciphertext)).decode(’utf-8’) # 解密函數 def decrypt(self, text): decode = base64.b64decode(text) cryptor = AES.new(self.key.encode('utf8'), self.mode, self.iv.encode('utf8')) plain_text = unpad(cryptor.decrypt(decode)) return a2b_hex(plain_text) .decode(’utf8’)RSA公鑰加密,私鑰解密

from Crypto.PublicKey import RSAfrom Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5import base64# 私鑰private_key = ’’’-----BEGIN RSA PRIVATE KEY-----5353dfggd-----END RSA PRIVATE KEY-----’’’# 公鑰public_key = ’’’-----BEGIN PUBLIC KEY-----hfgghftetet-----END PUBLIC KEY-----’’’def rsa_encrypt(message): '''校驗RSA加密 使用公鑰進行加密''' cipher = Cipher_pkcs1_v1_5.new(RSA.importKey(public_key)) cipher_text = base64.b64encode(cipher.encrypt(message.encode())).decode() return cipher_textdef rsa_decrypt(text): '''校驗RSA加密 使用私鑰進行解密''' cipher = Cipher_pkcs1_v1_5.new(RSA.importKey(private_key)) retval = cipher.decrypt(base64.b64decode(text), ’ERROR’).decode(’utf-8’) return retvalDES加解密

from pyDes import *import base64class Des3(object): def __init__(self, key, iv): # 這里密鑰key長度必須為16/24, ,偏移量ivs self.key = key self.mode = CBC self.iv = iv # 加密函數,如果text不是16的倍數【加密文本text必須為16的倍數!】,那就補足為16的倍數 def encrypt(self, text): des3 = triple_des(self.key, self.mode, self.iv, pad=None, padmode=PAD_PKCS5) data = des3.encrypt(text) data = base64.b64encode(data) return data.decode(’utf-8’) # 解密后,去掉補足的空格用strip() 去掉 def decrypt(self, data): des3 = triple_des(self.key, self.mode, self.iv, pad=None, padmode=PAD_PKCS5) data = base64.b64decode(data) text = des3.decrypt(data) return text.decode(’hex’)

以上就是python des,aes,rsa加解密的實現的詳細內容,更多關于python des,aes,rsa加解密的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 芜湖县| 白玉县| 应城市| 东台市| 元氏县| 多伦县| 平昌县| 夏邑县| 全南县| 北辰区| 永仁县| 黔江区| 忻州市| 怀柔区| 和田市| 东山县| 新乐市| 建德市| 罗甸县| 凌海市| 万盛区| 西藏| 泰和县| 德州市| 蒲城县| 精河县| 阳城县| 遂川县| 太仆寺旗| 石狮市| 樟树市| 玉环县| 绥化市| 彰化县| 香河县| 双柏县| 崇左市| 博兴县| 方山县| 光山县| 娄烦县|