Posts python实现aes256cbc加密解密
Post
Cancel

python实现aes256cbc加密解密

python2版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/python
# encoding: utf-8

import base64
from Crypto.Cipher import AES
from Crypto import Random
import hashlib

class AESCipher:
    def __init__( self, key ):
        self.bs = 32
        self.key = hashlib.sha256(key.encode()).hexdigest().decode("hex")

    def encrypt( self, raw ):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return ( iv + cipher.encrypt( raw ) ).encode("hex")

    def decrypt( self, enc ):
        iv = enc[:32]
        enc= enc[32:]
        cipher = AES.new(self.key, AES.MODE_CBC, iv.decode('hex') )
        return self._unpad(cipher.decrypt( enc.decode('hex')))

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    def _unpad(s):
        return s[:-ord(s[len(s) - 1:])]

if __name__== "__main__":
    key = "1E571258CE38D08672352587686B63D3"
    text = "abc123不要埋怨那种因为你穷而离开你的人,人生路还很长,总有一天你会知道,还有人因为你丑而离开你。"
    decryptor = AESCipher(key)
    etext = decryptor.encrypt(text)
    print(etext)
    print(decryptor.decrypt(etext))
    

python3版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/python
# encoding: utf-8
from Crypto.Cipher import AES
from Crypto import Random
import hashlib

class AESCipher:
    def __init__( self, key ):
        self.bs = 32
        self.key = bytes.fromhex(hashlib.sha256(key.encode()).hexdigest())

    def encrypt( self, raw ):
        content_padding = self._pad(raw).encode()
        iv = Random.new().read(AES.block_size)
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        encrypt_bytes = cipher.encrypt(content_padding)
        return (iv + encrypt_bytes).hex()

    def decrypt( self, enc ):
        enc = bytes.fromhex(enc)
        iv = enc[:AES.block_size]
        enc = enc[AES.block_size:]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        encrypt_bytes = enc
        decrypt_bytes = cipher.decrypt(encrypt_bytes)
        return self._unpad(decrypt_bytes.decode('utf-8'))

    def _pad(self, s):
        return s + (self.bs - len(s.encode()) % self.bs) * chr(self.bs - len(s.encode()) % self.bs)

    def _unpad(self, s):
        return s[:-ord(s[len(s) - 1:])]

if __name__== "__main__":
    key = "1E571258CE38D08672352587686B63D3"
    text = "abc123不要埋怨那种因为你穷而离开你的人,人生路还很长,总有一天你会知道,还有人因为你丑而离开你。"
    decryptor = AESCipher(key)
    etext = decryptor.encrypt(text)
    print(etext)
    print(decryptor.decrypt(etext))

邀请您关注我的公众号,我将会不时地为您推送独家原创的技术内容分享。
This post is licensed under CC BY 4.0 by the author.

Trending Tags