mark下,因为公司项目服务器是用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 = '';
// 对数据分段加密
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); //二进制转十六进制
}
function rsa_decrypt($method, $key, $data, $rsa_bit = 1024) {
$data = pack('H*',$data); //十六进制字符串转二进制
$inputLen = strlen($data);
$offSet = 0;
$i = 0;
$maxDecryptBlock = $rsa_bit / 8;
$de = '';
$cache = '';
// 对数据分段解密
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进行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);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
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);//运行curl
curl_close($ch);
return $data;
}