PHP、Python、Java的AES ECB加密实现
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 对称加密AES算法 (推荐)
PHP、Python、Java、C#、Javascript 运用AES加密解密 (推荐)
Python 常用加密算法 base64, md5, sha1
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2018-05-05 05:04:48
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!
我是小白,看不懂!
看大佬的博客,不一样的气质
牛人,好多PHP代码,我都看不懂了.
哈哈 我们也是看一行,在网上查一行,凑合着看