生成加密和解密的密鑰

1.對稱密鑰
2.不對稱密鑰
3.將非對稱密鑰存儲在密鑰容器中
4.將非對稱密鑰存儲在密鑰容器中示例
===============================

創建和管理密鑰是加密過程的一個重要部分。
對稱算法要求創建必須對不應解密數據的任何人保密的密鑰和初始化向量 (IV)。
不對稱算法要求創建一個公鑰和一個私鑰。
公鑰可以對任何人公開,
而私鑰必須只爲將要對用公鑰加密的數據進行解密的一方知道。

對稱密鑰
========
.NET Framework 提供的對稱加密類
需要一個密鑰和一個新的初始化向量 (IV) 來加密和解密數據。
每當使用默認構造函數創建某個託管對稱加密類的新實例時,
都將自動創建新的密鑰和 IV。
無論您允許誰解密您的數據,
他或她都必須擁有同樣的密鑰和 IV 並使用相同的算法。
通常,應該爲每個會話創建新的密鑰和 IV,
並且無論是密鑰還是 IV 都不應存儲以用於稍後的會話中。

爲了將對稱密鑰和 IV 傳送給遠程方,
通常使用不對稱加密來加密對稱密鑰和 IV。
通過不安全的網絡發送這些值而不對這些值進行加密會極不安全,
這是因爲截獲這些值的任何人都能夠解密您的數據。

下面的示例顯示
實現TripleDES 算法的 TripleDESCryptoServiceProvider 類的新實例的創建。

Visual Basic:
Dim TDES As TripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider()

C#:
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

在執行上面的代碼時,將生成新的密鑰和 IV 並將其分別放置在 Key 和 IV 屬性中。

有時您可能需要生成多個密鑰。
這種情況下,可以創建實現對稱算法的類的新實例,
然後通過調用 GenerateKey 和 GenerateIV 方法創建新的密鑰和 IV。
下面的代碼示例闡釋如何在創建了不對稱加密類的新實例後創建新的密鑰和 IV。

Visual Basic :
Dim TDES As TripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider()
TDES.GenerateIV()
TDES.GenerateKey()

C# :
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();
TDES.GenerateIV();
TDES.GenerateKey();

當執行上面的代碼時,創建 TripleDESCryptoServiceProvider 的新實例後將生成密鑰和 IV。
調用 GenerateKey 和 GenerateIV 方法時將創建另一個密鑰和 IV。

不對稱密鑰
==========
.NET Framework 爲不對稱加密提供了
RSACryptoServiceProvider 和 DSACryptoServiceProvider 類。
這些類在您使用默認構造函數創建新實例時創建一個公鑰/私鑰對。
既可以存儲不對稱密鑰以用在多個會話中,
也可以只爲一個會話生成不對稱密鑰。
公鑰可以被廣泛地使用,私鑰應被嚴密地保護起來。

每當創建不對稱算法類的新實例時,都生成一個公鑰/私鑰對。
創建該類的新實例後,可以用以下兩種方法之一提取密鑰信息:

ToXMLString 方法,它返回密鑰信息的 XML 表示形式。
ExportParameters 方法,它返回 RSAParameters 結構以保存密鑰信息。
兩個方法都接受布爾值,該值指示是隻返回公鑰信息還是同時返回公鑰和私鑰信息。

通過使用 ImportParameters 方法,
可以將 RSACryptoServiceProvider 類初始化爲 RSAParameters 結構的值。

千萬不要將不對稱私鑰逐字存儲(或者說以明文形式存儲)在本地計算機上。
如果需要存儲私鑰,則應使用密鑰容器。
有關如何在密鑰容器中存儲私鑰的更多信息,
請參見如何:將非對稱密鑰存儲在密鑰容器中。

下面的代碼示例創建 RSACryptoServiceProvider 類的一個新實例,
創建一個公鑰/私鑰對,並將公鑰信息保存在 RSAParameters 結構中。

Visual Basic  複製代碼
'Generate a public/private key pair.
Dim RSA as RSACryptoServiceProvider = new RSACryptoServiceProvider()
'Save the public key information to an RSAParameters structure.
Dim RSAKeyInfo As RSAParameters = RSA.ExportParameters(false)

 
C#  複製代碼
//Generate a public/private key pair.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Save the public key information to an RSAParameters structure.
RSAParameters RSAKeyInfo = RSA.ExportParameters(false);
 
將非對稱密鑰存儲在密鑰容器中
============================

創建非對稱密鑰並將其保存在密鑰容器中
------------
1.創建 CspParameters 類的一個新實例,
  並將您要密鑰容器使用的名稱傳遞給 CspParameters.KeyContainerName 字段。
2.爲從 AsymmetricAlgorithm 類派生的一個類
 (通常是 RSACryptoServiceProvider 或 DSACryptoServiceProvider)創建一個新實例,
  並將先前創建的 CspParameters 對象傳遞給其構造函數。

從密鑰容器中刪除密鑰
------------
1.創建 CspParameters 類的一個新實例,
  並將您要密鑰容器使用的名稱傳遞給 CspParameters.KeyContainerName 字段。
2.爲從 AsymmetricAlgorithm 類派生的一個類
(通常是 RSACryptoServiceProvider 或 DSACryptoServiceProvider)創建一個新實例,
 並將先前創建的 CspParameters 對象傳遞給其構造函數。
