I have been working with encryption/decryption RijndaelManaged alogorithm.
While encrypting a GUID we get "%" symbol in the middle of the encrypted algorithm. When I decrypt the same encrypted GUI i get a " Invalid character in a Base-64 string" error. This occurs due to the presence of % symbol in the encrypted token.
Here is the Code for encryption and decryption,
using System;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
public class ABC_RMCryptography
{
public string Decrypt(string strValueIn)
{
try
{
byte[] arrB = System.Convert.FromBase64String(strValueIn);
string strRC;
byte[] key = System.Convert.FromBase64String(ConfigurationManager.AppSettings["TokenEncryptionKey"]);
byte[] IV = System.Convert.FromBase64String(ConfigurationManager.AppSettings["TokenEncryptionVector"]);
MemoryStream memStream = new MemoryStream(arrB);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream CryptStream = new CryptoStream(memStream, RMCrypto.CreateDecryptor(key, IV), CryptoStreamMode.Read);
StreamReader SReader = new StreamReader(CryptStream);
strRC = SReader.ReadToEnd();
SReader.Close();
return strRC;
}
catch (Exception ex)
{
throw ex;
}
}
public string Encrypt(string strValue)
{
MemoryStream memStream = new MemoryStream();
try
{
byte[] key = System.Convert.FromBase64String(ConfigurationManager.AppSettings["TokenEncryptionKey"]);
byte[] IV = System.Convert.FromBase64String(ConfigurationManager.AppSettings["TokenEncryptionVector"]);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream CryptStream = new CryptoStream(memStream, RMCrypto.CreateEncryptor(key, IV), CryptoStreamMode.Write);
StreamWriter SWriter = new StreamWriter(CryptStream);
SWriter.Write(strValue);
SWriter.Close();
CryptStream.Close();
byte[] b = memStream.ToArray();
return Convert.ToBase64String(b);
}
catch (Exception ex)
{
throw ex;
}
}
private string GenerateRMKey()
{
RijndaelManaged objRM = new RijndaelManaged();
objRM.GenerateKey();
return Convert.ToBase64String(objRM.Key);
}
private string GenerateRMIV()
{
RijndaelManaged objRM = new RijndaelManaged();
objRM.GenerateKey();
return Convert.ToBase64String(objRM.IV);
}
}
Please let me know the solution to avoid this exception. How do I avoid % symbol?
Encryption/decryption gives Invalid character in a Base-64 string
Upvotes: 0
Views: 3132
Reputation: 1500903
Where exactly is the % coming from? It shouldn't be part of the return value from the Encrypt
method.
My guess is that you've got something performing URL-encoding on your encrypted text. If you could tell us more about where the % is and how you got that string, that would help a lot.
(As an aside, you should use using
statements for all the streams etc, rather than explicitly closing them; also your try/catch is somewhat pointless. Those are side issues though.)
Upvotes: 1