views:

278

answers:

2

I have a project which requires encryption of customer ids. The encrypted value is used as a query string value for a website which then returns a personalized form for completion.

The problem I'm having is that the website we are working with has a security policy which disallows non-alphanumeric characters from a query string.

I'm currently trying to get confirmation of exactly which characters are being blocked, but the ideal solution would be to use an encryption algorithm which returns an alphanumeric string.

I haven't found any such algorithm in the System.Security.Cryptography namespace yet - evidently because the key size is generally 64bit or some multiple of - but I'm hoping that such an algorithm is available.

The only alternative at this stage is to swap out whichever characters are deemed illegal with other allowable characters, however I don't think I'm going to have enough allowable characters for this to work.

Does anything have any experience with this or suggestions on how to proceed?

+2  A: 

You just need to create a reversible mapping between arbitrary bytes (the output of the encryption algorithm) and characters in your allowable set.

Base64 works like this - it encodes arbitrary binary into characters in the set [A-Za-z0-9+/] (which is almost exactly what you want, with the addition of + and /). You could potentially use Base64 encoding, then replace + and / with two other "allowed characters", if there are any (perhaps - and _?).

There should be existing Base64 encoding and decoding functions available in your language.

caf
Thanks for the help - I've identified this possibility in my 'the only alternative...' statement above. It could/should work, but unfortunately I don't know what the allowable characters or if I'm going to have enough - i.e. there are not 64 alphanumeric characters.
Kirk Broadhurst
Well, there are 62 alphanumeric characters, so you only have to find two extra (I suggested `-` and `_` because they're very common in URLs, but `.` and `:` are two others to consider, because you can't really write a valid URL without those anyway...).
caf
+1  A: 

The encryption (or more likely in this case - hashing) will return an array of bytes. Convert the byte values to a hex string and pass that through.

private static string ByteArrayToHexString(byte[] byteArray)
{
    string result = string.Empty;

    foreach (byte outputByte in byteArray)
    {
        result += outputByte.ToString("x2");
    }
    return result;
}

Then to convert back from hex string to byte array

private static byte[] HexStringToByteArray(String hexString)
{
    int stringLength = hexString.Length;
    byte[] bytes = new byte[stringLength / 2];

    for (int i = 0; i < stringLength; i += 2)
    {
        bytes[i / 2] = System.Convert.ToByte(hexString.Substring(i, 2), 16);
    }
    return bytes;
}

Using these methods you can be sure that the only values you pass will be hex (0123456789ABCDEF)

PaulG