Invalid character in a Base-64 string when Concatenating and Url encoding a string
- by Rob
I’m trying to write some encryption code that is passed through a Url. For the sake of the issue I’ve excluded the actual encryption of the data and just shown the code causing the problem.
I take a salt value, convert it to a byte array and then convert that to a base64 string. This string I concatenate to another base64 string (which was previously a byte array).
These two base64 strings are then Url encoded. Here’s my code...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Web;
class RHEncryption
{
private static readonly Encoding ASCII_ENCODING = new System.Text.ASCIIEncoding();
private static readonly string SECRET_KEY = "akey";
private static string md5(string text)
{
return BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(ASCII_ENCODING.GetBytes(text))).Replace("-", "").ToLower();
}
public string UrlEncodedData;
public RHEncryption()
{
// encryption object
RijndaelManaged aes192 = new RijndaelManaged();
aes192.KeySize = 192;
aes192.BlockSize = 192;
aes192.Mode = CipherMode.CBC;
aes192.Key = ASCII_ENCODING.GetBytes(md5(SECRET_KEY));
aes192.GenerateIV();
// convert Ivector to base64 for sending
string base64IV = Convert.ToBase64String(aes192.IV);
// salt value
string s = "maryhadalittlelamb";
string salt = s.Substring(0, 8);
// convert to byte array
// and base64 for sending
byte[] saltBytes = ASCII_ENCODING.GetBytes(salt.TrimEnd('\0'));
string base64Salt = Convert.ToBase64String(saltBytes);
//url encode concatenated base64 strings
UrlEncodedData = HttpUtility.UrlEncode(base64Salt + base64IV, ASCII_ENCODING);
}
public string UrlDecodedData()
{
// decode the url encode string
string s = HttpUtility.UrlDecode(UrlEncodedData, ASCII_ENCODING);
// convert back from base64
byte[] base64DecodedBytes = null;
try
{
base64DecodedBytes = Convert.FromBase64String(s);
}
catch (FormatException e)
{
Console.WriteLine(e.Message.ToString());
Console.ReadLine();
}
return s;
}
}
If I then call the UrlDecodedData method I get a “Invalid character in a Base-64 string” exception. This is generated because the base64Salt variable contains an invalid character (I’m guessing a line termination) but I can’t seem to strip it off.