php 加密示例与说明
PHP加密
$param = array("test"=>"4564654564564564564","word"=>"CCC001");
$url = "http://XXXXXXXX.cc/getList";
$key = "jfdiiek08fdsf9+DW";
$data = encrypt(json_encode($param),$key);
$post = array("data"=>$data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1); //设置为POST方式
curl_setopt($ch, CURLOPT_URL, $url); //设置链接
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //POST数据
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设置是否返回信息
curl_setopt($ch, CURLOPT_HEADER, 0); //设置HTTP头
$response = curl_exec($ch); //接收返回信息
curl_close($ch); //关闭curl链接
$rcv = decrypt(json_decode($response)->data,$key); // 解析返回信息
function pkcs5Pad($text) {
$cipher = MCRYPT_RIJNDAEL_128;
$modes = MCRYPT_MODE_ECB;
$blocksize = mcrypt_get_block_size ( $cipher, $modes );
$pad = $blocksize - (strlen ( $text ) % $blocksize);
return $text . str_repeat ( chr ( $pad ), $pad );
}
function pkcs5Unpad($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);
}
// 报文加密
function encrypt($str,$key) {
$cipher = MCRYPT_RIJNDAEL_128; //加密类型
$mode = MCRYPT_MODE_ECB; //加密模式
$str_encrypt = mcrypt_encrypt($cipher,$key,pkcs5Pad($str),$mode);
return base64_encode($str_encrypt);
}
// 报文解密
function decrypt($str,$key) {
$cipher = MCRYPT_RIJNDAEL_128; //加密类型
$mode = MCRYPT_MODE_ECB; //加密模式
$str = base64_decode($str);
$str_decrypt = mcrypt_decrypt($cipher,$key,$str,$mode);
return $str_decrypt;
}
Java加密示例
String url = "http://XXXXXXX.cc/getList";
String key = "fjdklsj8989djjfd+DW";
Map<String,String> data = new HashMap<String,String>();
data.put("test", "4564654564564564564");
data.put("word", "CCC001");
JSONArray json = JSONArray.fromObject(data);
String data = json.get(0).toString().trim();
// 加密
data = aesEncrypt(data,key);
// POST
Map<String,String> param = new HashMap<String,String>();
param.put("data", data);
String rst = Post(url, param);
// 解析返回信息
JSONObject o = JSONObject.fromObject(rst);
String s = (String)o.get("data");
// 解密
System.out.println(aesDecrypt(s,key));
public String aesEncrypt(String message, String key) {
try {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"),"AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] r = cipher.doFinal(message.getBytes("UTF-8"));
return Base64.encodeBase64String(r);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String aesDecrypt(String message, String key) {
try {
byte[] bytesrc = Base64.decodeBase64(message);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"),"AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte,"utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}