3.將從 AsymmetricAlgorithm 中派生的類
  的 PersistKeyInCSP 屬性設置爲 false(在 Visual Basic 中爲 False)。
4.調用從 AsymmetricAlgorithm 派生的類的 Clear 方法。
  該方法釋放該類所有的資源並清除密鑰容器。

將非對稱密鑰存儲在密鑰容器中示例
====
下面的示例說明下面這一過程:
創建一個非對稱密鑰,將其保存在密鑰容器中,
以後檢索此密鑰,最後從該容器中刪除此密鑰。

請注意,GenKey_SaveInContainer 方法和 GetKeyFromContainer 方法的代碼相似。
當爲 CspParameters 對象指定密鑰容器名稱並將其傳遞給 PersistKeyInCsp 屬性
   或 PersistKeyInCsp 屬性設置爲 true 的 AsymmetricAlgorithm 對象時,
  將會發生以下情況。
  如果不存在具有指定名稱的密鑰容器,
        則系統將創建一個密鑰容器,但密鑰保持不變。
  如果確實存在具有指定名稱的密鑰容器,
        則將此容器中的密鑰自動加載到當前 AsymmetricAlgorithm 對象中。
  因此,GenKey_SaveInContainer 方法中的代碼保持密鑰不變,因爲它首先運行;
  而 GetKeyFromContainer 方法中的代碼加載此密鑰,因爲它隨後運行。

Visual Basic  複製代碼
Imports System
Imports System.IO
Imports System.Security.Cryptography
 _

Public Class StoreKey

    Public Shared Sub Main()
        Try
            ' Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer")

            ' Retrieve the key from the container.
            GetKeyFromContainer("MyKeyContainer")

            ' Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer")

            ' Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer")

            ' Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer")
        Catch e As CryptographicException
            Console.WriteLine(e.Message)
        End Try
    End Sub

    Public Shared Sub GenKey_SaveInContainer(ByVal ContainerName As String)
        ' Create the CspParameters object and set the key container
        ' name used to store the RSA key pair.
        Dim cp As New CspParameters()
        cp.KeyContainerName = ContainerName

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container MyKeyContainerName.
        Dim rsa As New RSACryptoServiceProvider(cp)

        ' Display the key information to the console.
        Console.WriteLine("Key added to container:  {0}", rsa.ToXmlString(True))
    End Sub

    Public Shared Sub GetKeyFromContainer(ByVal ContainerName As String)
        ' Create the CspParameters object and set the key container
        '  name used to store the RSA key pair.
        Dim cp As New CspParameters()
        cp.KeyContainerName = ContainerName

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container MyKeyContainerName.
        Dim rsa As New RSACryptoServiceProvider(cp)

        ' Display the key information to the console.
        Console.WriteLine("Key retrieved from container : {0}", rsa.ToXmlString(True))
    End Sub

    Public Shared Sub DeleteKeyFromContainer(ByVal ContainerName As String)
        ' Create the CspParameters object and set the key container
        '  name used to store the RSA key pair.
        Dim cp As New CspParameters()
        cp.KeyContainerName = ContainerName

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container.
        Dim rsa As New RSACryptoServiceProvider(cp)

        ' Delete the key entry in the container.
        rsa.PersistKeyInCsp = False

        ' Call Clear to release resources and delete the key from the container.
        rsa.Clear()

        Console.WriteLine("Key deleted.")
    End Sub
End Class

 
C#  複製代碼
using System;
using System.IO;
using System.Security.Cryptography;

public class StoreKey

{
    public static void Main()
    {
        try
        {
            // Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer");
           
            // Retrieve the key from the container.
            GetKeyFromContainer("MyKeyContainer");
   
            // Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer");

            // Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer");

            // Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer");
        }
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }

    }

    public static void GenKey_SaveInContainer(string ContainerName)
    {
        // Create the CspParameters object and set the key container
        // name used to store the RSA key pair.
        CspParameters cp = new CspParameters();
        cp.KeyContainerName = ContainerName;

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container MyKeyContainerName.
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);

        // Display the key information to the console.
        Console.WriteLine("Key added to container: /n  {0}", rsa.ToXmlString(true));
    }

    public static void GetKeyFromContainer(string ContainerName)
    {
        // Create the CspParameters object and set the key container
        // name used to store the RSA key pair.
        CspParameters cp = new CspParameters();
        cp.KeyContainerName = ContainerName;

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container MyKeyContainerName.
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);

        // Display the key information to the console.
        Console.WriteLine("Key retrieved from container : /n {0}", rsa.ToXmlString(true));
    }

    public static void DeleteKeyFromContainer(string ContainerName)
    {
        // Create the CspParameters object and set the key container
        // name used to store the RSA key pair.
        CspParameters cp = new CspParameters();
        cp.KeyContainerName = ContainerName;

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container.
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);

        // Delete the key entry in the container.
        rsa.PersistKeyInCsp = false;

        // Call Clear to release resources and delete the key from the container.
        rsa.Clear();

        Console.WriteLine("Key deleted.");
    }
}
 

輸出
 
Key added to container:
<RSAKeyValue> Key Information A</RSAKeyValue>
Key retrieved from container :
<RSAKeyValue> Key Information A</RSAKeyValue>
Key deleted.
Key added to container:
<RSAKeyValue> Key Information B</RSAKeyValue>
Key deleted.
 

發佈了37 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章