AES/ECB/PKCS7Padding 加解密 java 和 python 版本

java版

依赖

先添加maven依赖

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.56</version>
</dependency>
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>

代码

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;

/**
 * @Description
 * @Auther sty
 * @createTime 2020-02-26 17:28
 */
public class AESUtil {
    private static final String EncryptAlg ="AES";

    private static final String Cipher_Mode="AES/ECB/PKCS7Padding";

    private static final String Encode="UTF-8";

    private static final String PASSWORD="www.toocruel.net";

    public static String encode(String content) throws Exception {
        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

            byte[] raw = PASSWORD.getBytes(Encode);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, EncryptAlg);
            Cipher cipher = Cipher.getInstance(Cipher_Mode);//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

            byte[] data=cipher.doFinal(content.getBytes(Encode));
            String result= Base64.encodeBase64String(data);
            return result;
        } catch (Exception e) {
            throw new Exception("AES加密失败:"+e.getMessage(),e);
        }
    }

    public static String decode(String content) throws Exception {
        try {
            byte[] raw = PASSWORD.getBytes(Encode);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, EncryptAlg);
            Cipher cipher = Cipher.getInstance(Cipher_Mode);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(content);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,Encode);
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception e) {
            throw new Exception("AES解密失败:" +e.getMessage(),e);
        }
    }



    public static void main(String[] args) throws Exception {
        String content = "toocruel.net";
        String encode = encode(content);

        System.out.println("加密前:"+content);
        System.out.println("加密后:"+ encode);
        System.out.println("解密后:"+decode(encode));


    }

}

运行结果

加密前:toocruel.net
加密后:4whX3MkQzaR44cJ9R9qHvA==
解密后:toocruel.net

python版

依赖

先安装依赖组件

sudo pip install cryptography
sudo pip install pycrypto

代码

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import base64
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import algorithms

class AESUtil(object):


    PASSWORD = 'www.toocruel.net'
    ENCODING = 'UTF-8'

    @staticmethod
    def pkcs7_padding(data):
        if not isinstance(data, bytes):
            data = data.encode()

        padder = padding.PKCS7(algorithms.AES.block_size).padder()

        padded_data = padder.update(data) + padder.finalize()

        return padded_data

    @staticmethod
    def encrypt(text):
        key = AESUtil.PASSWORD.encode(AESUtil.ENCODING)
        mode = AES.MODE_ECB
        text = AESUtil.pkcs7_padding(text)
        cryptos = AES.new(key, mode)

        cipher_text = cryptos.encrypt(text)
        return base64.encodestring(cipher_text).rstrip("\x01"). \
            rstrip("\x02").rstrip("\x03").rstrip("\x04").rstrip("\x05"). \
            rstrip("\x06").rstrip("\x07").rstrip("\x08").rstrip("\x09"). \
            rstrip("\x0a").rstrip("\x0b").rstrip("\x0c").rstrip("\x0d"). \
            rstrip("\x0e").rstrip("\x0f").rstrip("\x10")

    @staticmethod
    def decrypt(text):
        key = AESUtil.PASSWORD.encode(AESUtil.ENCODING)
        mode = AES.MODE_ECB
        cryptor = AES.new(key, mode)
        encodeBytes = cryptor.decrypt(base64.decodestring(text))
        return bytes.decode(encodeBytes).encode(AESUtil.ENCODING).rstrip("\x01"). \
            rstrip("\x02").rstrip("\x03").rstrip("\x04").rstrip("\x05"). \
            rstrip("\x06").rstrip("\x07").rstrip("\x08").rstrip("\x09"). \
            rstrip("\x0a").rstrip("\x0b").rstrip("\x0c").rstrip("\x0d"). \
            rstrip("\x0e").rstrip("\x0f").rstrip("\x10")


if __name__ == '__main__':
    content = 'toocruel.net'
    encoded = AESUtil.encrypt(content)
    decoded = AESUtil.decrypt(encoded)
    print("orgin:", content)
    print("encoded:", encoded)
    print("decoded:", decoded)

运行结果

('orgin:', 'toocruel.net')
('encoded:', '4whX3MkQzaR44cJ9R9qHvA==')
('decoded:', 'toocruel.net')

验证

WX20200226-190825

(全文完)

(转载本站文章请注明作者和出处 AES/ECB/PKCS7Padding 加解密 java 和 python 版本