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

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

python 实现:

# -*- 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 实现:

<!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>
Relative Articles