使用openssl/makecert工具创建x509证书

Zé *_*los 5 security encryption openssl rsa makecert

我正在使用带有以下参数的makecert创建x509证书:

makecert -r -pe -n"CN = Client"-ss MyApp

我想使用此证书使用RSA算法加密和解密数据.我期待在Windows证书库中生成证书,一切似乎都好(它有一个私钥,公钥是一个1024位的RSA密钥等等)

现在我使用这个C#代码来加密数据:

X509Store store = new X509Store("MyApp", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "Client", false);
X509Certificate2 _x509 = certs[0];

using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_x509.PublicKey.Key)
{
    byte[] dataToEncrypt = Encoding.UTF8.GetBytes("hello");
    _encryptedData = rsa.Encrypt(dataToEncrypt, true);
}
Run Code Online (Sandbox Code Playgroud)

执行Encrypt方法时,我收到带有消息"Bad key"的CryptographicException.

我认为代码很好.可能我没有正确创建证书.任何意见?谢谢

----------------编辑--------------
如果有人知道如何使用OpenSsl创建证书,它对我来说也是一个有效的答案.

Ras*_*ber 4

要允许密钥用于加密,您应该使用-sky-option。默认情况下 \xc2\xb4makecert` 使用 AT_SIGNATURE 密钥规范,该规范不适用于加密/解密。相反,通过发出以下命令来使用 AT_KEYEXCHANGE 规范:

\n\n
makecert -r -pe -n "CN=Client" -ss MyApp -sky Exchange\n
Run Code Online (Sandbox Code Playgroud)\n\n

(请记住删除以前的密钥或使用其他容器名称)。

\n