Securing plain text — whether stored data or information sent over a network — is a common requirement in many applications. In .NET (C#), you can use cryptography libraries built into the framework to encrypt and decrypt strings. There are two major approaches: symmetric encryption, which uses a single shared secret key, and asymmetric encryption, which uses a pair of keys (public and private). This article shows you when to use each, and how to implement them with code.
Symmetric Encryption: Fast & Efficient with AES
What is Symmetric Encryption
- Symmetric encryption uses one secret key for both encrypting and decrypting data.
- It is fast and efficient, making it suitable for encrypting larger amounts of data.
- A commonly used algorithm in .NET is AES (Advanced Encryption Standard).
Example Implementation in C#
Here is a simplified example using AES to encrypt and decrypt a string:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AesStringCipher
{
public static (string cipherText, byte[] key, byte[] iv) Encrypt(string plainText)
{
using (Aes aes = Aes.Create())
{
aes.GenerateKey();
aes.GenerateIV();
byte[] key = aes.Key;
byte[] iv = aes.IV;
using (var ms = new MemoryStream())
using (var encryptor = aes.CreateEncryptor(key, iv))
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
using (var writer = new StreamWriter(cs))
{
writer.Write(plainText);
}
string cipherText = Convert.ToBase64String(((MemoryStream)ms).ToArray());
return (cipherText, key, iv);
}
}
public static string Decrypt(string cipherText, byte[] key, byte[] iv)
{
byte[] buffer = Convert.FromBase64String(cipherText);
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
using (var ms = new MemoryStream(buffer))
using (var decryptor = aes.CreateDecryptor(key, iv))
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (var reader = new StreamReader(cs))
{
return reader.ReadToEnd();
}
}
}
}
How it works
- We create a new AES instance, which generates a random secret key and initialization vector (IV).
- We encrypt the plaintext, write the encrypted bytes into a memory stream, then convert to a Base64 string for easy storage or transmission.
- To decrypt, the same key and IV are required; the Base64 string is converted back to bytes and decrypted to recover the original plaintext.
When to Use Symmetric Encryption
- When you control both ends of encryption/decryption and can securely share the secret key/IV.
- When encrypting larger strings or bulk data, since symmetric encryption is efficient and fast.
- When you need a simple but strong way to obfuscate data at rest (e.g. storing sensitive text in a database).
Asymmetric Encryption: Public/Private Key with RSA
What is Asymmetric Encryption
- Asymmetric encryption uses a key pair: a public key (which can be shared) and a private key (which you keep secret).
- Data encrypted with the public key can only be decrypted with the corresponding private key.
- Common use cases: secure transmission of small messages, secure key exchange, and sending data between parties who don’t share a secret key in advance.
Example Implementation in C#
Here’s a basic example using RSA to encrypt and decrypt a small string message:
using System;
using System.Security.Cryptography;
using System.Text;
public class RsaStringCipher
{
public static (string publicKeyXml, string privateKeyXml) GenerateKeys(int keySize = 2048)
{
using (var rsa = new RSACryptoServiceProvider(keySize))
{
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
return (publicKey, privateKey);
}
}
public static byte[] Encrypt(string plainText, string publicKeyXml)
{
using (var rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(publicKeyXml);
byte[] data = Encoding.UTF8.GetBytes(plainText);
return rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
}
}
public static string Decrypt(byte[] cipherBytes, string privateKeyXml)
{
using (var rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKeyXml);
byte[] plainBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
return Encoding.UTF8.GetString(plainBytes);
}
}
}
How it works
- You generate an RSA key pair (public + private) using
RSACryptoServiceProvider. - Use the public key to encrypt a plaintext message (converted to bytes).
- Decrypt with the private key — only the holder of the private key can recover the original message.
Important Considerations for Asymmetric Encryption
- Asymmetric encryption is relatively slow and not ideal for large data or long strings. It’s best suited for small messages or to encrypt symmetric keys.
- It’s common to combine symmetric and asymmetric encryption in a “hybrid” approach — e.g., encrypt your data with a fast symmetric algorithm like AES, then encrypt the symmetric key itself with RSA before transmitting.
- Always protect the private key securely — if it’s exposed, the security of the encrypted data is compromised.
Hybrid Approach: Combining AES + RSA
For many real-world applications, the optimal strategy is to combine the strengths of both symmetric and asymmetric encryption:
- Generate a random AES key (and IV) — use this to encrypt the actual plaintext (fast, efficient).
- Use RSA (or another asymmetric algorithm) to encrypt the AES key (and IV) using the recipient’s public key.
- Send both: (a) the AES-encrypted ciphertext, (b) the RSA-encrypted AES key (and IV).
- The recipient uses their RSA private key to decrypt the AES key/IV, then uses them to decrypt the ciphertext back to plaintext.
This hybrid model ensures both performance and secure key exchange, and is widely used in systems that require confidentiality + safe key distribution.
Practical Tips & Best Practices
- Use a strong random key and IV for symmetric encryption. Avoid reusing keys and IVs across different encryption operations.
- Never hard-code private keys or shared secret keys in source code. Consider securely storing keys, or deriving them from a secure password + salt.
- For sensitive scenarios (e.g., financial data, personal data), prefer using the hybrid approach (AES + RSA) rather than just symmetric or just asymmetric encryption.
- Always handle exceptions and errors properly in cryptographic code (e.g., invalid keys, corrupted ciphertexts).
- Consider additional security measures — encryption is just one piece of the puzzle; key management, secure storage, transport security, and access control are equally important.
Conclusion
Encrypting and decrypting strings in .NET / C# is straightforward once you understand the difference between symmetric and asymmetric encryption and know when to use each.
- Use symmetric encryption (like AES) when you need efficient, fast encryption — especially for larger strings or data at rest.
- Use asymmetric encryption (like RSA) when you need secure key distribution or to send data between parties that don’t share a secret key.
- For many real-world applications, combining both — encrypting data with AES and encrypting the AES key with RSA — gives you a balance of performance and security.
With the code templates provided above, you should be able to integrate basic encryption/decryption functionality into your .NET applications — just be sure to handle keys carefully and follow good security practices.