Python: AES encryption and decryption, aes encryption and decryption

Source: Internet
Author: User

Python: AES encryption and decryption, aes encryption and decryption

Origin:

When the video is downloaded and parsed to a website, it is found that the video id is encrypted with AES, and the file is https://code.google.com/archive/p/crypto-js.
Decryption is a simple JavaScript code:

t.video = CryptoJS.AES.decrypt(t.video, secret).toString(CryptoJS.enc.Utf8);

I thought it was simple. I had to find a python code segment for decryption. I didn't expect to try it again and again. There were a variety of writing methods, but I couldn't solve it. It took a lot of time!

How easy? I only need to verify the following string encryption and decryption:

    # data = '-85297962_172051801'    # key = '583a01a9ba901a3adda7252ebca42c09'    # encrypt_data = 'U2FsdGVkX192df0Gxgia8s93zZp85f9m2nU1VIGU+RZQDtViB1LPBnE0CBWgVDBj'

 

1. Python Cryptography Toolkit (pycrypto)

Encryption and decryption needs to use it, its URL is: https://pypi.python.org/pypi/pycrypto
The latest version is 2.6.1. How to install it and its simple Demo, on its page, and its usage is everywhere on the Internet, but it cannot solve my problem. I think I used it wrong, but which one is right!

Crypto-js should use the default AES mode, AES. MODE_CBC. JavaScript code is also hard to understand and keeps trying!

 

2. encryption and decryption

Go directly to the code. It meets the requirements:

# coding=utf-8import base64from Crypto.Cipher import AESfrom Crypto import Randomfrom hashlib import md5BLOCK_SIZE = AES.block_sizedef pad(data):    length = BLOCK_SIZE - (len(data) % BLOCK_SIZE)    return data + (chr(length) * length).encode()def unpad(data):    return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]def bytes_to_key(my_data, salt, output=48):    # extended from https://gist.github.com/gsakkis/4546068    assert len(salt) == 8, len(salt)    my_data += salt    key = md5(my_data).digest()    final_key = key    while len(final_key) < output:        key = md5(key + my_data).digest()        final_key += key    return final_key[:output]def encrypt(message, passphrase):    salt = Random.new().read(8)    key_iv = bytes_to_key(passphrase, salt, 32 + 16)    key = key_iv[:32]    iv = key_iv[32:]    aes = AES.new(key, AES.MODE_CBC, iv)    return base64.b64encode(b"Salted__" + salt + aes.encrypt(pad(message)))def decrypt(data, password):    if len(data) <= BLOCK_SIZE:        return data    data = base64.b64decode(data)    salt = data[8:16]    key_iv = bytes_to_key(password, salt, 32 + 16)    key = key_iv[:32]    iv = key_iv[32:]    cipher = AES.new(key, AES.MODE_CBC, iv)    return unpad(cipher.decrypt(data[BLOCK_SIZE:]))if __name__ == '__main__':    # data = '-85297962_172051801'    # key = '583a01a9ba901a3adda7252ebca42c09'    # encrypt_data = 'U2FsdGVkX192df0Gxgia8s93zZp85f9m2nU1VIGU+RZQDtViB1LPBnE0CBWgVDBj'    key = '583a01a9ba901a3adda7252ebca42c09'    data = '-85297962_172051801'    encrypt_data = encrypt(data, key)    print encrypt_data    # encrypt_data = 'U2FsdGVkX192df0Gxgia8s93zZp85f9m2nU1VIGU+RZQDtViB1LPBnE0CBWgVDBj'    decrypt_data = decrypt(encrypt_data, key)    print 'decrypt_data:', decrypt_data

The same string. The encrypted strings are found to be different each time. I don't have much research on AES. It's strange!

 

3. Packaging and Publishing

If only a part of Crypto functions are used, for example, aes decryption, you can extract the required code to avoid entering the entire Crypto library.

The strange thing is that there is a problem with the reference path when referencing the dynamic library _ AES. pyd. For more information, the Reference Path of Crypto is dead. The page code is as follows:
Https://github.com/dlitz/pycrypto/blob/master/src/block_template.c#L801

#ifdef IS_PY3K    m = PyModule_Create(&moduledef);#else    m = Py_InitModule("Crypto.Cipher." _MODULE_STRING, modulemethods);#endif

 

Py2exe is used for packaging and extraction. It renamed Crypto \ Cipher \ _ AES. pyd to the Crypto. Cipher. _ AES. pyd file, which is under the release directory.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.