Sunday, February 13, 2005

I see requests for CF encryption examples on a regular basis in the newsgroups and the Forums.  Well, here's one I used in an app for storing a password in the registry using the OpenNETCF Encryption stuff :

internal static byte[] GetIV(string keyString)
{
 byte[] bytes = Encoding.Unicode.GetBytes(keyString);
 byte[] iv = new byte[24];
 if(bytes.Length < 24)
 {
  for(int i = 0 ; i < 24 ; i++)
  {
   iv[i] = bytes[i % bytes.Length];
  }
 }
 else
 {
  Array.Copy(bytes, 0, iv, 0, 24);
 }
 return iv;
}
internal static byte[] Encrypt(string toEncrypt, byte[] iv)
{
 TripleDESCryptoServiceProvider des = null;
 try
 {
  des = new TripleDESCryptoServiceProvider();
 }
 catch(Exception)
 {
  MessageBox.Show("The high encryption pack must be installed.  Please install and try again.",
   "Crypto Failure",
   MessageBoxButtons.OK,
   MessageBoxIcon.Exclamation,
   MessageBoxDefaultButton.Button1);
  return null;
 }
 des.Key = PRIVATE_KEY;
 des.IV = iv;
 return des.EncryptValue(Encoding.Unicode.GetBytes(toEncrypt));
}
internal static string Decrypt(byte[] toDecrypt, byte[] iv)
{
 TripleDESCryptoServiceProvider des = null;
 try
 {
  des = new TripleDESCryptoServiceProvider();
 }
 catch(Exception)
 {
  MessageBox.Show("The high encryption pack must be installed.  Please install and try again.",
   "Crypto Failure",
   MessageBoxButtons.OK,
   MessageBoxIcon.Exclamation,
   MessageBoxDefaultButton.Button1);
  return null;
 }
 des.Key = PRIVATE_KEY;
 des.IV = iv;
 byte[] decBytes = des.DecryptValue(toDecrypt);
 return Encoding.Unicode.GetString(decBytes, 0, decBytes.Length);
}
Usage is simple:
byte[] encryptedPwd = AppGlobal.Encrypt(password, GetIV(PUBLIC_KEY));
string  previousPwd = Decrypt(encryptedPwd , GetIV(PUBLIC_KEY));
2/13/2005 7:13:36 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1]  |