我有一种情况,我生成了一个 2048 位 RSA 公钥/私钥对。公钥复制到客户端计算机 (Windows),而私钥保存在服务器 (Linux) 上。我希望服务器能够使用私钥在数据块上生成签名,然后将签名和数据块发送给客户端,以便客户端可以使用公钥验证签名。
这是生成密钥的方式:
openssl genrsa -out private.key 2048
openssl req -subj "/C=GB/ST=ST/L=L/O=Org/OU=Unit/CN=cert name/emailAddress=nothing@nowhere" -new -x509 -key private.key -out publickey.cer -days 3650
openssl pkcs12 -passout pass:mypassword -export -nokeys -out public.key -in publickey.cer -inkey private.key
这将创建两个密钥文件,private.key(组合的公钥和私钥)和 public.key(公钥)。
客户端应用程序使用 C#。在那里,我像这样加载公钥:
X509Certificate2 cert = new X509Certificate2(@"D:\public.key", "mypassword");
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;
这适用于加密,因为如果我加密一个数据块并将其通过套接字连接发送到服务器,那么服务器可以对其进行解密并正确显示数据内容。所以我有信心正确加载密钥。
当服务器获得加密的数据块并正确解密后,它会签署响应并将其发送回客户端:
// Send a signed reply
unsigned char *signature = (unsigned char *) malloc(RSA_size(privateKey));
if (signature != NULL)
{
char *reply ="Top of the morning to you";
unsigned int siglen;
if (RSA_sign(NID_sha1, (unsigned char *)reply, strlen(reply), signature, &siglen, privateKey))
{
printf("SigLen = %d\n", siglen);
unsigned char *msg = (unsigned char *)malloc(siglen + strlen(reply));
if (msg != NULL)
{
memcpy(msg, signature, siglen);
memcpy(msg+siglen, reply, strlen(reply));
send(sock, msg, siglen + strlen(reply), 0);
free(msg);
}
}
free(signature);
}
客户端接收数据并将签名从正在签名的数据中分离出来,然后尝试验证签名,但这总是失败。这是客户端部分的完整代码:
static void Main(string[] args)
{
X509Certificate2 cert = new X509Certificate2(@"D:\public.key", "mypassword");
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;
string payload = "Hello world!!";
byte[] encrypted = rsa.Encrypt(Encoding.ASCII.GetBytes(payload), false);
TcpClient client = new TcpClient();
client.Connect("192.168.1.57", 2002);
NetworkStream ns = client.GetStream();
ns.Write(encrypted, 0, encrypted.Length);
ns.ReadTimeout = 2000;
byte[] rx = new byte[5000];
int bytesRead = ns.Read(rx, 0, rx.Length);
if (bytesRead > 0)
{
int keySizeBytes = rsa.KeySize >> 3;
if (bytesRead > keySizeBytes)
{
byte[] signedMessage = new byte[bytesRead - keySizeBytes];
Array.Copy(rx, keySizeBytes, signedMessage, 0, signedMessage.Length);
Array.Resize<byte>(ref rx, keySizeBytes);
if (rsa.VerifyData(signedMessage, CryptoConfig.MapNameToOID("SHA1"), rx))
{
Console.WriteLine("Verified OK");
}
else
{
Console.WriteLine("Not verified");
}
}
}
client.Close();
Console.ReadLine();
}
为了能够在客户端验证数据,我需要做些什么吗?