mark下妙痹,因為公司項目服務(wù)器是用Ruby寫的铸史,用的是RSA加密,就嘗試下用PHP去讀取细诸。T.T沛贪,感覺PHP寫法比iOS簡單多了。
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
</head>
<?php
function rsa_publickey_encrypt($pubk, $data) {
$pubk = openssl_get_publickey($pubk);
openssl_public_encrypt($data, $en, $pubk, OPENSSL_PKCS1_PADDING);
return $en;
}
function rsa_publickey_decrypt($pubk, $data) {
// $prik = openssl_get_privatekey($prik);
$prik = openssl_get_publickey($pubk);
// openssl_private_decrypt($data, $de, $prik, OPENSSL_PKCS1_PADDING);
openssl_public_decrypt($data, $de, $pubk,OPENSSL_PKCS1_PADDING);
return $de;
}
function rsa_encrypt($method, $key, $data, $rsa_bit = 1024) {
$inputLen = strlen($data);
$offSet = 0;
$i = 0;
$maxDecryptBlock = $rsa_bit / 8 - 11;
$en = '';
// 對數(shù)據(jù)分段加密
while ($inputLen - $offSet > 0) {
if ($inputLen - $offSet > $maxDecryptBlock) {
$cache = $method($key, substr($data, $offSet, $maxDecryptBlock));
} else {
$cache = $method($key, substr($data, $offSet, $inputLen - $offSet));
}
$en = $en . $cache;
$i++;
$offSet = $i * $maxDecryptBlock;
}
return bin2hex($en); //二進(jìn)制轉(zhuǎn)十六進(jìn)制
}
function rsa_decrypt($method, $key, $data, $rsa_bit = 1024) {
$data = pack('H*',$data); //十六進(jìn)制字符串轉(zhuǎn)二進(jìn)制
$inputLen = strlen($data);
$offSet = 0;
$i = 0;
$maxDecryptBlock = $rsa_bit / 8;
$de = '';
$cache = '';
// 對數(shù)據(jù)分段解密
while ($inputLen - $offSet > 0) {
if ($inputLen - $offSet > $maxDecryptBlock) {
$cache = $method($key, substr($data, $offSet, $maxDecryptBlock));
} else {
$cache = $method($key, substr($data, $offSet, $inputLen - $offSet));
}
$de = $de . $cache;
$i = $i + 1;
$offSet = $i * $maxDecryptBlock;
}
return $de;
}
$pubk = '-----BEGIN PUBLIC KEY-----
xxx
-----END PUBLIC KEY-----';
$url = 'http://xxx.com/login';
$post_data['name'] = 'admin';
$post_data['pwd'] = 'admin';
$o = "";
foreach ( $post_data as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
$post_data = rsa_encrypt('rsa_publickey_encrypt', $pubk, $post_data);
echo 'post_data='.$post_data.'</br>';
$res = request_post($url, $post_data);
$de = rsa_decrypt('rsa_publickey_decrypt', $pubk, $res);
echo "de=".$de.'</br>';
/**
* 模擬post進(jìn)行url請求
* @param string $url
* @param string $param
*/
function request_post($url = '', $param = '') {
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
$ch = curl_init();//初始化curl
curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定網(wǎng)頁
curl_setopt($ch, CURLOPT_HEADER, 0);//設(shè)置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結(jié)果為字符串且輸出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$headers = array();
$headers[] = 'X-ANFAN-PRODUCTID: 2';
$headers[] = 'X-ANFAN-RETAILER: 1';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);//運(yùn)行curl
curl_close($ch);
return $data;
}