AES 256加密:公钥和私钥我如何生成和使用它.net

时间:2013-09-17 12:35:13

标签: c# java .net vb.net aes

关于AES 256加密:

  • 什么是公钥和私钥?
  • 如何生成这两个键?
  • 如何使用公共加密数据?
  • 如何使用私有来解密数据?

2 个答案:

答案 0 :(得分:32)

在.Net中,您可以像这样创建密钥对:

public static Tuple<string, string> CreateKeyPair()
{
    CspParameters cspParams = new CspParameters { ProviderType = 1 };

    RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(1024, cspParams);

    string publicKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));
    string privateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true));

    return new Tuple<string, string>(privateKey, publicKey);
}

然后,您可以使用公钥来加密消息,如下所示:

public static byte[] Encrypt(string publicKey, string data)
{
    CspParameters cspParams = new CspParameters { ProviderType = 1 };
    RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);

    rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey));

    byte[] plainBytes = Encoding.UTF8.GetBytes(data);
    byte[] encryptedBytes = rsaProvider.Encrypt(plainBytes, false);

    return encryptedBytes;
}

并使用您的私钥解密,如下所示:

public static string Decrypt(string privateKey, byte[] encryptedBytes)
{
    CspParameters cspParams = new CspParameters { ProviderType = 1 };
    RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);

    rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey));

    byte[] plainBytes = rsaProvider.Decrypt(encryptedBytes, false);

    string plainText = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length);

    return plainText;
}

答案 1 :(得分:9)

我认为你正在混淆。 AES是对称密码,因此只有一个密钥用于加密和解密。像RSA这样的非对称密码有两个密钥。用于加密的公钥和用于解密的私钥。

And for reddit, you can indeed answer without being logged in.