如何通过 PHP 验证在 OpenSSL 命令行上创建的签名?
由于大小限制,PHP 的 openssl_sign
和 openssl_verify
函数似乎在签名之前对数据执行哈希处理,因此我尝试在命令行上模拟这一点。
通过 openssl 签名:
echo "foo" | openssl dgst -sha1 -binary | openssl rsautl -inkey priv.pem -sign > sig.bin
然后通过 PHP 验证
$key = openssl_pkey_get_public('pub.pem');
$ver = openssl_verify( "foo\n", file_get_contents('sig.bin'), $key, OPENSSL_ALGO_SHA1 );
// $ver always 0
我已经尝试了多种组合,二进制和十六进制形式的哈希,带或不带尾随换行符,甚至在传递到 php 函数之前进行哈希
It seems that PHP's openssl_sign
and openssl_verify
functions perform hashing of the data before signing, due to size restrictions, so I've tried emulating this on the command line.
Signing via openssl:
echo "foo" | openssl dgst -sha1 -binary | openssl rsautl -inkey priv.pem -sign > sig.bin
then verifying via PHP
$key = openssl_pkey_get_public('pub.pem');
$ver = openssl_verify( "foo\n", file_get_contents('sig.bin'), $key, OPENSSL_ALGO_SHA1 );
// $ver always 0
I've tried numerous combinations, binary and hex forms of the hash, with and without the trailing newline, and even hashing before passing into php function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的发现是 PHP 的签名和验证不能与 openssl 的 rsautl
-sign
和-verify
选项互操作。 PHP 似乎添加了一些元数据(额外的 15 个字节),尽管我不知道这意味着什么。我的解决方案:
我直接使用加密和解密函数并自己处理散列。
这样,命令行
-verify
选项类似于“用公钥解密”。同样,
-sign
类似于“用公钥加密”。事实上,通过这种方式,您可以定义自己的签名格式,例如包含日期和哈希值
My findings are that PHP's sign and verify are not interoperable with openssl's rsautl
-sign
and-verify
options. PHP seems to add some meta data, (an extra 15 bytes) although I don't know what it means.My solution:
I am using encrypt and decrypt functions directly and handling the hashing myself.
This way, the command line
-verify
option is analogous to "decrypt with public key".By the same token
-sign
is analogous to "encrypt with public key"In fact, this way you can define your own signature format, for example including a date along with the hash