生成签名
更新:2007 年 11 月
数字签名通常应用于表示较大数据的哈希值。下面的示例将数字签名应用于哈希值。首先,创建 RSACryptoServiceProvider 类的新实例以生成公钥/私钥对。接着,将 RSACryptoServiceProvider 传递给 RSAPKCS1SignatureFormatter 类的新实例。这就将该私钥传输给实际执行数字签名的 RSAPKCS1SignatureFormatter。在可以对哈希代码进行签名之前,必须指定要使用的哈希算法。本示例使用 SHA1 算法。最后,调用 RSAPKCS1SignatureFormatter.CreateSignature 方法以执行签名操作。
Imports System
Imports System.Security.Cryptography
Module Module1
Sub Main()
'The hash value to sign.
Dim HashValue As Byte() = {59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135}
'The value to hold the signed value.
Dim SignedHashValue() As Byte
'Generate a public/private key pair.
Dim RSA As New RSACryptoServiceProvider()
'Create an RSAPKCS1SignatureFormatter object and pass it
'the RSACryptoServiceProvider to transfer the private key.
Dim RSAFormatter As New RSAPKCS1SignatureFormatter(RSA)
'Set the hash algorithm to SHA1.
RSAFormatter.SetHashAlgorithm("SHA1")
'Create a signature for HashValue and assign it to
'SignedHashValue.
SignedHashValue = RSAFormatter.CreateSignature(HashValue)
End Sub
End Module
using System;
using System.Security.Cryptography;
class Class1
{
static void Main()
{
//The hash value to sign.
byte[] HashValue = {59,4,248,102,77,97,142,201,210,12,224,93,25,41,100,197,213,134,130,135};
//The value to hold the signed value.
byte[] SignedHashValue;
//Generate a public/private key pair.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Create an RSAPKCS1SignatureFormatter object and pass it the
//RSACryptoServiceProvider to transfer the private key.
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
//Set the hash algorithm to SHA1.
RSAFormatter.SetHashAlgorithm("SHA1");
//Create a signature for HashValue and assign it to
//SignedHashValue.
SignedHashValue = RSAFormatter.CreateSignature(HashValue);
}
}
签名 XML 文件
.NET Framework 提供使您可以对 XML 进行签名的 System.Security.Cryptography.XML 命名空间。当想要验证 XML 是否源自某个源时,对 XML 进行签名就变得非常重要。例如,如果您正在利用使用 XML 的股票报价服务,则如果 XML 被签名,您就可以验证该 XML 的源。
此命名空间中的类遵循万维网联合会的建议,详见在 www.w3.org 描述的“XML-Signature Syntax and Processing”(XML 签名语法和处理)。