共用方式為


產生簽章

數位簽章通常套用到代表較大資料的雜湊值。以下範例將數位簽章套用到雜湊值。首先,建立 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 提供 System.Security.Cryptography.XML 命名空間,這讓您能夠簽章 XML。當您希望驗證 XML 是來自某一來源時,簽章 XML 是很重要的。例如,如果您是採用利用 XML 的內建 (Stock) 引號服務時,若它已被簽章您就可以驗證 XML 的來源。

這個命名空間中的類別遵照全球資訊網協會的建議<XML-Signature Syntax and Processing>,網址為 www.w3.org。

請參閱

概念

驗證簽章
密碼編譯簽章

其他資源

密碼編譯工作
密碼編譯服務