Python implements certificate free encryption and decryption instances

  • 2020-04-02 14:16:13
  • OfStack

The example of this article describes the python implementation of certificate-free encryption and decryption method, to share with you for your reference. The specific implementation method is as follows:

No certificate encryption is the two sides do not need to maintain, and a key encryption and decryption only need the two sides can, without certificate encryption method used more widely, python official also have this aspect of the relevant examples, the address is: https://pypi.python.org/pypi/pycrypto, mainly with the from Crypto. The Cipher import AES this module, the code is as follows:

'''
/**
* AES Encrypted string
*
* @param string data Encrypted string
* @param string key The key ( Can only be 16 , 24 , 32 position )
* @param string iv 16 Bit length vector
* @param bool Coding format ( true:base64 / false: Hexadecimal)
* @return string The encrypted result
*/
'''
def encrypt_mode_cbc(data, key, iv = 'www.jb51.net!!', 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.jb51.net!!')
print encrypt
'''
/**
* AES Decrypt string
*
* @param string encrypted String to be decrypted
* @param string key The key
* @param string iv 16 Bit length vector
* @param bool Encoding ( true:base64 / false: Hexadecimal)
* @return string Decrypted results or bool
*/
'''
def decrypt_mode_cbc(encrypted, key, iv = 'www.jb51.net!!', 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.jb51.net!!')
exit()

I hope this article has helped you with your Python programming.


Related articles: