doudizhu2222 2015-05-11 08:22
浏览 909
已采纳

如何在PHP上使用hash_hmac()和“SHA256withRSA”?

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

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.

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
}
  • 写回答

2条回答 默认 最新

  • dongrong1856 2015-06-01 12:28
    关注

    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...
    

    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()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 代写uni代码,app唤醒
  • ¥15 全志t113i启动qt应用程序提示internal error
  • ¥15 ensp可以看看嘛.
  • ¥80 51单片机C语言代码解决单片机为AT89C52是清翔单片机
  • ¥60 优博讯DT50高通安卓11系统刷完机自动进去fastboot模式
  • ¥15 minist数字识别
  • ¥15 在安装gym库的pygame时遇到问题,不知道如何解决
  • ¥20 uniapp中的webview 使用的是本地的vue页面,在模拟器上显示无法打开
  • ¥15 网上下载的3DMAX模型,不显示贴图怎么办
  • ¥15 关于#stm32#的问题:寻找一块开发版,作为智能化割草机的控制模块和树莓派主板相连,要求:最低可控制 3 个电机(两个驱动电机,1 个割草电机),其次可以与树莓派主板相连电机照片如下: