Updated on Kisan Patel
Problem:
Encrypting & Decrypting a String in C#
Decrypting PKCS#7 encrypted data in C#
Encrypt string with Bouncy Castle AES/CBC/PKCS7
AES PKCS7 padding
Decrypt PKCS#7 Message in C#
C# Encrypt/Decrypt from Java AES/CBC/PKCS5Padding
Solution:
using System; using System.Text; using System.Security.Cryptography; public class Program { public static string Encrypt(string text) { var b = Encoding.UTF8.GetBytes(text); var encrypted = getAes().CreateEncryptor().TransformFinalBlock(b, 0, b.Length); return Convert.ToBase64String(encrypted); } public static string Decrypt(string encrypted) { var b = Convert.FromBase64String(encrypted); var decrypted = getAes().CreateDecryptor().TransformFinalBlock(b, 0, b.Length); return Encoding.UTF8.GetString(decrypted); } static Aes getAes() { var keyBytes = new byte[16]; var skeyBytes = Encoding.UTF8.GetBytes("12345678901234567890123456789012"); Array.Copy(skeyBytes, keyBytes, Math.Min(keyBytes.Length, skeyBytes.Length)); Aes aes = Aes.Create(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; aes.Key = keyBytes; aes.IV = keyBytes; return aes; } public static void Main() { string encryptMe; string encrypted; string decrypted; encryptMe = "Hello World!"; Console.WriteLine("encryptMe = " + encryptMe); encrypted = Program.Encrypt(encryptMe); Console.WriteLine("Encypted: " + encrypted); decrypted = Program.Decrypt(encrypted); Console.WriteLine("Dencypted: " + decrypted); } }