Ken

Ken

  • 0
  • 110
  • 0

Why do carrots disappear when coding a string in Base64?

Mar 20 2016 1:49 PM
Hi.  I am created a Base64 string using two functions I found online 
  1. public static string Encode(string plainText) {  
  2.   var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);  
  3.   return System.Convert.ToBase64String(plainTextBytes);  
  4. }  
  5.   
  6. public static string Decode(string base64EncodedData) {  
  7.   var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);  
  8.   return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);  
  9. }  
So I do string encoded = Encode("test^string"); but if I Console.WriteLine the encoded string I see "teststring".  How can I encode it and preserve the carrot?  I also tried two crypto functions I found online: 
  1. public static string EncryptString(string Message, string Passphrase) {  
  2.   byte[] Results;  
  3.   System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();  
  4.   MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();  
  5.   byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));  
  6.   TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();  
  7.   TDESAlgorithm.Key = TDESKey;  
  8.   TDESAlgorithm.Mode = CipherMode.ECB;  
  9.   TDESAlgorithm.Padding = PaddingMode.PKCS7;  
  10.   byte[] DataToEncrypt = UTF8.GetBytes(Message);  
  11.   try {  
  12.     ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();  
  13.     Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);  
  14.   } finally {  
  15.     TDESAlgorithm.Clear();  
  16.     HashProvider.Clear();  
  17.   }  
  18.   return Convert.ToBase64String(Results);  
  19. }  
  20.   
  21. public static string DecryptString(string Message, string Passphrase) {  
  22.   byte[] Results;  
  23.   System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();  
  24.   MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();  
  25.   byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));  
  26.   TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();  
  27.   TDESAlgorithm.Key = TDESKey;  
  28.   TDESAlgorithm.Mode = CipherMode.ECB;  
  29.   TDESAlgorithm.Padding = PaddingMode.PKCS7;  
  30.   byte[] DataToDecrypt = Convert.FromBase64String(Message);  
  31.   try {  
  32.     ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();  
  33.     Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);  
  34.   } finally {  
  35.     TDESAlgorithm.Clear();  
  36.     HashProvider.Clear();  
  37.   }  
  38.   return UTF8.GetString(Results);  
  39. }  
 I did string encoded = EncryptString("test^string", "somepassphrase"); then when I output it I get the same "teststring" as the other function.  Augh!

Answers (5)