Encryption OpenSSL:在RSA中用私钥加密,用公钥解密

Encryption OpenSSL:在RSA中用私钥加密,用公钥解密,encryption,rsa,digital-signature,signature,Encryption,Rsa,Digital Signature,Signature,我想使用带有RSA算法的OpenSSL使用私钥加密文件: openssl rsautl -in txt.txt -out txt2.txt -inkey private.pem -encrypt 现在,如果我执行解密操作: openssl rsautl -in txt2.txt -pubin -inkey public.pem -decrypt 此操作需要私钥 我知道我应该使用公钥来加密,如果我使用私钥,我会得到一个签名 不过,我想这样做是为了学习。你用错键了。在公钥加密中,加密使用公钥:

我想使用带有RSA算法的OpenSSL使用私钥加密文件:

openssl rsautl -in txt.txt -out txt2.txt -inkey private.pem -encrypt
现在,如果我执行解密操作:

openssl rsautl -in txt2.txt -pubin -inkey public.pem -decrypt
此操作需要私钥

我知道我应该使用公钥来加密,如果我使用私钥,我会得到一个签名


不过,我想这样做是为了学习。

你用错键了。在公钥加密中,加密使用公钥:

openssl rsautl -in txt.txt -out txt2.txt -inkey public.pem -pubin -encrypt
对于解密,使用与公钥相关的私钥:

openssl rsautl -in txt2.txt -inkey private.pem -decrypt
私钥(不带
-pubin
)可用于加密,因为它实际上包含公共指数。请注意,RSA通常不应直接用于加密数据,而应仅用于“封装”(RSA-KEM)或“包装”用于对称加密的密钥

但你提到你实际上想研究签名。尽管历史上RSA签名有时被描述为“使用私钥加密”,但这种描述具有误导性,而且实际上实现起来并不安全。签名和验证实际上是不同于加密和解密的操作,而
rsautl
只执行其中的一部分。例如,您可以执行以下操作:

相反,最好使用执行PKCS1指定的整个签名和验证序列的
openssl dgst
。例如,对于带有SHA256的RSASSA-PKCS1v1_5签名:

此表单(但不是
rsautl
)还支持更新的、技术上更好但使用不广泛的PSS填充。这仅在
dgst
手册页上引用,并且主要记录在
pkeyutl
手册页上,这并不完全明显

在其他堆栈上,更多关于此主题,请参见,例如:






我的猜测是,在第一个命令中,即使您传递了私钥,它也只读取文件的前两个组件作为公钥,并执行公钥操作。您必须使用“签名”和“验证”子命令来执行看似要执行的操作。@dave_thompson_085感谢您的编辑。你想作为社区来回答这个问题吗?我看不出有任何理由;在我看来,它现在既完整又正确,没有必要鼓励进一步的改变。当然,像往常一样,任何(其他)想要进一步改变的人都可以提出或请求。
# 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 -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