//********************************************************************* // // UniqueKeyContainerName // Derives unique key container name from CryptoAPI keycontainer name // // Note that keycontainer implementions are platform specific. // // Copyright (C) 2004. Michel I. Gallant // //********************************************************************** using System; using System.IO; using System.Text; using System.Security; using System.Security.Cryptography; using Microsoft.Win32; public class uniquekeycontainer { public static void Main(String[] args) { Console.WriteLine("Enter CryptoAPI CSP key containername:"); string containername = Console.ReadLine().Trim().ToLower(); byte[] strdata = Encoding.ASCII.GetBytes(containername); // uniquecontainername includes terminal null byte in data-to-hash; C# initializes array to zero byte[] datatohash = new byte[strdata.Length + 1]; Array.Copy(strdata, datatohash, strdata.Length); MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(datatohash); showBytes("\nMD5 raw hash:", result) ; // Display as DWORD (4-byte) groups; this simply reverses the order of 4-byte groups Console.WriteLine("Uniquecontainername prefix (hash read as 4 DWORDS)"); StringBuilder strb = new StringBuilder(32) ; BinaryReader binr = new BinaryReader(new MemoryStream(result)) ; for(int i=1; i<=4; i++) strb.Append(binr.ReadInt32().ToString("x8")); //read and build string Console.WriteLine("{0}", strb.ToString()) ; // Get MachineGuid suffix form registry try{ RegistryKey rk = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Cryptography"); String mguid = (String)rk.GetValue("MachineGuid"); strb.Append("_" + mguid); Console.WriteLine(); Console.WriteLine("Unique Key Container Name:\n{0}", strb.ToString()); } catch(Exception exc) { Console.WriteLine(exc.Message); } } private static byte[] GetFileBytes(String filename){ if(!File.Exists(filename)) return null; Stream stream=new FileStream(filename,FileMode.Open); int datalen = (int)stream.Length; byte[] filebytes =new byte[datalen]; stream.Seek(0,SeekOrigin.Begin); stream.Read(filebytes,0,datalen); stream.Close(); return filebytes; } private static void showBytes(String info, byte[] data){ Console.WriteLine("{0} [{1} bytes]", info, data.Length); for(int i=1; i<=data.Length; i++){ Console.Write("{0:x2}", data[i-1]) ; if(i%16 == 0) Console.WriteLine(); } Console.WriteLine(); } }