2

I am developing an application in c# asp.net which deals with reserved information.

For that reason I did some research and came up with below two functions for encryption and decryption respectively from c# on this tutorial :

http://www.aspsnippets.com/Articles/AES-Encryption-Decryption-Cryptography-Tutorial-with-example-in-ASPNet-using-C-and-VBNet.aspx

I have verified that there are cases where the decryption goes wrong, e.g

Encrypt("a808XXX") not working

Encrypt("A808XXX") working

Encrypt("a631XXX") working

Encrypt("A631XXX") not working

The error is :

base64 invalid characters

I have tried applied replace syntax without success :

Request.QueryString["m"].ToString().Replace(" ", "+")

My code below, how to do resolve this ?

Please help me, thank you in advance.

public string Encrypt(string clearText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}



private string Decrypt(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}
Antonio Mailtraq
  • 1,397
  • 5
  • 34
  • 82
  • 3
    Base64 strings can contain`/+=` characters that can cause issues when improperly sent in a query string, is that what your doing? If so see [How to achieve Base64 URL safe encoding in C#?](http://stackoverflow.com/questions/26353710/how-to-achieve-base64-url-safe-encoding-in-c), if not you need to show a `clearText` value captured from the debugger and the corresopnding string sent to `Decrypt()` – Alex K. Mar 01 '16 at 13:17
  • Not sure this will correct your problem, but you should add cs.FlushFinalBlock() after the cs.Write call in Encrypt. – Kevin Mar 01 '16 at 13:26
  • @Kevin Thank you for reply, but I don't understand your suggestion- – Antonio Mailtraq Mar 01 '16 at 13:29
  • It ensures that the final encrypted block is written to your stream before you close it. – Kevin Mar 01 '16 at 13:31
  • `.Close()` calls `.FlushFinalBlock()` so no need. – Alex K. Mar 01 '16 at 13:39
  • 1
    You should take note of Alex's full comment about base64 characters in a url (querystring, etc.), hence the suggestion to "base64urlencode" - re: debug the value of `m` so you see what you're actually using vs _expecting_. Also, there is an implementation in .Net [HttpServerUtility.UrlTokenEncode](https://msdn.microsoft.com/en-us/library/system.web.httpserverutility.urltokenencode(v=vs.100).aspx) and [UrlTokenDecode](https://msdn.microsoft.com/en-us/library/system.web.httpserverutility.urltokendecode(v=vs.100).aspx) Use what works for you. Hth... – EdSF Mar 01 '16 at 16:24

2 Answers2

1

The error message: "base64 invalid characters" is clear.

Debug: Find the error, where it occurs, fix the error. Don't just start trying things.

Print the Base64 string just after encryption and again just prior to decryption.

Compare looking for differences/corruption.

Verify that both Base64 strings contain only valid characters "A-Za-z/+" and possibly one or two trailing "=" characters.

If the Base64 string is part of a query string you may need to URL encode it.

zaph
  • 111,848
  • 21
  • 189
  • 228
0

You have to at least replace the characters + and /.

Try something like

.Replace("+", "-").Replace("/", "_");

Obviously you will have to do the opposite before decrypting.