AES加密 ECB模式 PKCS5填充 128位密码/密码块 

ECB模式是将明文按照固定大小的块进行加密的,块大小不足则进行填充,ECB模式没有用到向量。

具体加密算法,请参见米扑博客总结的系列文章:AES、DES、RSA三种典型加密算法

 

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)); 
    }   
}

PHP 使用示例:

$aes = new AES();

// 设置密钥
$aes->__set("key", "1234567812345678");

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

 

 

Python 实现

需要下载安装 pycrypto:https://pypi.python.org/pypi/pycrypto

官网介绍:This is a collection of both secure hash functions (such as SHA256 and RIPEMD160), and various encryption algorithms (AES, DES, RSA, ElGamal, etc.)

官网示例

An example usage of the SHA256 module is:

>>> from Crypto.Hash import SHA256
>>> hash = SHA256.new()
>>> hash.update('message')
>>> hash.digest()
'\xabS\n\x13\xe4Y\x14\x98+y\xf9\xb7\xe3\xfb\xa9\x94\xcf\xd1\xf3\xfb"\xf7\x1c\xea\x1a\xfb\xf0+F\x0cm\x1d'

An example usage of an encryption algorithm (AES, in this case) is:

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'

One possible application of the modules is writing secure administration tools. Another application is in writing daemons and servers. Clients and servers can encrypt the data being exchanged and mutually authenticate themselves; daemons can encrypt private data for added security. Python also provides a pleasant framework for prototyping and experimentation with cryptographic algorithms; thanks to its arbitrary-length integers, public key algorithms are easily implemented.

As of PyCrypto 2.1.0, PyCrypto provides an easy-to-use random number generator:

>>> from Crypto import Random
>>> rndfile = Random.new()
>>> rndfile.read(16)
'\xf7.\x838{\x85\xa0\xd3>#}\xc6\xc2jJU'

A stronger version of Python’s standard “random” module is also provided:

>>> from Crypto.Random import random
>>> random.choice(['dogs', 'cats', 'bears'])
'bears'

Caveat: For the random number generator to work correctly, you must call Random.atfork() in both the parent and child processes after using os.fork()

 

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")

 

 

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;
    }
}

 

 

 

参考推荐

php 加密算法md5, sha1

PHP 对称加密AES算法 (推荐

PHP 更安全的加密机制 Bcrypt

PHP、Python、Java、C#、Javascript 运用AES加密解密 (推荐

Python 常用加密算法 base64, md5, sha1

Python中Base64编码和解码

AES、DES、RSA三种典型加密算法

AES 加密算法的详细介绍与实现

PHP 使用cookie实现记住登录状态

PHP Session与Cookie详解

公钥,私钥,数字签名的通俗理解