如何将hash_hmac()与"SHA256withRSA"配合使用;在PHP上? [英] How to use hash_hmac() with "SHA256withRSA" on PHP?
问题描述
我正在尝试使PayPal Webhooks与我的PHP应用程序一起使用. 问题是它们通过标头发送的哈希算法,我必须使用该算法来验证请求是否有效.
I'm trying to get PayPal Webhooks to work with my PHP app. The problem is the hashing algorithm they send via headers, that i must use to verify if the request is valid.
当我尝试使用它时,出现此错误:
When I try to use it, I get this error:
hash_hmac(): Unknown hashing algorithm: SHA256withRSA
我仅使用"sha256"算法尝试了hash_hmac,并且有效,所以我认为问题一定出在他们希望我使用的算法上.
I have tried hash_hmac using just the "sha256" algo and it worked, so I think the problem must be with the one they want me to use.
这是我用来处理Webhook的代码:
Here is the code I use to process the Webhook:
$headers = apache_request_headers();
$body = @file_get_contents('php://input');
$json = json_decode($body);
// Concatanate the reqired strings values
$sigString = $headers['PAYPAL-TRANSMISSION-ID'].'|'.$headers['PAYPAL-TRANSMISSION-TIME'].'|'.$json->id.'|'.crc32($body);
// Get the certificate file and read the key
$pub_key = openssl_pkey_get_public(file_get_contents($headers['PAYPAL-CERT-URL']));
$keyData = openssl_pkey_get_details($pub_key);
// check signature
if ($headers['PAYPAL-TRANSMISSION-SIG'] != hash_hmac($headers['PAYPAL-AUTH-ALGO'],$sigString,$keyData['key'])) {
//invalid
}
推荐答案
这是最后起作用的代码:
Here is the code that worked in the end:
// Get the certificate file and read the key
$pubKey = openssl_pkey_get_public(file_get_contents($headers['PAYPAL-CERT-URL']));
$details = openssl_pkey_get_details($pubKey);
$verifyResult = openssl_verify($sigString, base64_decode($headers['PAYPAL-TRANSMISSION-SIG']), $details['key'], 'sha256WithRSAEncryption');
if ($verifyResult === 0) {
throw new Exception('signature incorrect');
} elseif ($verifyResult === -1) {
throw new Exception('error checking signature');
}
//rest of the code when signature is correct...
我需要对PayPal用base64_decode()
发送给我的签名进行解码,并且由于某些原因,该密钥仅在使用openssl_pkey_get_details()
I needed to decode the signature PayPal sent me with base64_decode()
and for some reason the key worked only when I used openssl_pkey_get_details()
这篇关于如何将hash_hmac()与"SHA256withRSA"配合使用;在PHP上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!