i am implementing the application using asp.net.
I want to make the querysting unchangeable. if i do the changes in manually , some exception needs to thrown .
how do i implement ?
"Try encrypting the querystring and append the resulting string to the querystring. When reading out your querystring, first encrypt the normal parameters again and compare it to the string. Then when any parameters get changed, the hash will not match anymore and you can throw an exception.
Something like this. Search for a nice Querystring reader/writer class to make life easier.
private string GetSecureQsToken(string querystring)
{
Byte[] buffer = Encoding.UTF8.GetBytes(querystring);
SHA1CryptoServiceProvider cryptoTransformSha1 =
new SHA1CryptoServiceProvider();
string hash = BitConverter.ToString(
cryptoTransformSha1.ComputeHash(buffer)).Replace("-", "");
return hash;
}
private void GoToSecureQsPage()
{
string qsvalues = "id=1&page=4";
Response.Redirect(string.Format("Default.aspx?{0}&hash={1}", qsvalues, GetSecureQsToken(qsvalues)));
}
private void ReadSecureQs()
{
//here check the normal querystring parameters again against the hash parameter
if (GetSecureQsToken("id=1&page=4") != Request.QueryString["hash"])
{
throw new Exception("Error here");
}
}
I simply went for the Hash version as it was suggested in the comments, but yes, then it becomes changeable again by the client. SO you will need some encryption like this:
public class SecureQuerystring
{
public SecureQuerystring()
{
m_passPhrase = "#oqT6%hKg";
m_saltValue = "7651273512";
m_initVector = "#1B2c3D4e5F6g7H8";
m_hashAlgorithm = "SHA1";
m_passwordIterations = 5;
m_keySize = 128;
}
private string m_plaintext;
private string m_ciphertext;
private byte[] m_plaintextbytes;
private byte[] m_ciphertextbytes;
private string m_passPhrase;
private string m_saltValue;
private string m_hashAlgorithm;
private Int32 m_passwordIterations;
private string m_initVector;
private Int32 m_keySize;
public string plaintext
{
get { return m_plaintext; }
set { m_plaintext = value; }
}
public string ciphertext
{
get { return m_ciphertext; }
set { m_ciphertext = value; }
}
public byte[] plaintextbytes
{
get { return m_plaintextbytes; }
set { m_plaintextbytes = value; }
}
public byte[] ciphertextbytes
{
get { return m_ciphertextbytes; }
set { m_ciphertextbytes = value; }
}
public string passPhrase
{
get { return m_passPhrase; }
set { m_passPhrase = value; }
}
public string saltValue
{
get { return m_saltValue; }
set { m_saltValue = value; }
}
public string hashAlgorithm
{
get { return m_hashAlgorithm; }
set { m_hashAlgorithm = value; }
}
public Int32 passwordIterations
{
get { return m_passwordIterations; }
set { m_passwordIterations = value; }
}
public string initVector
{
get { return m_initVector; }
set { m_initVector = value; }
}
public Int32 keySize
{
get { return m_keySize; }
set { m_keySize = value; }
}
public string ASCIIEncrypt(string plaintext2)
{
try
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(m_initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(m_saltValue);
byte[] plainTextBytes = Encoding.ASCII.GetBytes(plaintext2);
PasswordDeriveBytes password = new PasswordDeriveBytes(m_passPhrase, saltValueBytes, m_hashAlgorithm, m_passwordIterations);
byte[] keyBytes = password.GetBytes(m_keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
m_ciphertext = Convert.ToBase64String(cipherTextBytes);
return "SUCCESS";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
public string ASCIIDecrypt(string ciphertext2)
{
try
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(m_initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(m_saltValue);
byte[] cipherTextBytes = Convert.FromBase64String(ciphertext2);
PasswordDeriveBytes password = new PasswordDeriveBytes(m_passPhrase, saltValueBytes, m_hashAlgorithm, m_passwordIterations);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
m_plaintext = Encoding.ASCII.GetString(plainTextBytes);
return "SUCCESS";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
}
So append to the qyerstring the ASCIIEncrypt("yourquerstring without encryption string") and when reading read the normal qs paramaters again and compare the hash in the qs to the result.
Related
return System.Text.ASCIIEncoding.ASCII.GetString(ence); - the name 'ence' does not exist in the current context.
I am trying to decrypt text from a file that I am already encrypt.
public static string Decrypte(string encrypted)
{
var Check = Form1.verify;
string password = Form1.password;
if (Check == password)
{
byte[] textBytes = Convert.FromBase64String(encrypted);
AesCryptoServiceProvider endec = new AesCryptoServiceProvider();
endec.BlockSize = 128;
endec.KeySize = 256;
endec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
endec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
endec.Mode = CipherMode.CBC;
ICryptoTransform icrypt = endec.CreateDecryptor(endec.Key, endec.IV);
byte[] ence = icrypt.TransformFinalBlock(textBytes, 0, textBytes.Length);
icrypt.Dispose();
return Convert.ToString(ence);
}
if (Form1.verify == password)
{
return System.Text.ASCIIEncoding.ASCII.GetString(ence);
}
else if (Form1.verify != password)
{
MessageBox.Show("Use originas key file");
}
return encrypted;
}
I am getting above mentioned error during a hybrid cryptography implementation.
as per https://en.wikipedia.org/wiki/Hybrid_cryptosystem
I am just stucked at the last step
My code is
private void button1_Click(object sender, EventArgs e)
{
try
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(2048, cspParams);
string publicKey =lblPublicKey.Text = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));
string privateKey = lblPrivateKey.Text= Convert.ToBase64String(rsaProvider.ExportCspBlob(true));
string symmericKey = txtBoxSymmetricKey.Text = "Kamran12";
txtEncryptedData.Text = EncryptData(txtInputData.Text, symmericKey);
txtBoxEncryptedSymmetricKey.Text = RSA_Encrypt(symmericKey, publicKey);
txtBoxDescryptedSymmetricKey.Text = RSA_Decrypt(txtBoxEncryptedSymmetricKey.Text, privateKey);
txtDecryptedData.Text = DecryptData(txtEncryptedData.Text, txtBoxDescryptedSymmetricKey.Text); //getting error length of the data to decrypt is invalid
}
catch (Exception exc)
{
}
}
public static string RSA_Decrypt(string encryptedText, string privateKey)
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey));
var buffer = Convert.FromBase64String(encryptedText);
byte[] plainBytes = rsaProvider.Decrypt(buffer, false);
string plainText = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length);
return plainText;
}
public static string RSA_Encrypt(string data, string publicKey)
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey));
byte[] plainBytes = Encoding.UTF8.GetBytes(data);
byte[] encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
return Convert.ToBase64String(encryptedBytes);
}
public string EncryptData(string data, string key)
{
string encryptedData = null;
byte[] buffer = Encoding.UTF8.GetBytes(data);
DESCryptoServiceProvider desCryptSrvckey = new DESCryptoServiceProvider
{
Key = new UTF8Encoding().GetBytes(key)
};
desCryptSrvckey.IV = desCryptSrvckey.Key;
using (MemoryStream stmCipherText = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(stmCipherText, desCryptSrvckey.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
cs.FlushFinalBlock();
encryptedData = Encoding.UTF8.GetString(stmCipherText.ToArray());
}
}
return encryptedData;
}
public string DecryptData(string data, string key)
{
byte[] encryptedMessageBytes = Encoding.UTF8.GetBytes(data);
string decryptedData = null;
DESCryptoServiceProvider desCryptSrvckey = new DESCryptoServiceProvider
{
Key = new UTF8Encoding().GetBytes(key)
};
desCryptSrvckey.IV = desCryptSrvckey.Key;
using (MemoryStream encryptedStream = new MemoryStream(encryptedMessageBytes))
{
using (
CryptoStream cs = new CryptoStream(encryptedStream, desCryptSrvckey.CreateDecryptor(),
CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decryptedData = sr.ReadToEnd();
}
}
}
return decryptedData;
}
You declare encryptedData as a string. This is incorrect. Your encrypted data is bytes, not a character string. Attempting to convert raw bytes to UTF-8 text, as in encryptedData = Encoding.UTF8.GetString(stmCipherText.ToArray()); will not result in UTF-8 text but give you garbage and possibly lose data.
If you want the output from your encryption to be as text, then take the cyphertext bytes and use Convert.ToBase64String() to turn them into a text string.
When decrypting, convert the Base64 string back into bytes and decrypt the bytes.
This question already has answers here:
Encrypting & Decrypting a String in C# [duplicate]
(7 answers)
Closed 6 years ago.
public string EncryptPwd(String strString)
{
int intAscii;
string strEncryPwd = "";
for (int intIndex = 0; intIndex < strString.ToString().Length; intIndex++)
{
intAscii = (int)char.Parse(strString.ToString().Substring(intIndex, 1));
intAscii = intAscii + 5;
strEncryPwd += (char)intAscii;
}
return strEncryPwd;
}
This is my code.Please suggest me it is right way or not.
you can use this code:
Encrypt string with password:
public static string EncryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(Message);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
and Decrypt String with password:
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
// Step 5. Bat dau giai ma chuoi
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
catch (Exception) { Results = DataToDecrypt; }
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
Do you have a way to decrypt that? Here is another answer on SO
private static readonly UTF8Encoding Encoder = new UTF8Encoding();
public static string Encrypt(string unencrypted)
{
if (string.IsNullOrEmpty(unencrypted))
return string.Empty;
try
{
var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));
if (encryptedBytes != null && encryptedBytes.Length > 0)
return HttpServerUtility.UrlTokenEncode(encryptedBytes);
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
public static string Decrypt(string encrypted)
{
if (string.IsNullOrEmpty(encrypted))
return string.Empty;
try
{
var bytes = HttpServerUtility.UrlTokenDecode(encrypted);
if (bytes != null && bytes.Length > 0)
{
var decryptedBytes = MachineKey.Unprotect(bytes);
if(decryptedBytes != null && decryptedBytes.Length > 0)
return Encoder.GetString(decryptedBytes);
}
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
I agree with all the previous answers (especially share pvv) but in case you really did want a Caesar Cipher (Caesar Cipher is a very weak encryption and should not be used in production), and if this is a learning exercise, then here is some code
string strString = "abcdefghijklmnopqrstuvwxyz";
string enc = String.Join("", strString.ToArray().Select(x =>(char)( 'a' + (x-'a'+5)%26)));
Console.WriteLine(enc);
Or using a for loop like you did
string strEncryPwd = "";
for (int index = 0; index < strString.ToString().Length; index++)
{
int plainChar = strString[index];
int encrypted = 'a' + (plainChar - 'a' + 5) % 26;
strEncryPwd += (char)encrypted;
}
Console.WriteLine(strEncryPwd);
Why it does get wrong results?
It not pkcs7 supported by the crypto ++?
I would like to know the value of the result to be like what to do.
Iv value is equal to the supposed well-delivered.
// c# code
private byte[] _iv;
private readonly string key = "7794b12op901252bfcea66d6f0521212";
public string decrypt(string Input)
{
string str = "";
RijndaelManaged managed = new RijndaelManaged();
managed.KeySize = 128;
managed.BlockSize = 128;
managed.Mode = CipherMode.CBC;
managed.Padding = PaddingMode.Zeros;
managed.Key = Encoding.UTF8.GetBytes(this.key);
managed.IV = this._iv;
try
{
ICryptoTransform transform = managed.CreateDecryptor();
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
byte[] buffer = Convert.FromBase64String(Input);
stream2.Write(buffer, 0, buffer.Length);
}
bytes = stream.ToArray();
}
str = Encoding.ASCII.GetString(bytes);
}
catch (Exception)
{
}
return str;
}
public string encrypt(string Input)
{
RijndaelManaged managed = new RijndaelManaged();
managed.KeySize = 128;
managed.BlockSize = 128;
managed.Mode = CipherMode.CBC;
managed.Padding = PaddingMode.Zeros;
managed.Key = Encoding.ASCII.GetBytes(this.key);
managed.GenerateIV();
this._iv = managed.IV;
ICryptoTransform transform = managed.CreateEncryptor(managed.Key, managed.IV);
byte[] inArray = null;
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
byte[] bytes = Encoding.UTF8.GetBytes(Input);
stream2.Write(bytes, 0, bytes.Length);
}
inArray = stream.ToArray();
}
return Convert.ToBase64String(inArray);
}
Below is qt5 code.
Omit details.
QT code
QString aeskey = "7794b12op901252bfcea66d6f0521212";
QString _iv;
void Cipher::GenerateIV()
{
AutoSeededRandomPool rnd;
byte iv3[AES::BLOCKSIZE];
rnd.GenerateBlock(iv3, AES::BLOCKSIZE);
QByteArray out((char*)iv3, AES::BLOCKSIZE);
_iv = out.toBase64();
}
QString Cipher::AESencrypt(QString Qstr_in)
{
string str_in = Qstr_in.toStdString();
string key = aeskey.toStdString();
GenerateIV();
string iv = _iv.toStdString();
string str_out;
CBC_Mode<AES>::Encryption encryption;
encryption.SetKeyWithIV((byte*)key.c_str(), key.length(), (byte*)iv.c_str());
StringSource encryptor(str_in, true,
new StreamTransformationFilter(encryption,
new Base64Encoder(
new StringSink(str_out)
// ,StreamTransformationFilter::PKCS_PADDING
,StreamTransformationFilter::ZEROS_PADDING
)
)
);
return QString::fromStdString(str_out);
}
QString Cipher::AESdecrypt(QString Qstr_in)
{
string str_in = Qstr_in.toStdString();
string key = aeskey.toStdString();
string iv = _iv.toStdString();
string str_out;
CBC_Mode<AES>::Decryption decryption;
decryption.SetKeyWithIV((byte*)key.c_str(), key.length(), (byte*)iv.c_str());
StringSource decryptor(str_in, true,
new Base64Decoder(
new StreamTransformationFilter(decryption,
new StringSink(str_out)
// ,StreamTransformationFilter::PKCS_PADDING
,StreamTransformationFilter::DEFAULT_PADDING
)
)
);
return QString::fromStdString(str_out);
}
I don't understand really what your question is and I can't really comment so here what I think:
ICryptoTransform transform = managed.CreateEncryptor(managed.Key, managed.IV);
ICryptoTransform transform = managed.CreateDecryptor();
Both need key and IV, or at least need to be the same....
Then you used once Rijndael then AES. You could use AES in you C# too.
A couple things jump out... In C# code, you do this:
private readonly string key = "7794b12op901252bfcea66d6f0521212";
...
managed.Key = Encoding.UTF8.GetBytes(this.key);
In Crypto++ code, you do this:
QString aeskey = "7794b12op901252bfcea66d6f0521212";
...
string key = aeskey.toStdString();
You need to HexDecode the string in Crypto++.
Also, GenerateIV Base64 encodes on the Qt side of things:
AutoSeededRandomPool rnd;
byte iv3[AES::BLOCKSIZE];
rnd.GenerateBlock(iv3, AES::BLOCKSIZE);
QByteArray out((char*)iv3, AES::BLOCKSIZE);
_iv = out.toBase64();
But C# uses a byte[] (presumably not Base64 encoded):
private byte[] _iv;
I have following code that works fine when I use a four letter word as input, E.g. “Test”. When the input is not a multiple of 4, it fails E.g. “MyTest”.
Eexception: Invalid length for a Base-64 char array.
QUESTIONS
Is it guaranteed that the encrypted result will be always compatible to a Unicode string (without any loss). If yes I can use UTF encoding instead of Base64? What's the difference between UTF8/UTF16 and Base64 in terms of encoding
How can add padding so that we get correct result (after decryption) even if the input is not a multiple of 4?
MAIN PRGORAM
class Program
{
static void Main(string[] args)
{
string valid128BitString = "AAECAwQFBgcICQoLDA0ODw==";
string inputValue = "MyTest";
string keyValue = valid128BitString;
byte[] byteValForString = Convert.FromBase64String(inputValue);
EncryptResult result = Aes128Utility.EncryptData(byteValForString, keyValue);
EncryptResult encyptedValue = new EncryptResult();
string resultingIV = "4uy34C9sqOC9rbV4GD8jrA==";
if (String.Equals(resultingIV,result.IV))
{
int x = 0;
}
encyptedValue.IV = resultingIV;
encyptedValue.EncryptedMsg = result.EncryptedMsg;
string finalResult = Convert.ToBase64String(Aes128Utility.DecryptData(encyptedValue, keyValue));
Console.WriteLine(finalResult);
if (String.Equals(inputValue, finalResult))
{
Console.WriteLine("Match");
}
else
{
Console.WriteLine("Differ");
}
Console.ReadLine();
}
}
AES Crypto UTILITY
public static class Aes128Utility
{
private static byte[] key;
public static EncryptResult EncryptData(byte[] rawData, string strKey)
{
EncryptResult result = null;
if (key == null)
{
if (!String.IsNullOrEmpty(strKey))
{
key = Convert.FromBase64String((strKey));
result = Encrypt(rawData);
}
}
else
{
result = Encrypt(rawData);
}
return result;
}
public static byte[] DecryptData(EncryptResult encryptResult, string strKey)
{
byte[] origData = null;
if (key == null)
{
if (!String.IsNullOrEmpty(strKey))
{
key = Convert.FromBase64String(strKey);
origData = Decrypt(Convert.FromBase64String(encryptResult.EncryptedMsg), Convert.FromBase64String(encryptResult.IV));
}
}
else
{
origData = Decrypt(Convert.FromBase64String(encryptResult.EncryptedMsg), Convert.FromBase64String(encryptResult.IV));
}
return origData;
}
private static EncryptResult Encrypt(byte[] rawData)
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
aesProvider.Key = key;
aesProvider.Mode = CipherMode.CBC;
aesProvider.Padding = PaddingMode.PKCS7;
aesProvider.IV = Convert.FromBase64String("4uy34C9sqOC9rbV4GD8jrA==");
using (MemoryStream memStream = new MemoryStream())
{
CryptoStream encStream = new CryptoStream(memStream, aesProvider.CreateEncryptor(), CryptoStreamMode.Write);
encStream.Write(rawData, 0, rawData.Length);
encStream.FlushFinalBlock();
EncryptResult encResult = new EncryptResult();
encResult.EncryptedMsg = Convert.ToBase64String(memStream.ToArray());
encResult.IV = Convert.ToBase64String(aesProvider.IV);
return encResult;
}
}
}
private static byte[] Decrypt(byte[] encryptedMsg, byte[] iv)
{
using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
{
aesProvider.Key = key;
aesProvider.IV = iv;
aesProvider.Mode = CipherMode.CBC;
aesProvider.Padding = PaddingMode.PKCS7;
using (MemoryStream memStream = new MemoryStream())
{
CryptoStream decStream = new CryptoStream(memStream, aesProvider.CreateDecryptor(), CryptoStreamMode.Write);
decStream.Write(encryptedMsg, 0, encryptedMsg.Length);
decStream.FlushFinalBlock();
return memStream.ToArray();
}
}
}
}
DTO
public class EncryptResult
{
public string EncryptedMsg { get; set; }
public string IV { get; set; }
}
REFERENCES:
How to create byte[] with length 16 using FromBase64String
Getting incorrect decryption value using AesCryptoServiceProvider
If you are encrypting, then encoding Base64 for me doesn't add anything useful, instead it brings the problems you face.
As for the padding, a solution i have seen is to create a new byte[] that is indeed a multiple of 4 and copy the source byte[] to that new byte[].
So, something like this:
if (rawdata.Length % 16 !=0)
{
newSource = new byte[source.Length + 16 - source.Length % 16];
Array.Copy(source, newSource, source.Length);
}
Base64 is a way of representing binary values as text so that you do not conflict with common control codes like \x0A for newline or \0 for a string terminator. It is NOT for turning typed text in to binary.
Here is how you should be passing the text in and getting it back out. You can replace UTF8 with whatever encoding you want, but you will need to make sure the Encoding.Whatever.GetBytes is the same encoding as the Encoding.Whatever.GetString
class Program
{
static void Main(string[] args)
{
string valid128BitString = "AAECAwQFBgcICQoLDA0ODw==";
string inputValue = "MyTest";
string keyValue = valid128BitString;
//Turns our text in to binary data
byte[] byteValForString = Encoding.UTF8.GetBytes(inputValue);
EncryptResult result = Aes128Utility.EncryptData(byteValForString, keyValue);
EncryptResult encyptedValue = new EncryptResult();
//(Snip)
encyptedValue.IV = resultingIV;
encyptedValue.EncryptedMsg = result.EncryptedMsg;
string finalResult = Encoding.UTF8.GetString(Aes128Utility.DecryptData(encyptedValue, keyValue));
Console.WriteLine(finalResult);
if (String.Equals(inputValue, finalResult))
{
Console.WriteLine("Match");
}
else
{
Console.WriteLine("Differ");
}
Console.ReadLine();
}
}