Libsodium解密返回空响应

时间:2019-06-14 15:19:38

标签: php laravel libsodium aes-gcm

我无法让Libsodium解密我从Webhook收到的响应,但是openssl_decrypt可以。我没有收到错误,但结果一直是空白,这意味着我必须做错了什么。

我想通过OpenSSL使用Libsodium的原因是它更可靠。在高流量的情况下,openssl_decrypt变得非常不可靠。

这是我的代码:

public function webhook(Request $request) {

    $psp = new Psp();
    $transaction_state = new \stdClass();
    $transaction_state->state = 'Live';

    $key_from_configuration = 'B46FAC78301751BCB489AC6D878877CA9AD8A71278DA777DD91B1AAB82135817';
$iv_from_http_header = $request->header('x-initialization-vector');
$auth_tag_from_http_header = $request->header('x-authentication-tag');
$http_body = file_get_contents('php://input');

    $key = hex2bin($key_from_configuration);
    $iv = hex2bin($iv_from_http_header);
    $auth_tag = hex2bin($auth_tag_from_http_header);
    $cipher_text = hex2bin($http_body.$auth_tag_from_http_header);

    // This works when $cipher_text = hex2bin($http_body)
    $result = openssl_decrypt($cipher_text, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $auth_tag);

    // This does not work. According to the webhook docs, $cipher_text has to equal hex2bin($http_body.$auth_tag_from_http_header);
$result = sodium_crypto_aead_aes256gcm_decrypt($cipher_text, NULL, $iv, $key);

    Storage::put('json.txt', $result);
}

webhook的文档并不是很好,它们的示例是PHP v7.1之前的版本。这是他们的示例代码...

<?php
/* Php 7.1 or later */
    $key_from_configuration = "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f";
$iv_from_http_header = "000000000000000000000000";
    $auth_tag_from_http_header = "CE573FB7A41AB78E743180DC83FF09BD";
$http_body = "0A3471C72D9BE49A8520F79C66BBD9A12FF9";

    $key = hex2bin($key_from_configuration);
    $iv = hex2bin($iv_from_http_header);
    $auth_tag = hex2bin($auth_tag_from_http_header);
    $cipher_text = hex2bin($http_body);

    $result = openssl_decrypt($cipher_text, "aes-256-gcm", $key, OPENSSL_RAW_DATA, $iv, $auth_tag);
print($result);

/* Php prior to 7.1 */
    /* Please refer Using Libsodium in PHP Projects */
    $key_from_configuration = "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f";
$iv_from_http_header = "000000000000000000000000";
    $auth_tag_from_http_header = "CE573FB7A41AB78E743180DC83FF09BD";
$http_body = "0A3471C72D9BE49A8520F79C66BBD9A12FF9";

    $key = hex2bin($key_from_configuration);
    $iv = hex2bin($iv_from_http_header);
    $cipher_text = hex2bin($http_body . $auth_tag_from_http_header);

    $result = \Sodium\crypto_aead_aes256gcm_decrypt($cipher_text, NULL, $iv, $key);
    print($result);
?>

0 个答案:

没有答案