概述
AES (Advanced Encryption Standard), 是一种很常见的对称加密算法,通信双方保存一致的私钥,来完成加密解密。 Web开发中,通常被用于加密传输密码等重要信息。
通信原理:
加密原理:
AES 算法有几个基本概念:
- 秘钥 :如上面图中的 “私钥” 通信双方需要使用同一个 秘钥, AES 支持3种长度的秘钥:
- 128位(AES18) 安全性低,效率高
- 192位(AES192)
- 256位(AES256) 安全性最高,效率低
-
填充 :对于密文的加密,并非一次性处理,而是拆分成一个个独立的、大小一致的块(128bit)来处理,如果不足 128bit 的时候,就需要进行填充。因此,如果使用了填充方式,那么就必须保证接收方在解密的时候使用同样的填充方式。
- 模式 : 主要作用于将文明块加密成密文块的过程中,同样的,通信双方需要保持一致的模式。
- CBC : 电码本模式
- ECB : 密码分组链接模式
- CTR : 计算器模式
- CFB : 密码反馈模式
- OFB : 输出反馈模式
PHP 中的 AES
<?php
class CryptAES
{
/*秘钥长度*/
protected $cipher = MCRYPT_RIJNDAEL_128;
/*模式*/
protected $mode = MCRYPT_MODE_ECB;
/*填充方式*/
protected $pad_method = NULL;
/*指定秘钥*/
protected $secret_key = '';
/*向量*/
protected $iv = '';
public function set_cipher($cipher)
{
$this->cipher = $cipher;
}
public function set_mode($mode)
{
$this->mode = $mode;
}
public function set_iv($iv)
{
$this->iv = $iv;
}
public function set_key($key)
{
$this->secret_key = $key;
}
public function require_pkcs5()
{
$this->pad_method = 'pkcs5';
}
protected function pad_or_unpad($str, $ext)
{
if (is_null($this->pad_method)) {
return $str;
} else {
$func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
if (is_callable($func_name)) {
$size = mcrypt_get_block_size($this->cipher, $this->mode);
return call_user_func($func_name, $str, $size);
}
}
return $str;
}
protected function pad($str)
{
return $this->pad_or_unpad($str, '');
}
protected function unpad($str)
{
return $this->pad_or_unpad($str, 'un');
}
public function encrypt($str)
{
$str = $this->pad($str);
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');
if (empty($this->iv)) {
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
} else {
$iv = $this->iv;
}
mcrypt_generic_init($td, $this->secret_key, $iv);
$cyper_text = mcrypt_generic($td, $str);
$rt = base64_encode($cyper_text);
//$rt = bin2hex($cyper_text);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $rt;
}
public function decrypt($str)
{
$td = mcrypt_module_open($this->cipher, '', $this->mode, '');
if (empty($this->iv)) {
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
} else {
$iv = $this->iv;
}
mcrypt_generic_init($td, $this->secret_key, $iv);
//$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
$decrypted_text = mdecrypt_generic($td, base64_decode($str));
$rt = $decrypted_text;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $this->unpad($rt);
}
public static function hex2bin($hexdata)
{
$bindata = '';
$length = strlen($hexdata);
for ($i = 0; $i < $length; $i += 2) {
$bindata .= chr(hexdec(substr($hexdata, $i, 2)));
}
return $bindata;
}
/**
* PKCS5Padding:填充的原则是,如果长度少于16个字节,需要补满16个字节,补(16-len)个(16-len)例如:
* huguozhen这个节符串是9个字节,16-9= 7,补满后如:huguozhen+7个十进制的7
* @param $text
* @param $blocksize
* @return string
*/
public static function pkcs5_pad($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
public static function pkcs5_unpad($text)
{
$pad = ord($text{strlen($text) - 1});
if ($pad > strlen($text)) return false;
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
return substr($text, 0, -1 * $pad);
}
}
$keyStr = 'UITN25LMUQC436IZ';
$plainText = 'hello world!';
$aes = new CryptAES();
$aes->set_key($keyStr);
$aes->require_pkcs5();
$encText = $aes->encrypt($plainText);
$decString = $aes->decrypt($encText);
echo $encText, "\n", $decString;
结果:
phZJZRBoK9O+HVDDFlGCaw==
hello world!
Java 中的 AES
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
//需要去下载该jar包 http://mirrors.hust.edu.cn/apache//commons/codec/binaries/commons-codec-1.11-bin.zip
import org.apache.commons.codec.binary.Base64;
public class Security {
private static final String AESTYPE ="AES/ECB/PKCS5Padding";
public static String AES_Encrypt(String keyStr, String plainText) {
byte[] encrypt = null;
try{
Key key = generateKey(keyStr);
Cipher cipher = Cipher.getInstance(AESTYPE);
cipher.init(Cipher.ENCRYPT_MODE, key);
encrypt = cipher.doFinal(plainText.getBytes());
}catch(Exception e){
e.printStackTrace();
}
return new String(Base64.encodeBase64(encrypt));
}
public static String AES_Decrypt(String keyStr, String encryptData) {
byte[] decrypt = null;
try{
Key key = generateKey(keyStr);
Cipher cipher = Cipher.getInstance(AESTYPE);
cipher.init(Cipher.DECRYPT_MODE, key);
decrypt = cipher.doFinal(Base64.decodeBase64(encryptData));
}catch(Exception e){
e.printStackTrace();
}
return new String(decrypt).trim();
}
private static Key generateKey(String key)throws Exception{
try{
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
return keySpec;
}catch(Exception e){
e.printStackTrace();
throw e;
}
}
//测试
public static void main(String[] args) {
//加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式,key需要为16位
String keyStr = "UITN25LMUQC436IZ";
String plainText = "hello world!";
String encText = AES_Encrypt(keyStr, plainText);
String decString = AES_Decrypt(keyStr, encText);
System.out.println(encText); //phZJZRBoK9O+HVDDFlGCaw==
System.out.println(decString); //hello world!
}
}