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))

真诚邀请您走进我的知识小宇宙,关注我个人的公众号,在这里,我将不时为您献上独家原创且极具价值的技术内容分享。每一次推送,都倾注了我对技术领域的独特见解与实战心得,旨在与您共享成长过程中的每一份收获和感悟。您的关注和支持,是我持续提供优质内容的最大动力,让我们在学习的道路上并肩同行,共同进步,一起书写精彩的成长篇章!

AI文字转语音
AI个性头像生成
This post is licensed under CC BY 4.0 by the author.

Trending Tags