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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18850030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:24:42  来源:igfitidea点击:

AES 256 Encryption: public and private key how can I generate and use it .net

c#java.netvb.netaes

提问by Yasser-Farag

Regarding AES 256 Encryption:

关于 AES 256 加密:

  • What is the public and private key?
  • How can I generate these two keys?
  • How can I use the public to encrypt the data?
  • How can I use the private to decrypt the data?
  • 什么是公钥和私钥?
  • 如何生成这两个密钥?
  • 如何使用公共加密数据?
  • 如何使用私有来解密数据?

采纳答案by dcastro

In .Net, you can create your key pair like this:

在 .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);
}

You can then use your public key to encrypt a message like so:

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

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;
}

And use your private key to decrypt like this:

并使用您的私钥像这样解密:

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;
}

回答by user2787670

I think you are mixing things up. AES is a symmetric cipher, thus only have one key both for encryption and decryption. Asymmetric ciphers like RSA have two keys. A public key for encryption and a private key for decryption.

我认为你把事情搞混了。AES 是一种对称密码,因此只有一个密钥用于加密和解密。像 RSA 这样的非对称密码有两个密钥。用于加密的公钥和用于解密的私钥。

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

而对于reddit,你确实可以在不登录的情况下回答。