php AES 加解密方法使用函数了解

来源:互联网 发布:erp软件排名 编辑:程序博客网 时间:2024/05/21 18:30

1、php中关于mcrypt加密的一些函数
1)mcrypt_get_iv_size — 返回指定算法/模式组合的初始向量大小

int mcrypt_get_iv_size ( string $cipher , string $mode )

2)mcrypt_list_algorithms – mcrypt支持的加密算法列表
3)mcrypt_list_modes() – mcrypt支持的加密模式列表
php中默认没有mcrypt扩展,检测是否支持mcrypt

$cipher_list = mcrypt_list_algorithms();//mcrypt支持的加密算法列表  $mode_list = mcrypt_list_modes();   //mcrypt支持的加密模式列表  echo '<xmp>';  print_r($cipher_list);  print_r($mode_list);

若支持,输出结果为:

Array(    [0] => cast-128    [1] => gost    [2] => rijndael-128    [3] => twofish    [4] => cast-256    [5] => loki97    [6] => rijndael-192    [7] => saferplus    [8] => wake    [9] => blowfish-compat    [10] => des    [11] => rijndael-256    [12] => serpent    [13] => xtea    [14] => blowfish    [15] => enigma    [16] => rc2    [17] => tripledes    [18] => arcfour)Array(    [0] => cbc    [1] => cfb    [2] => ctr    [3] => ecb    [4] => ncfb    [5] => nofb    [6] => ofb    [7] => stream)

其中rijndael-128,rijndael-192,rijndael-256就是AES加密,3种分别是使用不同的数据块和密钥长度进行加密
4)hash_hmac — 使用 HMAC 方法生成带有密钥的哈希值
5)hash_algos — 返回已注册的哈希算法列表

<?phpprint_r(hash_algos());?>

输出结果为:

Array(    [0] => md2    [1] => md4    [2] => md5    [3] => sha1    [4] => sha224    [5] => sha256    [6] => sha384    [7] => sha512    [8] => ripemd128    [9] => ripemd160    [10] => ripemd256    [11] => ripemd320    [12] => whirlpool    [13] => tiger128,3    [14] => tiger160,3    [15] => tiger192,3    [16] => tiger128,4    [17] => tiger160,4    [18] => tiger192,4    [19] => snefru    [20] => snefru256    [21] => gost    [22] => adler32    [23] => crc32    [24] => crc32b    [25] => salsa10    [26] => salsa20    [27] => haval128,3    [28] => haval160,3    [29] => haval192,3    [30] => haval224,3    [31] => haval256,3    [32] => haval128,4    [33] => haval160,4    [34] => haval192,4    [35] => haval224,4    [36] => haval256,4    [37] => haval128,5    [38] => haval160,5    [39] => haval192,5    [40] => haval224,5    [41] => haval256,5)

2、laravel通过mcrypt PHP 的扩展提供的AES-256加密组件

Crypt::encrypt($str);//加密Crypt::decrypt($encryptedValue);//解密

注意: 确认在 app/config/app.php 文件设置了一个32随机字符给 key 项。否则,加密的值是不安全的。
laravel中 Encrypter类中定义的一些初始变量

    protected $key;    protected $cipher = 'rijndael-256';    protected $mode = 'cbc';    protected $block = 32;    public function __construct($key)    {        $this->key = $key;    }

可设置在encrypter中使用的cipher 和 mode:

Crypt::setMode('crt');//加密模式Crypt::setCipher($cipher);//加密算法

laravel中使用AES加密示例:

$str = 'xiaoming';Crypt::setMode('ecb');Crypt::setCipher('rijndael-128');$s = Crypt::encrypt($str);echo $s;die;

结果为:

eyJpdiI6IkpjUEJKcHUyNGpmaWxRTURXXC9DN1R3PT0iLCJ2YWx1ZSI6IkZDRDNZKzQ3WGV2QVhaVkJEcXMyRzA0c3luTlE4ZGIxaTFzTzZpanhUU289IiwibWFjIjoiOTI2MDY4OGIwNGRkM2MwZWI4YzdkMTI4MDBhNmJlZDBmM2YwYmQzN2Y5ZWRhMDhiZmRjN2ZiYjYwNmEzZmI0YSJ9
0 0