I am trying to create a simple system that encrypts strings, converts the encrypted byte array to a string and stores it in the database. Later on, the values can be retrieved from the database (as strings), comverted to byte arrays, decrypted and then converted to strings again. I am also using a 256 bit key. However, I seem to be doing something wrong and I am not familiar enough with the concept to come up with a fix.
Encryption code:
private static string EncryptString(SymmetricAlgorithm symAlg, string inString)
{
byte[] inBlock = Encoding.Unicode.GetBytes(inString);
ICryptoTransform xfrm = symAlg.CreateEncryptor();
return Convert.ToBase64String(xfrm.TransformFinalBlock(inBlock, 0, inBlock.Length));
}
Decryption code:
private static byte[] DecryptString(SymmetricAlgorithm symAlg, string inBytes)
{
ICryptoTransform xfrm = symAlg.CreateDecryptor();
return xfrm.TransformFinalBlock(Convert.FromBase64String(inBytes), 0, inBytes.Length);
}
The error I am getting when decrypting:
System.ArgumentOutOfRangeException: Attempt to transform beyond end of buffer.
Parameter name: inputCount
at
System.Security.Cryptography.CapiSymmetricAlgorithm.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at
CDMEncryptionLibrary.SyncEncryption.SecureCDM.DecryptString(SymmetricAlgorithm symAlg, String inBytes)
I understand that the problem is the conversion from and to bytes but how can I solve it?
--Edit
Decryption code is now:
private static string DecryptString(SymmetricAlgorithm symAlg, string inBytesString)
{
var inBytes = Convert.FromBase64String(inBytesString);
ICryptoTransform xfrm = symAlg.CreateDecryptor();
byte[] outBlock= xfrm.TransformFinalBlock(inBytes, 0, inBytes.Length);
return Encoding.Unicode.GetString(outBlock);
}
with error The input data is not a complete block.