我想使用带有RSA算法的OpenSSL使用私钥加密文件
openssl rsautl -in txt.txt -out txt2.txt -inkey private.pem -encrypt
现在,如果我要解密操作
openssl rsautl -in txt2.txt -pubin -inkey public.pem -decrypt
此操作需要私钥
我知道我应该使用公钥进行加密,如果使用私钥,我将获得签名。 我想这样做是为了学习目的
答案 0 :(得分:1)
您错误地使用了按键。在公钥加密中,加密使用公钥:
openssl rsautl -in txt.txt -out txt2.txt -inkey public.pem -pubin -encrypt
对于解密,使用与公钥相关的私钥:
openssl rsautl -in txt2.txt inkey private.pem -decrypt
私钥( without -pubin
)可以用于加密,因为它实际上包含公用指数。请注意,通常不应将RSA直接用于加密数据,而只能“封装”(RSA-KEM)或“包装”用于对称加密的密钥。
但是您提到您实际上想研究签名。尽管从历史上讲,有时有时将RSA签名描述为“使用私钥加密”,但这种描述具有误导性,实际上实施起来并不安全。签名和验证实际上是不同于加密和解密的不同操作,rsautl
仅执行其中的 part 。例如,您可以做:
# hash the data and encode the result in ASN.1
openssl rsautl -sign -in hashenc.dat -out sig.dat -inkey private.pem
...
# on the recipient (with signature and purportedly correct data)
openssl rsautl -verify -in sig.dat -out hashenc.dat -inkey public.pem -pubin
# or often more appropriate use a certificate for the public key
openssl rsautl -verify -in sig.dat -out hashenc.dat -inkey cert.pem -certin
# now either decode hashenc.dat and compare the hash
# to a new hash of the data (which should be the same)
# or compare all of hashenc.dat to an encoding of a new hash
相反,最好使用openssl dgst
来执行PKCS1 e.g. rfc8017指定的整个签名和验证序列。例如,带有SHA256的RSASSA-PKCS1v1_5签名 :
openssl dgst -sha256 -sign private.pem -in data.txt -out sig.dat
# or can be abbreviated
openssl sha256 -sign private.pem -in data.txt -out sig.dat
# hashes the data, encodes the hash, does type 1 padding and modexp d
...
openssl dgst -sha256 -verify public.pem -in data.txt -signature sig.dat
# or abbreviated
openssl sha256 -verify public.pem -in data.txt -signature sig.dat
# does modexp e and type 1 unpadding, and compares the result to a hash of the data
# notice you don't specify which key is public or private
# because this command knows what to expect
# however it does not accept the public key from a certificate,
# you must extract the public key from the cert first
此表单(但不rsautl
)也支持更新且技术上更好但使用不广泛的PSS填充。这仅在dgst
手册页上进行了引用,并且大多在pkeyutl
手册页上进行了记录,这并不完全清楚。
在其他堆栈上,这是最受关注的内容,例如:
https://security.stackexchange.com/questions/93603/understanding-digitial-certifications
https://security.stackexchange.com/questions/87325/if-the-public-key-cant-be-used-for-decrypting
https://security.stackexchange.com/questions/11879/is-encrypting-data-with-a-private-key-dangerous
https://security.stackexchange.com/questions/68822/trying-to-understand-rsa-and-its-terminology
https://crypto.stackexchange.com/questions/2123/rsa-encryption-with-private-key-and-decryption-with-a-public-key
https://crypto.stackexchange.com/questions/15997/is-rsa-encryption-the-same-as-signature-generation
https://crypto.stackexchange.com/questions/15295/why-the-need-to-hash-before-signing-small-data