本文 51893 pv

0

python无证书的加密解密

© kekehu / 技术资源 / 2014.10.14 / 15:20 / 51893PV

无证书加密的好外就是双方不需要维护证书,加密与解密只需要双方约定一个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.geekso.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.geekso.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.geekso.com!!', base64 = 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.geekso.com!!')
exit()

本文有 0 篇评论

发表你的见解

打开HTML 打开UBB 打开表情 隐藏 记住我
emotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemotemot
emotemotemotemotemot