forked from alipay/global-open-sdk-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SignatureTool.php
46 lines (38 loc) · 2 KB
/
SignatureTool.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
class SignatureTool{
static public function sign($httpMethod, $path, $clientId, $reqTime, $content, $merchantPrivateKey){
$signContent = self::genSignContent($httpMethod, $path, $clientId, $reqTime, $content);
$signValue = self::signWithSHA256RSA($signContent, $merchantPrivateKey);
return urlencode($signValue);
}
static public function verify($httpMethod, $path, $clientId, $rspTime, $rspBody, $signature, $alipayPublicKey){
$rspContent = self::genSignContent($httpMethod, $path, $clientId, $rspTime, $rspBody);
return self::verifySignatureWithSHA256RSA($rspContent, $signature, $alipayPublicKey);
}
static private function genSignContent($httpMethod, $path, $clientId, $timeString, $content){
$payload = $httpMethod . " " . $path . "\n" . $clientId . "." . $timeString . "." . $content;
return $payload;
}
static private function signWithSHA256RSA($signContent, $merchantPrivateKey){
$priKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
wordwrap($merchantPrivateKey, 64, "\n", true) .
"\n-----END RSA PRIVATE KEY-----";
openssl_sign($signContent, $signValue, $priKey, OPENSSL_ALGO_SHA256);
return base64_encode($signValue);
}
static private function verifySignatureWithSHA256RSA($rspContent, $rspSignValue, $alipayPublicKey){
$pubKey = "-----BEGIN PUBLIC KEY-----\n" .
wordwrap($alipayPublicKey, 64, "\n", true) .
"\n-----END PUBLIC KEY-----";
if(strstr($rspSignValue, "=")
|| strstr($rspSignValue, "+")
|| strstr($rspSignValue, "/")
|| $rspSignValue == base64_encode(base64_decode($rspSignValue))){
$originalRspSignValue = base64_decode($rspSignValue);
} else {
$originalRspSignValue = base64_decode(urldecode($rspSignValue));
}
$verifyResult = openssl_verify($rspContent, $originalRspSignValue, $pubKey, OPENSSL_ALGO_SHA256);
return $verifyResult;
}
}