使用phpseclib vs openssl的rsa签名验证

时间:2018-07-29 12:50:04

标签: php phpseclib

public function verify1()
{
    $pem = "-----BEGIN PUBLIC KEY-----\n" . chunk_split('MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjnUb+QXzIPgc4jM/IhrDw9WW9xS3P7Tu4gopaSjKYs1Kw0djxtpBI6+JOkSLbFQQIpEb9RrUDCTyFjgqlcQiapYk9RjbYJaZVit6+fkYKr43G6XcuMvuv61/nrTrMoX6AdVkcmE2Ufdg/a3TOgm8W/rT2BRk8FIdnFZlbeMIZbcnVKwfFRoAG4AasBLe62PhSZSCyj+eBNSH5ABWi0SXjQ9u4j/w+GXl3ezrjOkBop35n6i+8osdhrs7UI9ganJRPjGnUqgfLTC7GklyOhPb1l+LshHuXMgbq7EQ2f2pCZOS0S2VX25rtfQ8GLskE7xL4COLH7nk/KBS87Rikle41QIDAQAB', 64, "\n") . "-----END PUBLIC KEY-----\n";
    $hash = hash('sha256', "{\"paymentIdentifier\":\"Q0541311\",\"internalTrackingId\":\"20180726OPENAPI00FGAGS0020026\",\"clientReferenceId\":\"274\"}", true);
    $signature = "TqQtWL9XEmFX9WOMq4ti4JZEZtWj/nlPqnB99L+mPOTMcnzAAXXMsGc2u504Wf445vEid+ts+VvBmB0af/itJKL1nNINDb9e3NA0+0bOAFfDBKO+i5ULcPVx72tFmIY7uMux6GsZsVN/p2YGyhQhD/9A6ds+72jf8HguSYZ1urw4tT3hCfDPSgoCL4svqbPJ2AGRllrPMnrDOqnmGJaWGXNlm1J+6aFiEyWpb2O496descwhHs7WVYUxX1tRcFfd+AXjIDXJ1OzFTzXWAcvHF/v9y/sYgdz0TtG4URviypp4dLmJvL52Y1hoK/74vcHa4HKw/LZTFnDR4mzYEfnOFQ==";
    $ok = openssl_verify($hash, base64_decode($signature), $pem);
    if ($ok == 1) {
        echo "valid";
    } elseif ($ok == 0) {
        echo "invalid";
    } else {
        echo "error: ".openssl_error_string();
    }
}


public function verify2()
{
    $pem = "-----BEGIN PUBLIC KEY-----\n" . chunk_split('MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjnUb+QXzIPgc4jM/IhrDw9WW9xS3P7Tu4gopaSjKYs1Kw0djxtpBI6+JOkSLbFQQIpEb9RrUDCTyFjgqlcQiapYk9RjbYJaZVit6+fkYKr43G6XcuMvuv61/nrTrMoX6AdVkcmE2Ufdg/a3TOgm8W/rT2BRk8FIdnFZlbeMIZbcnVKwfFRoAG4AasBLe62PhSZSCyj+eBNSH5ABWi0SXjQ9u4j/w+GXl3ezrjOkBop35n6i+8osdhrs7UI9ganJRPjGnUqgfLTC7GklyOhPb1l+LshHuXMgbq7EQ2f2pCZOS0S2VX25rtfQ8GLskE7xL4COLH7nk/KBS87Rikle41QIDAQAB', 64, "\n") . "-----END PUBLIC KEY-----\n";
    $hash = hash('sha256', "{\"paymentIdentifier\":\"Q0541311\",\"internalTrackingId\":\"20180726OPENAPI00FGAGS0020026\",\"clientReferenceId\":\"274\"}", true);
    $signature = "TqQtWL9XEmFX9WOMq4ti4JZEZtWj/nlPqnB99L+mPOTMcnzAAXXMsGc2u504Wf445vEid+ts+VvBmB0af/itJKL1nNINDb9e3NA0+0bOAFfDBKO+i5ULcPVx72tFmIY7uMux6GsZsVN/p2YGyhQhD/9A6ds+72jf8HguSYZ1urw4tT3hCfDPSgoCL4svqbPJ2AGRllrPMnrDOqnmGJaWGXNlm1J+6aFiEyWpb2O496descwhHs7WVYUxX1tRcFfd+AXjIDXJ1OzFTzXWAcvHF/v9y/sYgdz0TtG4URviypp4dLmJvL52Y1hoK/74vcHa4HKw/LZTFnDR4mzYEfnOFQ==";
    $rsa = new \phpseclib\Crypt\RSA();
    $rsa->setEncryptionMode(\phpseclib\Crypt\RSA::ENCRYPTION_PKCS1);
    $rsa->loadKey($pem);
    echo $rsa->verify($hash, base64_decode($signature, true)) ? 'valid' : 'invalid';

}

有人可以帮助我理解为什么verify1()有效verify2()无效吗?

1 个答案:

答案 0 :(得分:0)

在verify2中,您正在这样做:

$rsa->setEncryptionMode(\phpseclib\Crypt\RSA::ENCRYPTION_PKCS1);

执行此操作:

$rsa->setSignatureMode(\phpseclib\Crypt\RSA::SIGNATURE_PKCS1);