AES加密php、python、java、js互通

2023-08-31  本文已影响0人  耍帅oldboy

一、python代码

import time
import hashlib

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64

class AESECB():
    def aesEncrypt(self,key, data):
        '''
        AES的ECB模式加密方法
        :param key: 密钥
        :param data:被加密字符串(明文)
        :return:密文
        '''
        key = key.encode('utf8')
        # 字符串补位
        data = pad(data.encode(),AES.block_size)
        cipher = AES.new(key, AES.MODE_ECB)
        # 加密后得到的是bytes类型的数据,使用Base64进行编码,返回byte字符串
        result = cipher.encrypt(data)
        encodestrs = base64.b64encode(result)
        enctext = encodestrs.decode('utf8')
        print(enctext)
        return enctext

    def aesDecrypt(self,key, data):
        '''

        :param key: 密钥
        :param data: 加密后的数据(密文)
        :return:明文
        '''
        key = key.encode('utf8')
        data = base64.b64decode(data)
        cipher = AES.new(key, AES.MODE_ECB)

        # 去补位
        text_decrypted = unpad(cipher.decrypt(data),AES.block_size)
        text_decrypted = text_decrypted.decode('utf8')
        print(text_decrypted)
        return text_decrypted

二、php代码

php需要注意秘钥的长度使用对应AES-128-ECB、AES-256-ECB
python可以自动根据秘钥长度识别,但是php不能

/**
 * AES加密
 * @param $data
 * @param $key
 * @return string
 */
function encryptECB($data,$key){
    $encrypted = openssl_encrypt($data, 'AES-256-ECB', $key,OPENSSL_PKCS1_PADDING);
    return base64_encode($encrypted);
}

/**
 * AES解密
 * @param $encryptedData
 * @param $key
 * @return false|string
 */
function decryptECB($encryptedData,$key){
    $decrypted = openssl_decrypt(base64_decode($encryptedData), 'AES-256-ECB', $key,OPENSSL_PKCS1_PADDING);
    return $decrypted;
}

三、js代码

import CryptoJS from "crypto-js";

var key = CryptoJS.enc.Utf8.parse("613531958ed4266724dd7e0373c72382");

// 定义要加密的明文
var plaintext = "Hello, world!";

// 加密
var ciphertext = CryptoJS.AES.encrypt(plaintext, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
});

// 输出加密后的Base64编码字符串
console.log("加密后的文本:", ciphertext.toString());

// 解密
var decryptedBytes = CryptoJS.AES.decrypt(ciphertext, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
});

// 将解密的字节数组转换为UTF-8编码的字符串
var decryptedText = decryptedBytes.toString(CryptoJS.enc.Utf8);
console.log("解密后的文本:", decryptedText);

四、java

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.security.MessageDigest;
import java.net.URLEncoder;
public class ThirdLoginExample {
    public static void main(String[] args) throws Exception {

    }

    public static String encryptAES(String plaintext, String secretKey) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decryptAES(String encryptedText, String secretKey) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }

    public static String calculateMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(input.getBytes());

            StringBuilder hexString = new StringBuilder();
            for (byte b : bytes) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读