使用 CspParameters

vic*_*ico 4 c# cryptography

我有将密钥存储在容器中的示例代码。但我只看到容器名称集。密钥存储程序在哪里?如何从容器加载密钥?

UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes("MySecretData!");
string containerName = "SecretContainer"; 
CspParameters csp = new CspParameters() { KeyContainerName = containerName }; 
byte[] encryptedData; 
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(csp)) 
{ 
 encryptedData = RSA.Encrypt(dataToEncrypt, false); 
}
Run Code Online (Sandbox Code Playgroud)

Evk*_*Evk 5

当您CspParameters使用KeyContainerNameset to传递时RSACryptoServiceProvider,其PersistKeyInCsp属性设置为true根据docs

当您在 CspParameters 对象的 KeyContainerName 字段中指定密钥容器名称并使用它通过调用具有参数参数的构造函数之一来初始化 RSACryptoServiceProvider 对象时,PersistKeyInCsp 属性会自动设置为 true。

使用该属性设置 - 提供者将首先检查具有此类名称的容器是否存在。如果是,它将使用该容器中的密钥。否则它将创建容器并将其密钥存储在那里。由于您没有提供特定的密钥 - 将生成一对随机密钥并将其存储在容器中。当您下次使用具有相同容器名称的 csp 时 - 将使用生成的密钥。

如果有不清楚的地方,请运行以下代码:

public class Program {
    static void Main(string[] args) {
        var containerName = "MyContainer";
        var original = "MySecretData!";
        var encrypted = Encrypt(containerName, original);
        var decrypted = Decrypt(containerName, encrypted);
        Debug.Assert(decrypted == original);
        Console.ReadLine();
    }

    static string Encrypt(string containerName, string data) {
        byte[] dataToEncrypt = Encoding.UTF8.GetBytes(data);
        CspParameters csp = new CspParameters() { KeyContainerName = containerName };
        // random key is generated and stored in new created container with provided name
        // since it does not exist yet
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp)) {
            return Convert.ToBase64String(rsa.Encrypt(dataToEncrypt, false));
        }
    }

    static string Decrypt(string containerName, string data) {
        CspParameters csp = new CspParameters() { KeyContainerName = containerName };
        // here container already exists so key from that container is used            
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp)) {
            return Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(data), false));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)