1. 程式人生 > >AES ECB加密實現(java/php/python)

AES ECB加密實現(java/php/python)

這裡做個一個加密實現的記錄,方便以後查詢

AES加密 ECB模式 PKCS5填充 128位密碼/密碼塊
ECB模式是將明文按照固定大小的塊進行加密的,塊大小不足則進行填充。ECB模式沒有用到向量。

python 實現

# -*- coding=utf-8-*-

from Crypto.Cipher import AES
import os
from Crypto import Random
import base64

"""
aes加密演算法
padding : PKCS5
"""

class AESUtil:

    __BLOCK_SIZE_16 = BLOCK_SIZE_16 = AES.block_size

    @staticmethod
def encryt(str, key): cipher = AES.new(key, AES.MODE_ECB) x = AESUtil.__BLOCK_SIZE_16 - (len(str) % AESUtil.__BLOCK_SIZE_16) if x != 0: str = str + chr(x)*x msg = cipher.encrypt(str) msg = base64.urlsafe_b64encode(msg).replace('=', '') return
msg @staticmethod def decrypt(enStr, key): cipher = AES.new(key, AES.MODE_ECB) enStr += (len(enStr) % 4)*"=" decryptByts = base64.urlsafe_b64decode(enStr) msg = cipher.decrypt(decryptByts) paddingLen = ord(msg[len(msg)-1]) return msg[0:-paddingLen] if
__name__ == "__main__": print AESUtil.encryt("512345", "1234567812345678") print AESUtil.decrypt("1MbqzdK0IzP8vchDgRlzvw", "1234567812345678")

PHP實現

class AES {

    var $key = "1234567812345678";

    public function __set($key, $value){
        $this->$key = $value;
    }

    public function __get($key) {
        return $this->$key;
    }

    public function encrypt($input) {
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = $this->pkcs5_pad($input, $size);
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $this->key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = $this->base64url_encode($data);
        return $data;
    }

    private function pkcs5_pad ($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    function strToHex($string)   
    {   
        $hex="";   
        for   ($i=0;$i<strlen($string);$i++)   
        $hex.=dechex(ord($string[$i]));   
        $hex=strtoupper($hex);   
        return   $hex;   
    }   
    function hexToStr($hex)   
    {   
        $string="";   
        for   ($i=0;$i<strlen($hex)-1;$i+=2)   
        $string.=chr(hexdec($hex[$i].$hex[$i+1]));   
        return   $string;   
    }

    public function decrypt($sStr) {
        $decrypted= mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128,
            //$sKey,
            $this->key,
            //base64_decode($sStr),
            $this->base64url_decode($sStr),
            //$sStr,
            MCRYPT_MODE_ECB
        );
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }
    /**
     *url 安全的base64編碼 sunlonglong
     */
    function base64url_encode($data) { 
      return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
    } 
    /**
     *url 安全的base64解碼 sunlonglong
     */
    function base64url_decode($data) { 
      return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); 
    }   
}

使用示例

$aes = new AES();

//設定金鑰
$aes->__set("key", "1234567812345678");

echo $aes->encrypt("123");
echo "\r\n";
echo $aes->decrypt("q7eZEivlY5ra7BUPzoF9vg");

java實現

public class SecureUtils {

    public static String decryptByAes(String sSrc, String reqKey) {
        try {
            byte[] raw;
            if (reqKey != null) {
                raw = reqKey[0].getBytes("ASCII");
            } else {
                raw = sKey.getBytes("ASCII");
            }

            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = decryptUrlSafe(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original);
                return originalString;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    public static String encryptByAes(String sSrc, String...reqKey) throws Exception {
        byte[] raw;
        if (reqKey != null) {
            raw = reqKey[0].getBytes("ASCII");
        } else {
            raw = sKey.getBytes("ASCII");
        }
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());
        return encryptUrlSalf(encrypted);
    }

    public static byte[] decryptUrlSafe(String key) throws Exception {
        String decodeStr = key.replaceAll("-", "+").replaceAll("_", "/");
        String qualsStr = "";
        for (int i = 0; i < key.length() % 4; i++) {
            qualsStr += "=";
        }
        return Base64.decode(decodeStr + qualsStr);
    }

    public static String encryptUrlSalf(byte[] key) {
        String str = Base64.encode(key);
        str = str.replaceAll("\\+", "-").replaceAll("/", "_").replaceAll("=+$", "");
        return str;
    }

}