前提说明
对接口的业务数据进行AES-128-CBC-PKCS5Padding
加密,然后做 Base64编码将得到的最终字符串
特别注意
在废弃的 mcrypt加密库中,128实际上指的是块大小而不是密钥大小
但是在 openssl 中的 aes-128-cbc 的128 指的是密钥大小
也就是说,在使用有效的256位密钥时,它们都是aes-256,而如果要把 mcrypt 转为 openssl 的加密方式, mcrypt 的128 需要写成 openssl 的 256
java的 aes-128-cbc , 在php中要写成 aes-256-cbc
java 代码
package xmb.util;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.alibaba.fastjson.JSONObject;
import ncd.comm.tools.StringUtil;
import org.apache.commons.codec.binary.Base64;
public class AESUtil {
// mode_key:Cipher
private static final Map<String, Cipher> CIPHERMAP_MAP = new HashMap<String, Cipher>();
// constants
private static final String DEFAULT_CHARSET = "utf-8";
private static final String ALGORITHM_NAME = "AES";
private static final String ALGORITHM_STR = ALGORITHM_NAME + "/CBC/PKCS5Padding";
private static final String IV = "1234567890123456";
/**
* get cipher
*
* @param mode
* @param key
* @param charset
* @return
* @throws Exception
*/
private static Cipher getCipher(int mode, String key, String charset) throws Exception {
Cipher cipher = CIPHERMAP_MAP.get(mode + "_" + key);
if (cipher != null) {
return cipher;
}
// secretKeySpec
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(charset), ALGORITHM_NAME);
// ivParameterSpec
IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes(charset));
// cipher
cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(mode, secretKeySpec, ivParameterSpec);
// return
CIPHERMAP_MAP.put(mode + "_" + key, cipher);
return cipher;
}
public static String encrypt(String a, String key, String charset) throws Exception {
Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, key, charset);
byte[] resultByte = cipher.doFinal(a.getBytes(charset));
return base64BytesToString(resultByte, charset);
}
public static String encrypt(String a, String key) throws Exception {
return encrypt(a, key, DEFAULT_CHARSET);
}
public static String decrypt(String a, String key, String charset) throws Exception {
Cipher cipher = getCipher(Cipher.DECRYPT_MODE, key, charset);
byte[] inputByte = base64stringToBytes(a, charset);
byte[] resultByte = cipher.doFinal(inputByte);
return new String(resultByte, charset);
}
public static String decrypt(String a, String key) throws Exception {
return decrypt(a, key, DEFAULT_CHARSET);
}
private static String base64BytesToString(byte[] bytes, String charset) throws Exception {
return new String(Base64.encodeBase64(bytes), charset);
}
private static byte[] base64stringToBytes(String string, String charset) throws Exception {
return Base64.decodeBase64(string.getBytes(charset));
}
/**
* 解析参数并转成json返回
* @param paramsStr 加密参数
* @param paramsKey 签名key
* @return 返回json对象结果
*/
public static JSONObject decryptToJsonObject(String paramsStr, String paramsKey) throws Exception {
String params = decrypt(paramsStr, paramsKey);
if (!StringUtil.isEmpty(params)) {
return JSONObject.parseObject(params);
}
return null;
}
public static void main(String[] args) throws Exception {
String a = "123456";
System.out.println(encrypt(a,"vyhnYtwnHExqxbj6kGvjhpl6QQXS6Y13"));
}
}
php 对应代码
$key = "vyhnYtwnHExqxbj6kGvjhpl6QQXS6Y13";
$txt = "123456";
$options = OPENSSL_RAW_DATA;
$iv = "1234567890123456";
// 加密
function encrypt($input, $key, $iv){
return base64_encode(openssl_encrypt($input, 'AES-256-CBC', $key, OPENSSL_RAW_DATA,$iv));
}
// 解密
function decrypt($input, $key, $iv){
return openssl_decrypt(base64_decode($input), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
}
$str = '123456';
echo "加密结果: ".encrypt($str, $key, $iv);
$encrypt = '6H5HIbnvlq/7fnhNNNw6yg==';
echo "解密结果: ".decrypt($encrypt, $key, $iv);
AES/ECB/PKCS5Padding 格式加密php7 类
<?php
namespace vendor\aes;
/**
* 用于对接 java的aes AES/ECB/PKCS5Padding 格式加密
* Class Security
*/
class Security {
/**
* PHP7 AES 加密
* @param string $str 需要加密的字符串
* @param string $key 密钥
* @param string $type 加密类型。支持base64_encode、bin2hex等
* @return bool|string
*/
public static function ssl_encrypt($str, $key, $type='base64_decode') {
$encrypt = openssl_encrypt($str, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
return call_user_func($type, $encrypt);
}
/**
* PHP7 AES 解密
* @param string $str 需要解密的字符串
* @param string $key 密钥
* @param string $type 解密类型,支持base64_decode、hex2bin等
* @return bool|string
*/
public static function ssl_decrypt($str, $key, $type='base64_decode') {
$decrypt = call_user_func($type, $str);
return openssl_decrypt($decrypt, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
}
}
一套完整的不同语言相互转换的AES加密解密
php版本 <= 7.0
namespace App\Libraries\AES;
class AES{
public $key;
public function __construct($_key = '')
{
$this->key = $_key;
}
//AES 加密 ECB 模式
public function AESencode($_values)
{
$data = null;
try{
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$_values = $this->pkcs5_pad($_values, $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, $_values);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$data = base64_encode($data);
}
catch(\Exception $e){
}
return $data;
}
//AES 解密 ECB 模式
public function AESdecode($_values)
{
$data = null;
try{
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->key, base64_decode($_values), MCRYPT_MODE_ECB);
$dec_s = strlen($decrypted);
$padding = ord($decrypted[$dec_s - 1]);
$data = substr($decrypted, 0, -$padding);
}
catch(\Exception $e){
}
return $data;
}
public function pkcs5_pad ($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text. str_repeat(chr($pad), $pad);
}
}
PHP版本>=7.1
namespace App\Libraries\AES;
class AES{
public $key;
public function __construct($_key = '')
{
$this->key = $_key;
}
//AES 加密 ECB 模式
public function AESencode($_values)
{
Try{
$data = openssl_encrypt($_values, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
$data = base64_encode($data);
}
Catch (\Exception $e){
}
return $data;
}
//AES 解密 ECB 模式
public function AESdecode($_values)
{
$data = null;
Try{
$data = openssl_decrypt(base64_decode($_values), 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
}
Catch (Exception $e) {
}
return $data;
}
}
Java
public static String aesEncrypt(String dataString, String appKey) throws Exception {
Base64.Encoder encoder = Base64.getEncoder();
SecretKeySpec keySpec = new SecretKeySpec(appKey.getBytes(), 'AES');
Cipher cipher = Cipher.getInstance('AES/ECB/PKCS5Padding');
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return encoder.encodeToString(cipher.doFinal(dataString.getBytes('UTF-8')));
}
public static String aesDecrypt(String dataString, String appKey) throws Exception {
Base64.Decoder decoder = Base64.getDecoder();
SecretKeySpec keySpec = new SecretKeySpec(appKey.getBytes(), 'AES');
Cipher cipher = Cipher.getInstance('AES/ECB/PKCS5Padding');
cipher.init(Cipher.DECRYPT_MODE, keySpec);
return new String(cipher.doFinal(decoder.decode(dataString)));
}
C#
public static string AesEncrypt(string str, string key)
{
if (string.IsNullOrEmpty(str)) return null;
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = System.Security.Cryptography.CipherMode.ECB,
Padding = System.Security.Cryptography.PaddingMode.PKCS7,
};
System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string AesDecrypt(string str, string key)
{
if (string.IsNullOrEmpty(str)) return null;
Byte[] toEncryptArray = Convert.FromBase64String(str);
System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = System.Security.Cryptography.CipherMode.ECB, Padding = System.Security.Cryptography.PaddingMode.PKCS7
};
System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Encoding.UTF8.GetString(resultArray);
}
参考文档: https://www.jianshu.com/p/ae1f955e7a75
加密解密在线工具: http://tool.chacuo.net/cryptaes/