首先贴一下java的算法:
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* @version V1.0
* @desc AES 加密工具类
*/
public class AESUtil {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final String KEY = "KE0yS1GcqQ823TatPYMLbwOmu7NZXHJI";
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
/**
* AES 加密操作
*
* @param content 待加密内容
* @param password 加密密码
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content, String password) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
byte[] byteContent = content.getBytes(DEFAULT_CHARSET);
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);// 加密
return parseByte2HexStr(result);//通过hex转码返回
} catch (Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* AES 解密操作
*
* @param content
* @param password
* @return
*/
public static String decrypt(String content, String password) {
try {
//实例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
//执行操作
byte[] result = cipher.doFinal(parseHexStr2Byte(content));
return new String(result, DEFAULT_CHARSET);
} catch (Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* 生成加密秘钥
*
* @return
*/
private static SecretKeySpec getSecretKey(final String password) {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
secureRandom.setSeed(password.getBytes());
//AES 要求密钥长度为 128
// kg.init(128, new SecureRandom(password.getBytes()));
kg.init(128, secureRandom);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
//System.out.println(secretKey);
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static void main(String[] args) {
String content = "idaddy0000000001KE0yS1GcqQ823TatPYMLbwOmu7NZXHJI111111";
System.out.println("加密前:" + content);
String encrypt = AESUtil.encrypt(content, KEY);
System.out.println("加密后:" + encrypt);
System.out.println("解密后:"+AESUtil.decrypt(encrypt, KEY));
}
}
结果:
加密前:123abc
加密后:ED4FFA53B4F3AE8277DEB8A4D313508E
解密后:123abc
++++++++++++++++++++++++++++++++++++++++++++++
下面贴PHP的加解密算法:[高版本]
class Aes
{
public $key = '';
public $iv = '';
public function __construct($config)
{
foreach($config as $k => $v){
$this->$k = $v;
}
}
//加密
public function aesEn($data){
return base64_encode(openssl_encrypt($data, $this->method,$this->key, OPENSSL_RAW_DATA , $this->iv));
}
//解密
public function aesDe($data){
return openssl_decrypt(base64_decode($data), $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
}
public function decode($data) {
$secret= 'xxxxx';
$key= substr(openssl_digest(openssl_digest($secret,'sha1',true),'sha1',true),0,16);
$encrypted= base64_decode($data);
$result= openssl_decrypt($encrypted,'aes-128-ecb', $key,OPENSSL_RAW_DATA);
return $result;
}
}
$config = [
'key' => 'reter4446fdfgdfgdfg', //加密key
'iv' => md5(time(). uniqid(),true), //保证偏移量为16位
'method' => 'AES-128-CBC' //加密方式 # AES-256-CBC等
];
$obj = new Aes($config);
$res = $obj->aesEn('aaaddee44');//加密数据
echo $res;
echo '<hr>';
echo $obj->aesDe($res);
PHP低版本【5.6】
class AES {
//PKCS5Padding 补码方式
private function _pkcs5Pad($text, $blockSize) {
$pad = $blockSize - (strlen($text) % $blockSize);
return $text . str_repeat(chr($pad), $pad);
}
private function _pkcs5Unpad($text) {
$end = substr($text, -1);
$last = ord($end);
$len = strlen($text) - $last;
if(substr($text, $len) == str_repeat($end, $last)) {
return substr($text, 0, $len);
}
return false;
}
//加密
public function encrypt($encrypt, $key) {
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$paddedData = $this->_pkcs5Pad($encrypt, $blockSize);
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
$key2 = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true),0,16);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key2, $paddedData, MCRYPT_MODE_ECB, $iv);
return base64_encode($encrypted);
}
//解密
public function decrypt($decrypt, $key) {
$decoded = base64_decode($decrypt);
$blockSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($blockSize, MCRYPT_RAND);
$key2 = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key2, $decoded, MCRYPT_MODE_ECB, $iv);
return $this->_pkcs5Unpad($decrypted);
}
}