// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.IO; using System.Text; using System.Security.Cryptography; public class PersistedInfo { private Encoding utf = new UTF8Encoding(); private TripleDES des3 = new TripleDESCryptoServiceProvider(); private ICryptoTransform encrypt; private ICryptoTransform decrypt; public PersistedInfo(string key) { if(key.Length != 24) { throw new Exception("Key musy be 24 characters"); } byte[] bkey = utf.GetBytes(key); byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 }; encrypt = des3.CreateEncryptor(bkey, iv); decrypt = des3.CreateDecryptor(bkey, iv); } public void Save(string data, string filename) { byte[] cipher = encrypt.TransformFinalBlock(utf.GetBytes(data), 0, utf.GetByteCount(data)); Stream stm = new FileStream(filename, FileMode.Create); stm.Write(cipher, 0, cipher.Length); stm.Close(); } public string Load(string filename) { int len = (int)(new FileInfo(filename)).Length; byte[] cipher = new Byte[len]; Stream stm = new FileStream(filename, FileMode.Open); stm.Read(cipher, 0, len); stm.Close(); String plain = utf.GetString(decrypt.TransformFinalBlock(cipher, 0, cipher.Length)); return plain; } } public class PersistedUserInfo { private PersistedInfo pi; private string username; private string password; private string group; public PersistedUserInfo(string key) { pi = new PersistedInfo(key); } public void Save(string filename) { pi.Save(username + "," + password + "," + group, filename); } public void Load(string filename) { string temp = pi.Load(filename); string[] tempsplit = temp.Split(",".ToCharArray()); username = tempsplit[0]; password = tempsplit[1]; group = tempsplit[2]; } public string Username { get { return username; } set { username = value; } } public string Password { get { return password; } set { password = value; } } public string Group { get { return group; } set { group = value; } } } class MainClass { public static void Main(string[] args) { PersistedUserInfo pui = new PersistedUserInfo("123456789012345678901234"); pui.Username = "arne"; pui.Password = "hemmeligt"; pui.Group = "tech"; pui.Save("C:\\userinfo.dat"); PersistedUserInfo pui2 = new PersistedUserInfo("123456789012345678901234"); pui2.Load("C:\\userinfo.dat"); Console.WriteLine(pui2.Username + " " + pui2.Password + " " + pui2.Group); } }