当前位置: 首页 > 科技观察

几种常见加密算法的Python实现_0

时间:2023-03-19 21:46:55 科技观察

我们在生活中经常会遇到一些加密算法。今天我们就来说说这些加密算法的Python实现。一些常用的加密方法基本上都有对应的Python库,基本不需要我们用代码去实现具体的算法。MD5加密全称:MD5MessageDigestAlgorithm(英文:MD5Message-DigestAlgorithm),一种广泛使用的密码哈希函数,可以生成一个128位(16-byte)的哈希值(hashvalue),以保证完整性和信息传输的一致性。md5加密算法是不可逆的,所以解密一般都是通过暴力破解的方式,通过网站的接口实现解密。Python代码:importhashlibm=hashlib.md5()m.update(str.encode("utf8"))print(m.hexdigest())SHA1加密全称:安全哈希算法(SecureHashAlgorithm)主要适用于数字签名在(DigitalSignatureStandardDSS)中定义的标准(DigitalSignatureAlgorithmDSA),SHA1比MD5更安全。对于短于2^64位的消息,SHA1生成160位的消息摘要。Python代码:importhashlibsha1=hashlib.sha1()data='2333333'sha1.update(data.encode('utf-8'))sha1_data=sha1.hexdigest()print(sha1_data)HMAC加密全称:hash消息认证code(HashMessageAuthenticationCode),HMAC加密算法是一种基于加密哈希函数和共享密钥的安全消息认证协议。实现原理是利用公共函数和密钥生成一个固定长度的值作为认证标识符,并用这个标识符来标识消息的完整性。密钥用于生成一个固定大小的小数据块,即MAC,它被添加到消息中,然后被传输。接收方使用与发送方共享的密钥进行身份验证和身份验证。Python代码:importhmacimporthashlib#第一个参数是密钥,第二个参数是要加密的字符串,第三个参数是哈希函数mac=hmac.new('key','hello',hashlib.md5)mac。digest()#asciiformatofthestringmac.hexdigest()#hexadecimalformatoftheencryptedstringDES加密全称:数据加密标准(DataEncryptionStandard),属于对称加密算法。DES是一种块加密算法。典型的DES使用64位作为一个块来加密数据。加密和解密使用相同的算法。它的密钥长度为56位(因为每8位用作奇偶校验),密钥可以是任意56位数字,并且可以随时更改。Python代码:importbinasciifrompyDesimportdes,CBC,PAD_PKCS5#需要安装pipinstallpyDesdefdes_encrypt(secret_key,s):iv=secret_keyk=des(secret_key,CBC,iv,pad=None,padmode=PAD_PKCS5)en=k.encrypt(s,padmode=PAD_PKCS5)返回binascii.b2a_hex(en)defdes_decrypt(secret_key,s):iv=secret_keyk=des(secret_key,CBC,iv,pad=None,padmode=PAD_PKCS5)de=k.decrypt(binascii.a2b_hex(s),padmode=PAD_PKCS5)returndesecret_str=des_encrypt('12345678','IloveYOU~')print(secret_str)clear_str=des_decrypt('12345678',secret_str)print(clear_str)AES加密全称:高级加密标准(英文:AdvancedEncryptionStandard),在密码学中也称为Rijndael加密,是美国联邦政府采用的一种块加密标准。该标准用于替代原来的DES,经过多方分析,在世界范围内得到广泛应用。Python代码:importbase64fromCrypto.CipherimportAES'''AES对称加密算法'''#需要填写,如果str不是16的倍数,则补足16的倍数defadd_to_16(value):whilelen(value)%16!=0:value+='\0'returnstr.encode(value)#返回字节#加密方式defencrypt(key,text):aes=AES.new(add_to_16(key),AES.MODE_ECB)#初始化加密器encrypt_aes=aes.encrypt(add_to_16(text))#先进行aes加密encrypted_text=str(base64.encodebytes(encrypt_aes),encoding='utf-8')#执行加密转码返回字节returnencrypted_text#解密方式defdecrypt(key,text):aes=AES.new(add_to_16(key),AES.MODE_ECB)#初始化加密器base64_decrypted=base64.decodebytes(text.encode(encoding='utf-8'))#优先反向解密base64成bytesdecrypted_text=str(aes.decrypt(base64_decrypted),encoding='utf-8').replace('\0','')#执行解密转码返回strreturndecrypted_textRSA加密全名:Rivest-Shamir-Adleman,RSA加密算法是一种非对称加密算法。RSA广泛用于公钥加密和电子商务。普遍认为是目前较好的公钥方案之一。RSA是第一个可以同时用于加密和数字签名的算法,它可以抵抗目前已知的所有密码攻击。Python代码:#-*-coding:UTF-8-*-#referencecodes:https://www.jianshu.com/p/7a4645691c68importbase64importrsafromrsaimportcommon#使用rsa库进行RSA签名加解密classRsaUtil(object):PUBLIC_KEY_PATH='xxxxpublic_key.pem'#publickeyPRIVATE_KEY_PATH='xxxxxprivate_key.pem'#privatekey#initializationkeydef__init__(self,company_pub_file=PUBLIC_KEY_PATH,company_pri_file=PRIVATE_KEY_PATH):ifcompany_pub_file:self.company_public_key=rsa.PublicKey.load_pkcs1_openssl_popens)_popenssl_popens)_pkcs1_openssl_popens)_文件组件ifcompany_pri_file:self.company_private_key=rsa.PrivateKey.load_pkcs1(open(company_pri_file).read())defget_max_length(self,rsa_key,encrypt=True):"""当加密内容过长时,需要分段加密,转换每个segmentLength.:paramrsa_key:Key.:paramencrypt:加密与否."""blocksize=common.byte_size(rsa_key.n)reserve_size=11#保留位为11ifnotencrypt:#解密时无需考虑保留位reserve_size=0maxlength=blocksize-reserve_sizereturnmaxlength#加密付款人的公钥defencrypt_by_public_key(self,message):"""使用公钥加密。:parammessage:需要加密的内容。加密后需要进行base64转码"""encrypt_result=b''max_length=self.get_max_length(self.company_public_key)whilemessage:input=message[:max_length]message=message[max_length:]out=rsa.encrypt(input,self.company_public_key)encrypt_result+=outencrypt_result=4encode64.b加密结果=b''max_length=self.get_max_length(self.company_public_key)(encrypt_result)returnencrypt_resultdefdecrypt_by_private_key(self,message):"""使用私钥解密。:parammessage:需要加密的内容,解密后的内容直接为字符串,无需转义。"""decrypt_result=b""max_length=self.get_max_length(self.company_private_key,False)decrypt_message=base64.b64decode(消息)whiledecrypt_message:input=decrypt_message[:max_length]decrypt_message=decrypt_message[max_length:]out=rsa.decrypt(输入,self.company_private_key)decrypt_result+=outreturndecrypt_result#签名商户私钥base64转码defsign_by_private_key(self,data):"""私钥签名.:paramdata:需要签名的内容。使用SHA-1方法签名(或使用MD5)船尾呃签名,需要转义output"""signature=rsa.sign(str(data),priv_key=self.company_private_key,hash='SHA-1')returnbase64.b64encode(signature)defverify_by_public_key(self,message,signature):"""公钥签名验证。:parammessage:签名验证的内容。:paramsignature:签名验证内容的签名值(签名后,b64encode转码为执行,所以之前还需要进行签名校验Transcoding)。"""signature=base64.b64decode(signature)returnrsa.verify(message,signature,self.company_public_key)ECC加密全称:EllipticCurveCryptography(椭圆曲线密码学),ECC加密算法是一种公钥加密技术,以椭圆曲线理论为基础,利用椭圆曲线的点在有限域上形成的阿贝尔群的离散对数不可理解性,实现加密、解密和数字签名。将椭圆曲线中的加法运算对应到离散对数中的模乘运算,就可以建立相应的基于椭圆曲线的密码体制。Python代码:#-*-coding:utf-8*-#author:DYBOY#referencecodes:https://blog.dyboy.cn/websecurity/121.html#description:ECC椭圆曲线加密算法实现"""考虑K=kG,其中K和G为椭圆曲线Ep(a,b)上的点,n为G的阶数(nG=O∞),k为小于n的整数。给定k和G,根据加法规则,计算K很容易,但是反过来,给定K和G,求k就非常困难了。因为原则上,实际使用中的ECC使得p相当大,n也相当大,需要将n个解点一一计算出来列为上表是不可能的。这就是椭圆曲线加密算法的数学基础。点G称为基点(basepoint)k(kp-1temp=p-1-i#逆序#格式化输出1/2位数,y坐标轴iftemp>=10:print(temp,end="")else:print(temp,end="")#输出具体坐标的值,一行为jinrange(p):print(x_y[j][temp],end="")print("")#newline#输出x坐标轴print("",end="")foriinrange(p):ifi>=10:print(i,end="")else:print(i,end="")print('\n')defget_ng(G_x,G_y,key,a,p):"""计算nG"""temp_x=G_xtemp_y=G_ywhilekey!=1:temp_x,temp_y=get_np(temp_x,temp_y,G_x,G_y,a,p)key-=1returntemp_x,temp_ydefecc_main():whileTrue:a=int(input("请输入椭圆曲线参数a(a>0)的值:"))b=int(input("请输入椭圆曲线参数b的值(b>0):"))p=int(input("请输入椭圆曲线参数p的值(p为质数):"))#用作模运算#条件满足if(4*(a**3)+27*(b**2))%p==0:print("您输入的参数有误,请重新输入!!!\n")else:break#输出椭圆曲线散点图get_graph(a,b,p)#选点为G点print("user1:在上述坐标系中选择一个值为G的坐标")G_x=int(input("user1:请输入选择的x坐标值:"))G_y=int(input("user1:请输入选择的y坐标值:"))#获取椭圆曲线的阶数n=get_rank(G_x,G_y,a,b,p)#user1生成私钥,小keykey=int(input("user1:请输入私钥keysmallkey(<{}):".format(n)))#user1生成公钥,largeKEYKEY_x,kEY_y=get_ng(G_x,G_y,key,a,p)#user2阶段#user2获取user1的公钥KEY,Ep(a,b)令n,对需要加密的明文数据进行加密#加密准备k=int(input("user2:Pleaseenteranintegerk(<{})forkGandkQ:".format(n)))k_G_x,k_G_y=get_ng(G_x,G_y,k,a,p)#kGk_Q_x,k_Q_y=get_ng(KEY_x,kEY_y,k,a,p)#kQ#Encryptionplain_text=input("user2:请输入要加密的字符串:")plain_text=plain_text.strip()#plain_text=int(input("user1:请输入要加密的密文:"))c=[]print("密文为:",end="")forcharinplain_text:intchar=ord(char)cipher_text=intchar*k_Q_xc.append([k_G_x,k_G_y,cipher_text])print("({},{}),{}".format(k_G_x,k_G_y,cipher_text),end="-")#user1stage#获取user2加密数据解密#Knowingk_G_x,k_G_y,key,很容易解出k_Q_x,k_Q_y,那么plain_text=cipher_text/k_Q_xprint("\nuser1解密得到明文:",end="")forcharArrinc:decrypto_text_x,decrypto_text_y=get_ng(charArr[0],charArr[1],key,a,p)print(chr(charArr[2]//decrypto_text_x),end="")if__name__=="__main__":print("*************ECC椭圆曲线加密**************")ecc_main()本文主要介绍MD5、SHA-1、HMAC、DES/AES、RSA和ECC的加密算法以及上面的python代码示例就是今天的内容,希望大家喜欢,