python & js Crypto AES ECB Pkcs7 加密解密实现

基于一个需求:后端用python 加密js 脚本,前端用js 解密

python & js Crypto AES ECB Pkcs7 加密解密实现

python 实现:

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
41
# -*- coding=utf-8-*-

from base64 import b64decode
from base64 import b64encode
from Crypto.Cipher import AES

BLOCK_SIZE = 16  # Bytes


class AESCipher:

    def __init__(self, key):
        self.key = key

    def pad(self, s):
        return s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)

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

    def encrypt(self, raw):
        raw = self.pad(raw)
        cipher = AES.new(self.key, AES.MODE_ECB)
        return b64encode(cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = b64decode(enc)
        cipher = AES.new(self.key, AES.MODE_ECB)
        return self.unpad(cipher.decrypt(enc)).decode('utf8')


if __name__ == "__main__":
    msg = '12345'
    key = '1234567812345678'

    aes = AESCipher(key)

    en = aes.encrypt(msg)  # +5Pw2/kBkkdRNoUfCFqP+A==

    print('en:', en)
    print('de:', aes.decrypt(en))

js 实现:

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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="crypto-js-3.1.9.min.js" type="text/javascript"></script>
</head>
<body>

<script>

function enAES(key, str) {
    var encrypt = CryptoJS.AES.encrypt(str, CryptoJS.enc.Utf8.parse(key), {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypt.toString();
}
function deAES(key, str) {
    var decrypt = CryptoJS.AES.decrypt(str, CryptoJS.enc.Utf8.parse(key), {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return decrypt.toString(CryptoJS.enc.Utf8);
}

var key = '1234567812345678';
var s = "12345";

var en = enAES(key, s); // +5Pw2/kBkkdRNoUfCFqP+A==

console.log(en);
console.log(deAES(key, en));

</script>

</body>
</html>

本文网址: https://pylist.com/topic/147.html 转摘请注明来源

Suggested Topics

python 解析电子书的信息

epub 书是可供人们下载的开放性资源格式的电子图书。epub 文件通常与类似亚马逊Kindle 这样的电子阅读器不兼容。...

给ssdb python 接口提速

SSDB 是个新兴的数据库,其数据库的特点简单,性能高效,有好多python 接口,个人比较后选择一个最理想的,但还有提速空间,这里仅作经验分享。...

Leave a Comment