I am currently maintaining an Alipay URL-generation library, and there are some interesting things going on in this code snippet (other than the massively confusing naming schemes and function placements)..
I have a function that builds a URL (using create_linkstring()
) + its RSA-signed (sign()
) counterpart:
function build_mysign($sort_array,$key,$sign_type) {
$prestr = create_linkstring($sort_array);
$prestr = $prestr.$key;
$mysgin = sign($prestr,$sign_type);
return $mysgin;
}
This is my create_linkstring()
method:
function create_linkstring($array) {
$arg = "";
while (list ($key, $val) = each ($array)) {
$arg.=$key."=".$val."&";
}
$arg = substr($arg,0,count($arg)-2);
return $arg;
}
This is my sign()
function:
function sign($prestr){
$fprivate = fopen(dirname(__FILE__) . '/rsa_private_key.pem', 'r');
$priv_key = fread($fprivate, 123456);
fclose($fprivate);
$privatekeyid = openssl_get_privatekey($priv_key);
// Compute signature
openssl_sign($prestr, $signMsg, $privatekeyid, OPENSSL_ALGO_SHA1);
// Free the key from memory
openssl_free_key($privatekeyid);
$signMsg = base64_encode($signMsg);
return $signMsg;
}
It basically takes an array of keys and values and generates a URL, which then gets signed using the sign()
method.
This library actually has two signing mechanisms - MD5 and RSA. I wrote the RSA-signing function, since it wasn't supported by default. Looking at the output URL of using the MD5-signing, the sign=
is a 32 char string, so it looks like this sign=779d70d2b4d9b50cad3a4ce144726e9f
.
However, using my RSA-signing function, the output is a 172 char string! The input looks like this:
&sign=WiYQIl0x+Vkey3SciP03HDv/7IZKoq2+OcvsSlQJb3NMElG6JawRc5b98ddJOOYjt9YK2YypwlFWgizj0b5wk+HNJB5lSYq7rDCcDGG0m0cKbW/m9P23J8gQaR1x6RovEDaWhs5zv4YTFe83hmPaf4Q/eVa2CpiixjpHd3kjybg=
If I am not wrong, RSA-signed strings should be 128 chars long. I'm not quite sure why that is happening. I'm not 100% if I am appending it with extraneous strings, and I notice that all the RSA-signed keys end with a =
which definitely isn't right.