Solve the garbled problem of AES algorithm CBC mode encryption string after decryption

Source: Internet
Author: User
Tags crypt

Problem

After encrypting the string with AES CBC mode, the decrypted string is garbled, usually the first dozens of bytes are garbled;

Repetition

Because the department CGI is used? Aesencryptutil Library, after finding the problem, it is not easy to reproduce here, the use of Python to reproduce, can be easily reproduced.

#!/usr/bin/env python#coding =utf-8 fromCrypto.cipherImportAes? PADDING= ' + ' if __name__ == "__main__":? ? ? Pad_it= LambdaS:s+( - - Len(s)% -)*PADDING??? Key= ' 0123456789abcdef '? ? ? Data=Pad_it (' Luffichen0123456789abcdef ') ? ? Aes_util=Aes.new (Key, AES. MODE_CBC, b' 0000000000000000 ')?? ?? Crypt=Aes_util.encrypt (data)??Print(Base64.b64decode (crypt))??Print(data)??# using the same aes_util can cause garbled characters? ? Recovery=Aes_util.decrypt (crypt)??Print(recovery)

Output Result:

Conclusion

In the CBC mode, the same AES object, all previous encryption and decryption will affect the next encryption and decryption (encryption and decryption who first the impact is the same), because CBC is Block chained, encryption is serial, it is necessary to rely on the last block of the encryption and decryption results, it can be understood as it is the process of recording the middle State, So the next encryption and decryption using the original AES object has problems; The ECB model does not have this problem; more details can be seen wiki:https://en.wikipedia.org/wiki/block_cipher_mode_of_operation

Workaround

Each decryption requires a re-generation of an AES object.

Solve the garbled problem of AES algorithm CBC mode encryption string after decryption

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.