Trouble implementing functions to encrypt/decrypt a string- src included

  • Thread starter Thread starter EMonaco
  • Start date Start date
E

EMonaco

All,

I've taken a first crack at creating Encrypt/Decrypt (string) functions
for my password class. Unfortunately its not going too well. The
EncryptString line "bout = ess.ToArray();" returns bout[0]. Any ideas?


public class PasswordString
{
private string sPassword="";
private string sKey;

public string Key
{
get{return(sKey);}
set{sKey=value;}
}

private string EncryptString(string sUnencryptedPassword)
{
System.Byte [] bout = new System.Byte[1] {0};

if(sUnencryptedPassword.Length == 0)
return("");

try
{
// Create the stream to handle encrypted output
System.IO.MemoryStream ess = new System.IO.MemoryStream();
TripleDESCryptoServiceProvider tdes = new
TripleDESCryptoServiceProvider();
tdes.GenerateKey();
Key = System.Convert.ToBase64String(tdes.Key);
System.Security.Cryptography.CryptoStream encStream = new
System.Security.Cryptography.CryptoStream(ess,
tdes.CreateEncryptor(System.Convert.FromBase64String(Key),
KeepSecret.GetIV()), CryptoStreamMode.Write);

//write encrypted password to the output stream.
System.Byte [] bin =
System.Text.Encoding.UTF8.GetBytes(sUnencryptedPassword);
encStream.Write(bin, 0, bin.Length);
bout = ess.ToArray();
encStream.Clear();
ess.Close();
}
catch(System.Exception se)
{
System.Diagnostics.Debug.WriteLine(se.Message);
return("");
}

return(System.Convert.ToBase64String(bout));
}

private string DecryptString(string sEncryptedPassword)
{
System.Byte [] bout = new System.Byte[1] {0};

if(sEncryptedPassword.Length == 0)
return("");

try
{
System.IO.MemoryStream uss = new System.IO.MemoryStream();
TripleDESCryptoServiceProvider tdes = new
TripleDESCryptoServiceProvider();
System.Security.Cryptography.CryptoStream decStream = new
System.Security.Cryptography.CryptoStream(uss,
tdes.CreateDecryptor(System.Convert.FromBase64String(Key),
KeepSecret.GetIV()), CryptoStreamMode.Write);

// write unencrypted password to the output string
System.Byte [] bin =
System.Convert.FromBase64String(sEncryptedPassword);
decStream.Write(bin, 0, bin.Length);
bout = uss.ToArray();
decStream.Clear();
uss.Close();
}
catch(System.Exception se)
{
System.Diagnostics.Debug.WriteLine(se.Message);
return("");
}

return(System.Text.Encoding.UTF8.GetString(bout));
}

private class KeepSecret
{
public static byte [] GetIV()
{

return(System.Text.Encoding.UTF8.GetBytes("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQ
qRrSsTtUuVuWwXxYyZz"));
}
}
 
All,


I figured it out. After you have completed "writing" all data to the enc/dec
stream, you must close it before it actually gets encrypted/decrypted to
your underlying stream. And *shock*, this makes sense :)



Erin.
 
Back
Top