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

Regarding AES 256 encryption:

  • What is a public and private key?
  • How can I generate these two keys?
  • How can I use publication to encrypt data?
  • How can I use private to decrypt data?
+8
java c # aes
source share
2 answers

In .Net, you can create your key pair as follows:

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

Then you can use your public key to encrypt the message as follows:

 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 as follows:

 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; } 
+30
source share

I think you mix things. AES is symmetric encryption, therefore it has only one key for encryption and decryption. Asymmetric ciphers, such as RSA, have two keys. The public key for encryption and the private key for decryption.

And for reddit, you really can answer without logging in.

+10
source share

All Articles