using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Text; namespace BeWo.Security { public class EncryptionUtils { private static readonly byte[] _Rc2Iv = { 50, 241, 173, 46, 224, 103, 137, 72 }; private static readonly byte[] _Rc2Key = { 140, 81, 67, 90, 70, 222, 51, 20, 154, 60, 68, 87, 112, 169, 38, 234 }; public static string EncryptString(string stringToEncrypt) { var rc2Csp = new RC2CryptoServiceProvider(); var encryptor = rc2Csp.CreateEncryptor(_Rc2Key, _Rc2Iv); using(var memoryStream = new MemoryStream()) { using(var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) { var toEncrypt = Encoding.UTF8.GetBytes(stringToEncrypt); cryptoStream.Write(toEncrypt, 0, toEncrypt.Length); cryptoStream.FlushFinalBlock(); var encrypted = memoryStream.ToArray(); return Convert.ToBase64String(encrypted); } } } public static string DecryptString(string stringToDecrypt) { if (String.IsNullOrEmpty(stringToDecrypt)) { return ""; } var rc2Csp = new RC2CryptoServiceProvider(); var decryptor = rc2Csp.CreateDecryptor(_Rc2Key, _Rc2Iv); stringToDecrypt = stringToDecrypt.Replace(' ', '+'); stringToDecrypt = stringToDecrypt.Trim(','); try { using (var memoryStream = new MemoryStream(Convert.FromBase64String(stringToDecrypt))) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var bytes = new List(); int b; do { b = cryptoStream.ReadByte(); if(b != -1) { bytes.Add(Convert.ToByte(b)); } } while(b != -1); return Encoding.UTF8.GetString(bytes.ToArray()); } } } catch(CryptographicException) { // Es wird davon ausgegangen, dass der String nicht verschlüsselt ist. return Encoding.UTF8.GetString(Convert.FromBase64String(stringToDecrypt)); } } } }