——引子:本文主要针对python使用密码学算法原理的简单表述,主要说明了几种加密算法的主要原理和特点;python相关库的安装、说明和使用。可以解决如下问题:1.
from Crypto.Cipher import DES
要安装pycrypto库。2.pycrypto安装不上怎么办。3.pycryptodome和pycryptodomex有什么区别
版本:python3.7, pycryptodome3.9
安装: pip install pycryptodome
涉及模块说明: pycrypto、pycryptodome、pycryptodomex
pycrypto: 原始密码学模块,无人维护(已废弃)
pycryptodome: 强制替代pycrypto模块,用法相同,其安装在Crypto包下
All modules are installed under the Crypto package.
Check the pycryptodomex project for the equivalent library that works under the Cryptodome package.
pycryptodomex: 同pycryptodome功能,但与pycrypto模块可以共存,都安装在Cryptodome包下
All modules are installed under the Cryptodome package.
Check the pycryptodome project for the equivalent library that works under the Crypto package.
In this case, all modules are installed under the Cryptodome package. PyCrypto and PyCryptodome can coexist.
对称加密算法 具有更高的加密速度,但双方都需要事先知道秘钥,秘钥在传输过程中可能会被窃取,因此安全性没有非对称加密高。 如:‘DES’, ‘AES’, ‘3DES’
非对称加密算法 加密速度低于对称加密算法,但安全性更高。 如:RSA, DSA, ECC
利用字典的格式转换加密。 MAKETRANS()
#DES加密示例:
from Crypto.Cipher import DES
key = b'abcdefgh' # 密钥 8位或16位,必须为bytes
def pad(text):
"""加密函数,如果text不是8的倍数【加密文本text必须为8的倍数!】,那就补足为8的倍数
"""
while len(text) % 8 != 0:
text += ' '
return text
des = DES.new(key, DES.MODE_ECB) # 创建一个DES实例
text = 'Python rocks!'
padded_text = pad(text)
encrypted_text = des.encrypt(padded_text.encode('utf-8')) # 加密
print(encrypted_text)
#rstrip(' ')返回从字符串末尾删除所有字符串的字符串(默认空白字符)的副本
plain_text = des.decrypt(encrypted_text).decode().rstrip(' ') # 解密
print(plain_text)
#示例:ECB模式, 比CBC少一个key, 其他用法等同
from Cryptodome.Cipher import AES
from binascii import b2a_hex, a2b_hex
key = 'abcdefgh' # 秘钥,此处需要将字符串转为字节
def pad(text): # 加密内容需要长达16位字符,所以进行空格拼接
while len(text) % 16 != 0:
text += ' '
return text
aes = AES.new(key.encode(), AES.MODE_ECB) # 进行加密算法,模式ECB模式
text = 'hello' # 加密内容,此处需要将字符串转为字节
encrypted_text = aes.encrypt(pad(text).encode()) # 进行内容拼接16位字符后传入加密类中,结果为字节类型
encrypted_text_hex = b2a_hex(encrypted_text)
print(encrypted_text_hex)
#用aes对象进行解密,将字节类型转为str类型,错误编码忽略不计
de = str(aes.decrypt(a2b_hex(encrypted_text_hex)), encoding='utf-8',errors="ignore")
print(de[:len(text)]) # 获取str从0开始到文本内容的字符串长度。
#示例:
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
def pad(text):
"""加密文本text必须为16的倍数!
"""
while len(text) % 16 != 0:
text += '\0'.encode('utf-8') # \0 可以被decode()自动清除,并且不会影响本来的字符0
return text
def encrypt(text):
cryptor = AES.new(key.encode('utf-8')), AES.MODE_CBC, key.encode('utf-8')) # 此变量是一次性的(第二次调用值会变)不能作为常量通用
ciphertext = cryptor.encrypt(pad(text.encode('utf-8'))) # encode()转换是因为十六进制用的是字节码
return b2a_hex(ciphertext).decode('utf-8') # 因为AES加密时候得到的字符串不一定是ascii字符集的,所以使用十六进制转换才能print来储存
def decrypt(text):
cryptor = AES.new(key.encode('utf-8'), AES.MODE_CBC, key.encode('utf-8'))
plain_text = cryptor.decrypt(a2b_hex(text.encode('utf-8')))
return plain_text.decode('utf-8').rstrip('\0') # 去除凑数补全的\0
================================================================================
#示例:
import rsa
from binascii import b2a_hex, a2b_hex
class rsacrypt():
def __init__(self, pubkey, prikey):
self.pubkey = pubkey
self.prikey = prikey
def encrypt(self, text):
self.ciphertext = rsa.encrypt(text.encode(), self.pubkey)
# 因为rsa加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
# 所以这里统一把加密后的字符串转化为16进制字符串
return b2a_hex(self.ciphertext)
def decrypt(self, text):
decrypt_text = rsa.decrypt(a2b_hex(text), prikey)
return decrypt_text
if __name__ == '__main__':
pubkey, prikey = rsa.newkeys(256)
rs_obj = rsacrypt(pubkey,prikey)
text='hello'
ency_text = rs_obj.encrypt(text)
print(ency_text)
print(rs_obj.decrypt(ency_text))
"""
b'7cb319c67853067abcd16aad25b3a8658e521f83b1e6a6cf0c4c2e9303ad3e14'
b'hello'
"""
#示例:
s1 = base64.encodestring('hello world') # aGVsbG8gd29ybGQ=
s2 = base64.decodestring(s1) # hello world
print s1, s2
#示例:
from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "The answer is no"
ciphertext = obj.encrypt(message)
print(ciphertext)
#'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
decryptext = obj2.decrypt(ciphertext)
print(decryptext)
#'The answer is no'
#示例:
from string import maketrans # 必须调用 maketrans 函数。
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!"
print(str.translate(trantab))
https://www.pycryptodome.org/en/latest/src/installation.html
https://pypi.org/project/pycryptodomex/#description
https://pypi.org/project/pycryptodome/
https://pypi.org/project/pycrypto/
网络
tips:如有疑问,欢迎留言