直接上代码:
public CngKey _aliceKey;
public byte[] _alicePubKeyBlob;
static void Main(string[] args)
{
byte[] doc;
byte[] hash;
byte[] signature;
var pro = new Program();
pro.AliceTasks(out doc,out hash,out signature);
pro.BobTasks(doc, hash, signature);
Console.ReadLine();
}
public void AliceTasks(out byte[] data, out byte[] hash, out byte[] signature)
{
InitAliceKeys();
data = Encoding.UTF8.GetBytes("艾丽斯的问候");
hash = HashDocument(data);
signature = AddSignatureToHash(hash, _aliceKey);
}
private void InitAliceKeys()
{
_aliceKey = CngKey.Create(CngAlgorithm.Rsa);
_alicePubKeyBlob = _aliceKey.Export(CngKeyBlobFormat.GenericPublicBlob);
}
private byte[] HashDocument(byte[] data)
{
using (var hashAlg = SHA384.Create())
{
return hashAlg.ComputeHash(data);
}
}
private byte[] AddSignatureToHash(byte[] hash, CngKey key)
{
using (var signingAlg = new RSACng(key))
{
byte[] signed = signingAlg.SignHash(hash, HashAlgorithmName.SHA384, RSASignaturePadding.Pss);
return signed;
}
}
public void BobTasks(byte[] data, byte[] hash, byte[] signature)
{
CngKey aliceKey = CngKey.Import(_alicePubKeyBlob,CngKeyBlobFormat.GenericPublicBlob);
if (!IsSignatureValid(hash, signature, aliceKey))
{
Console.WriteLine("签名无效");
return;
}
if (!IsDocumentUnChanged(hash, data))
{
Console.WriteLine("文档已更改");
}
Console.WriteLine("签名有效文档未更改");
Console.WriteLine($"来自Alice的文档:{Encoding.UTF8.GetString(data)}");
}
private bool IsSignatureValid(byte[] hash, byte[] signature, CngKey key)
{
using (var SigningAlg = new RSACng(key))
{
return SigningAlg.VerifyHash(hash, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pss);
}
}
private bool IsDocumentUnChanged(byte[] hash, byte[] data)
{
byte[] newHash = HashDocument(data);
return newHash.SequenceEqual(hash);
}