这篇文章主要介绍了python实现无证书加密解密的方法,实例讲述了无证书加密解密的原理与具体实现过程,非常具有实用价值,需要的朋友可以参考下
本文实例讲述了python实现无证书加密解密的方法,分享给大家供大家参考。具体实现方法如下:
无证书加密就是双方不需要维护证书,加密与解密只需要双方约定一个key就可以,无证书加解密的方式应用更广泛一些,python官方也有这方面的相关例子说明,地址是:https://pypi.python.org/pypi/pycrypto,主要用的是from Crypto.Cipher import AES这个模块,代码如下:
代码如下:
”’
/**
* AES加密字符串
*
* @param string data 加密的串
* @param string key 密钥(只能是16、24、32位)
* @param string iv 16位长度向量
* @param bool 编码格式(true:base64 / false:十六进制)
* @return string 加密后的结果
*/
”’
def encrypt_mode_cbc(data, key, iv = ‘www.gaodaima.com!!’, base64 = True):
lenth = len(data)
num = lenth % 16
data = data.ljust(lenth + 16 – num)
obj = AES.new(key, AES.MODE_CBC, iv)
result = obj.encrypt(data)
return result.encode(‘base64’) if base64 is True else result.encode(‘hex’)
encrypt = encrypt_mode_cbc(‘hello geekso’, ‘www.gaodaima.com!!’)
print encrypt
”’
/**
* AES解密字符串
*
* @param string encrypted 待解密的串
* @param string key 密钥
* @param string iv 16位长度向量
* @param bool 编码(true:base64 / false:十六进制)
* @return string 解密后的结果 or bool
*/
”’
def decrypt_mode_cbc(encrypted, key, iv = ‘www.gaodaima.com!!’, bas来源gaodai#ma#com搞@@代~&码*网e64 = True):
encrypted = encrypted.decode(‘base64’) if base64 is True else encrypted.decode(‘hex’)
if encrypted is not ”:
obj = AES.new(key, AES.MODE_CBC, iv)
return obj.decrypt(encrypted)
else:
return False
/**
* AES加密字符串
*
* @param string data 加密的串
* @param string key 密钥(只能是16、24、32位)
* @param string iv 16位长度向量
* @param bool 编码格式(true:base64 / false:十六进制)
* @return string 加密后的结果
*/
”’
def encrypt_mode_cbc(data, key, iv = ‘www.gaodaima.com!!’, base64 = True):
lenth = len(data)
num = lenth % 16
data = data.ljust(lenth + 16 – num)
obj = AES.new(key, AES.MODE_CBC, iv)
result = obj.encrypt(data)
return result.encode(‘base64’) if base64 is True else result.encode(‘hex’)
encrypt = encrypt_mode_cbc(‘hello geekso’, ‘www.gaodaima.com!!’)
print encrypt
”’
/**
* AES解密字符串
*
* @param string encrypted 待解密的串
* @param string key 密钥
* @param string iv 16位长度向量
* @param bool 编码(true:base64 / false:十六进制)
* @return string 解密后的结果 or bool
*/
”’
def decrypt_mode_cbc(encrypted, key, iv = ‘www.gaodaima.com!!’, bas来源gaodai#ma#com搞@@代~&码*网e64 = True):
encrypted = encrypted.decode(‘base64’) if base64 is True else encrypted.decode(‘hex’)
if encrypted is not ”:
obj = AES.new(key, AES.MODE_CBC, iv)
return obj.decrypt(encrypted)
else:
return False
print decrypt_mode_cbc(encrypt,’www.gaodaima.com!!’)
exit()
以上就是python实现无证书加密解密实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!