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

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

Regarding AES 256 Encryption:

  • 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?

回答1:

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

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


回答2:

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.

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!