使用 phpseclib 与 openssl 进行 rsa 签名验证

rsa signature verification using phpseclib vs openssl

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()validverify2()invalid?

在 verify2 中你这样做:

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

改为这样做:

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