I am trying to encrypt / decrypt sensitive data such as SSN, the encryption process goes fine, saving in DB looks good too, retrieval looks good too, but when I am on the last step to decrypt the data I am getting error message: length of data to decrypt is invalid.
I created a SQL Server table for testing which has one column to hold the data, of varbinary type with size of 500.
This is how the data looks like in the table:
Now here is whole code in C# which is used to encrypt the data, insert in the db, get the last record (test) and decrypt. As I said the error happens on the last step in the decryption step:
Encryption Step
public byte[] EncryptStringToBytes(string plainText)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7;
string keyStr = "cGFzc3dvcmQAAAAAAAAAAA==";
string ivStr = "cGFzc3dvcmQAAAAAAAAAAA==";
byte[] ivArr = Convert.FromBase64String(keyStr);
byte[] keyArr = Convert.FromBase64String(ivStr);
rijAlg.Key = keyArr;
rijAlg.KeySize = 256;
rijAlg.BlockSize = 128;
rijAlg.IV = ivArr;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
SaveData(encrypted);
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
Saving data to database
public void SaveData(byte[] cipherText) {
string queryStmt = "INSERT INTO TestSSN(SSN) VALUES(#Content)";
using (SqlConnection _con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
using (SqlCommand _cmd = new SqlCommand(queryStmt, _con))
{
SqlParameter param = _cmd.Parameters.Add("#Content", SqlDbType.VarBinary);
param.Value = cipherText;
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
}
GetSSNData(1); }
Getting data from database
public byte[] GetSSNData(int id)
{
byte[] cipherData = new byte[500];
string queryStmt = "SELECT SSN FROM TestSSN WHERE ID=7";
using (SqlConnection _con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
using (SqlCommand _cmd = new SqlCommand(queryStmt, _con))
{
_con.Open();
SqlDataReader rdr = _cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
cipherData = Encoding.ASCII.GetBytes(rdr[0].ToString());
}
}
_con.Close();
}
string roundtrip = DecryptStringFromBytes(cipherData);
return cipherData;
}
Trying to decrypt the data(you will notice two different ways for decryption here, but I'll get the same message for both of them)
static string DecryptStringFromBytes(byte[] cipherText)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.PKCS7;
string keyStr = "cGFzc3dvcmQAAAAAAAAAAA==";
string ivStr = "cGFzc3dvcmQAAAAAAAAAAA==";
byte[] ivArr = Convert.FromBase64String(keyStr);
byte[] keyArr = Convert.FromBase64String(ivStr);
rijAlg.Key = keyArr;
rijAlg.KeySize = 256;
rijAlg.BlockSize = 128;
rijAlg.IV = ivArr;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
byte[] decryptedText = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
string decrpyted = ASCIIEncoding.UTF8.GetString(decryptedText);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// byte[] decryptedText = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
Advices more then welcome, I've been battling with the decryption whole day.
Thanks, Laziale
Check the place where you read your data from DB:
cipherData = Encoding.ASCII.GetBytes(rdr[0].ToString());
If rdr[0] is a byte array I don't think that you will get the string of bytes, probably you will get "System.Byte[]". And if you will get "0xFFAA" - Encoding.ASCII.GetBytes will not give you a byte array with { 0xFF, 0xAA } data. You should use SqlDataReader.GetBytes to read this data.
Also I want to remind you that SSN is sensitive information. You should inform your users that you are going to save this information. If you need this information just to verify identity - you can use last 4 digits or hash. Please consider to not save SSN if you don't have real justification for this.
Related
Using this method string GetfunddtlsEncrypted_res = TradeSmartGetFundDetails(uid, uid); I'm able to fetching the encrypted string
GetfunddtlsEncrypted_res = "1pGUvzzwv3Pg4O\/ZE6f8WSkkSWzymOZ4cBIVd\/ZkLC\/kCuZ9xkebaSB7htxDpcJSjGYe5eliUQIJrQaskpviN2E+uTN0EsC3tFd1h5QaIrTEz0vGIew16N33ecZo7oYNWmgR9aMp4BaZUDeqX3sVVg=="
After successfully fetch the above string I'm decoding using this method
if (!(GetfunddtlsEncrypted_res.Contains("\"status\":false")))
{
var Getfunddtlsdecryptedstr = DecryptPasswordAes(GetfunddtlsEncrypted_res);
TSGetFundDetails tSGetFundDetails = JsonConvert.DeserializeObject<TSGetFundDetails>(Getfunddtlsdecryptedstr);
}
Method Logic is :
public string DecryptPasswordAes(string encryptedString)
{
//Convert cipher text back to byte array
//byte[] cipherText = Convert.FromBase64String(encryptedString);
string strKey = "000fk15pvbbgmxgpej53298iu8nv555k";
//string iv = "000fk15pvbbgmxgpej53298iu8nv555k";
string iv = "7894561235789456";
encryptedString = encryptedString.Replace("\\", "").Replace("\"", "");
//1pGUvzzwv3Pg4O/ZE6f8WSkkSWzymOZ4cBIVd/ZkLC/kCuZ9xkebaSB7htxDpcJSjGYe5eliUQIJrQaskpviN2E+uTN0EsC3tFd1h5QaIrTEz0vGIew16N33ecZo7oYNWmgR9aMp4BaZUDeqX3sVVg==
//Convert cipher text back to byte array
byte[] cipherText = Convert.FromBase64String(encryptedString);
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an AesManaged object
// with the specified key and IV.
using (AesManaged aesAlg = new AesManaged())
{
// Create a decrytor to perform the stream transform.
aesAlg.Key = Encoding.ASCII.GetBytes(strKey);
aesAlg.IV = Encoding.ASCII.GetBytes(iv);
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
aesAlg.Padding = PaddingMode.None;
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd(); // Exception {Padding is invalid and cannot be removed}
}
}
}
}
return plaintext;
}
At the end of this line StreamReader srDecrypt = new StreamReader(csDecrypt) I'm getting the padding error.
Suggest me where I did the mistake and how can to achieve this.
I try to build simple AES encryption helper to encrypt/decrypt some strings
Fist, I have an issue with Padding mode wherein decryption it only accepts if Zero otherwise an error about padding occurs!
The second issue is when I try to encrypt simple string "Hello World," it got encrypted, and I have the base64 string, but when trying to decrypt, there's no error, but a weird unknown character is shown! like 㡲啁䎰廾ử靱㡲啁䎰廾ử靱
My code:
private static int keySizes = 256;
private static int blockSize = 128;
private static PaddingMode pMode = PaddingMode.Zeros;
private static CipherMode cMode = CipherMode.ECB;
private static byte[] key = GenEncryptionKey();
private const string passphrase = #"StartYourMorningWithASmile";
private static byte[] GenEncryptionKey()
{
HashAlgorithm hash = MD5.Create();
return hash.ComputeHash(Encoding.Unicode.GetBytes(passphrase));
}
private static AesManaged CreateCryptor()
{
AesManaged cryptor = new AesManaged();
cryptor.KeySize = keySizes;
cryptor.BlockSize = blockSize;
cryptor.Padding = pMode;
cryptor.Key = key;
cryptor.Mode = cMode;
cryptor.GenerateIV();
return cryptor;
}
public static string EncryptParams(string reqVal)
{
string cipherText = "";
if (string.IsNullOrEmpty(reqVal) || reqVal.Length < 1)
throw new ArgumentNullException();
byte[] plainBytes = Encoding.Unicode.GetBytes(reqVal);
using (var cryptor = CreateCryptor())
{
ICryptoTransform encryptor = cryptor.CreateEncryptor();
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(plainBytes, 0, plainBytes.Length);
}
byte[] cipherBytes = ms.ToArray();
cipherText = Convert.ToBase64String(cipherBytes);
}
cryptor.Clear();
}
return cipherText;
}
public static string DecryptParams(string resVal)
{
var data = Convert.FromBase64String(resVal);
byte[] cipherBytes = new byte[data.Length];
string plainText = "";
using (var crypto = CreateCryptor())
{
ICryptoTransform Dec = crypto.CreateDecryptor();
using (MemoryStream ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, Dec, CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
plainText = Encoding.Unicode.GetString(ms.ToArray());
}
}
crypto.Clear();
}
return plainText;
}
UPDATE 1:
Please set also the IV yourself to achieve successful decryption, as #maarten-bodewes pointed out. I missed that part and the decryption somehow worked (?) with your existing code, but you always should provide the same key and IV to a symmetric encryption algorithm to have it work both ways.
ORIGINAL ANSWER:
Your decryption fails (produces incorrect results) because you implemented the decryption part incorrectly (by using CryptoStreamMode.Write instead of CryptoStreamMode.Read) and besides feeding the decryption stream all zero bytes
At the point of execution of
cs.Write(cipherBytes, 0, cipherBytes.Length);
the variable cipherBytes is all zero. The real encrypted buffer is in the data variable which you only use to set the length of cipherBytes
So change your decryption method to this.
BONUS: After correcting the decryption part, you can specify the padding as you wish! I tested with PKCS7 and it is ok.
public static string DecryptParams(string resVal)
{
var cipherBytes = Convert.FromBase64String(resVal);
string plainText = "";
using (var crypto = CreateCryptor())
{
ICryptoTransform Dec = crypto.CreateDecryptor();
using (MemoryStream ms = new MemoryStream(cipherBytes))
{
using (var cs = new CryptoStream(ms, Dec, CryptoStreamMode.Read))
{
byte[] decryptBlock = new byte[4096];
MemoryStream decryptStream = new MemoryStream();
int readBytes;
while ((readBytes = cs.Read(decryptBlock, 0, 4096)) > 0)
{
decryptStream.Write(decryptBlock, 0, readBytes);
}
plainText = Encoding.Unicode.GetString(decryptStream.ToArray());
}
}
crypto.Clear();
}
return plainText;
}
Hope this helps.
Thanks to Oguz
Below is my description method after edit
public static string DecryptParams(string resVal)
{
var data = Convert.FromBase64String(resVal);
byte[] cipherBytes = new byte[data.Length];
string plainText = "";
using (var crypto = CreateCryptor())
{
ICryptoTransform Dec = crypto.CreateDecryptor();
using (MemoryStream ms = new MemoryStream(data))
{
using (var cs = new CryptoStream(ms, Dec, CryptoStreamMode.Read))
{
cs.Read(cipherBytes, 0, cipherBytes.Length);
plainText = Encoding.Unicode.GetString(cipherBytes.ToArray());
}
}
crypto.Clear();
}
return plainText;
}
one more thing about the return result after the decryption I got the original string plus \0\0\0\0 so I use myString.TrimEnd('\0') to solve that.
i have a problem, i tried to fix it myself but i cant.
My program search als .txt files from a directory. Then it read the files and encrypt each file and overwrite the old file. That works fine. Now i want to decrypt the txt files, the following happens:
Here you can see the encrypted text and the decrypted text
So the Problem is, the .txt file becomes encrypted, and the decryption works too, but when i decrypt there dont come the original text. You can see it on the picture, there are coming only wired letters. I cant understand why, i use the same salt and the same password.
Here is my code:
The first 3 snippets are for encryption, the other 3 for decryption.
foreach (var file in d2.GetFiles("*.txt"))
{
Console.WriteLine(file.FullName, file.Name);
string temppfad = file.FullName;
StreamReader sr = new StreamReader(temppfad);
string Inhalt = sr.ReadToEnd();
Console.WriteLine(Inhalt + "\n");
string Verschlüsselterinhalt = Verschlüsseln(Password, Inhalt);
sr.Close();
File.WriteAllText(temppfad, Verschlüsselterinhalt);
}
These Part is still working, just upload it to understand it better.
The encryption parts:
static string Verschlüsseln(string PW, string original)
{
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.GenerateKey();
myRijndael.GenerateIV();
byte[] salt = Encoding.ASCII.GetBytes("0PQUX76U0adfaDADFexA888887Dz3J3X");
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(PW, salt);
myRijndael.Key = key.GetBytes(myRijndael.KeySize / 8);
myRijndael.IV = key.GetBytes(myRijndael.BlockSize / 8);
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
StringBuilder s = new StringBuilder();
foreach (byte item in encrypted)
{
s.Append(item.ToString("X2") + " ");
}
Console.WriteLine("Encrypted: " + s + "\n\n");
return s.ToString();
}
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.Zeros;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
I think to that point all is ok, now I will post the decryption parts.
foreach (var file in d2.GetFiles("*.txt"))
{
Console.WriteLine(file.FullName, file.Name);
string temppfad = file.FullName;
StreamReader sr = new StreamReader(temppfad);
string Inhalt = sr.ReadToEnd();
Console.WriteLine("Inhalt: " + Inhalt + "\n");
string Entschlüsselterinhalt = Entschlüsseln(Password, Inhalt);
sr.Close();
File.WriteAllText(temppfad, Entschlüsselterinhalt);
}
static string Entschlüsseln(string PW, string original)
{
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.GenerateKey();
myRijndael.GenerateIV();
byte[] salt = Encoding.ASCII.GetBytes("0PQUX76U0adfaDADFexA888887Dz3J3X");
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(PW, salt);
myRijndael.Key = key.GetBytes(myRijndael.KeySize / 8);
myRijndael.IV = key.GetBytes(myRijndael.BlockSize / 8);
// Decrypt the bytes to a string.
byte[] originalbytes = Encoding.ASCII.GetBytes(original);
string decrypted = DecryptStringFromBytes(originalbytes, myRijndael.Key, myRijndael.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Decrypted: " + decrypted);
return decrypted;
}
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.Zeros;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
I would be very happy when someone could help me.
UPDATE!!!
I edited now my code, now it looks so:
foreach (var file in d2.GetFiles("*.txt"))
{
Console.WriteLine(file.FullName, file.Name);
string temppfad = file.FullName;
StreamReader sr = new StreamReader(temppfad);
string Inhalt = sr.ReadToEnd();
Console.WriteLine(Inhalt + "\n");
byte[] Verschlüsselterinhalt = Verschlüsseln(Password, Inhalt);
sr.Close();
File.WriteAllBytes(temppfad, Verschlüsselterinhalt);
}
static byte[] Verschlüsseln(string PW, string original)
{
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
byte[] salt = Encoding.ASCII.GetBytes("0PQUX76U0adfaDADFexA888887Dz3J3X");
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(PW, salt);
myRijndael.Key = key.GetBytes(myRijndael.KeySize / 8);
myRijndael.IV = key.GetBytes(myRijndael.BlockSize / 8);
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
return encrypted;
}
}
I think that part is ok, now on decryption i get an error
foreach (var file in d2.GetFiles("*.txt"))
{
Console.WriteLine(file.FullName, file.Name);
string temppfad = file.FullName;
StreamReader sr = new StreamReader(temppfad);
string Inhalt = sr.ReadToEnd();
Console.WriteLine("Inhalt: " + Inhalt + "\n");
string Entschlüsselterinhalt = Entschlüsseln(Password, Inhalt);
sr.Close();
File.WriteAllText(temppfad, Entschlüsselterinhalt);
}
static string Entschlüsseln(string PW, string original)
{
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
byte[] salt = Encoding.ASCII.GetBytes("0PQUX76U0adfaDADFexA888887Dz3J3X");
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(PW, salt);
myRijndael.Key = key.GetBytes(myRijndael.KeySize / 8);
myRijndael.IV = key.GetBytes(myRijndael.BlockSize / 8);
// Decrypt the bytes to a string.
byte[] originalbytes = Encoding.ASCII.GetBytes(original);
string decrypted = DecryptStringFromBytes(originalbytes, myRijndael.Key, myRijndael.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Decrypted: " + decrypted);
return decrypted;
}
}
The error comes here:
Errormessage
Here there full code:
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.Zeros;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
Greetings
The issue is you are messing with the encrypted text by doing this
StringBuilder s = new StringBuilder();
foreach (byte item in encrypted)
{
s.Append(item.ToString("X2") + " ");
}
As Damien mentioned you should return a byte array from static string Verschlüsseln(string PW, string original) and use File.WriteAllBytes to write it to file. You can then use File.ReadAllBytes to read it from the file and pass a byte[] into you're decrypt method and you don't need to do anything to do with encoding.
SOLVED
Thank you for your much help, my last error was pretty easy, just a little mistake, here the solution of the part where was the error:
foreach (var file in d2.GetFiles("*.txt"))
{
Console.WriteLine(file.FullName, file.Name);
string temppfad = file.FullName;
byte[] Inhaltsbyte = File.ReadAllBytes(temppfad);
string Entschlüsselterinhalt = Entschlüsseln(Password, Inhaltsbyte);
File.WriteAllText(temppfad, Entschlüsselterinhalt);
}
I'm trying to read a file, encrypt it, and send it to a server over socket, where it is written. And then the other way around, read it on server, send it to client, decrypt it, and write it again.
My problem using C# Aes class is, that the input size doesn't equal the output size.
For example, when I read 4096 bytes from the file, the output size is 4112 bytes, 16 bytes more. OK, so 4112 bytes are sent and written on the server, but when I get the file again, I can only send a maximum of 4096 bytes over the socket, and then, of course, the decrypt function on client throws an exception, that the padding is invalid and cannot be removed. Sure I could try to read less bytes on the client, but that doesn't work as well.
I'm a very experienced C++ programmer, and I've done this with OpenSsl, and it worked like a charm. The input size has been always the output size, I don't know what is wrong with my functions in C#.
this is the sending part:
byte[] SendData = new byte[4096];
iBytesRead = FileRead.Read (SendData, 0, 4096);
SendData = aes.encrypt (Encoding.Default.GetString (SendData, 0, iBytesRead), iBytesRead);
String a = aes.decrypt (SendData); // no problems here because the size is correct
Socket.sendB (SendData, SendData.Length);
and the part of receiving from server:
byte[] WriteData = new byte[4096],
Temp;
if ((iBytesReceived = Socket.receiveB (ref WriteData)) == 0)
break;
if (Encoding.ASCII.GetString (WriteData, 0, iBytesReceived) == "end")
break;
for (uint i = 0; i < iBytesReceived; i++)
Temp[i] = WriteData[i];
byte[] a = Encoding.Default.GetBytes (aes.decrypt (Temp));
FileWrite.Write (a, 0, Temp.Length);
Aes functions:
public byte[] encrypt(String _InStr, int _InStrLength)
{
if (!bKeySet)
return ErrorReturn;
byte[] encrypted;
using (Aes aes = Aes.Create ())
{
aes.Key = Key;
aes.IV = IV;
//aes.Padding = PaddingMode.PKCS7;
//aes.BlockSize = 128;
//aes.KeySize = 128;
//aes.Mode = CipherMode.CFB;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
// Create the streams used for encryption.
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(_InStr);
}
}
ms.Close ();
encrypted = ms.ToArray ();
}
}
return encrypted;
}
public String decrypt(byte[] _InStr)
{
if (!bKeySet)
return "";
String plaintext;
using (Aes aes = Aes.Create ())
{
aes.Key = Key;
aes.IV = IV;
//aes.Padding = PaddingMode.PKCS7;
//aes.BlockSize = 128;
//aes.KeySize = 128;
//aes.Mode = CipherMode.CBC;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(_InStr))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd ();
}
}
}
}
return plaintext;
}
As it was said, if any padding is used, the output will be aligned to a block size. However .Net doesn't want to work with incomplete blocks when PaddingMode.None is used. You should pad data yourself before encryption(decryption) and remove added bytes after.
One of the way to do this is to wrap ICryptoTransform passed to a CryptoStream
I have taken the decrypt code from http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream.aspx and modified it as follows below. I have an encrypted example, and it works just fine while decoding. But when using the encryption function, it returns junk string with strange symbols. below are the functions of encrypt/decrypt.
An example of encrypted string "hey" : "???U?b???z?Y???"
When decoded again: "ûc{ÁpÅ`ñ""Â"
I'm using this code to convert the byte array to string:
private string ByteArrayToString(byte[] input)
{
ASCIIEncoding dec = new ASCIIEncoding();
return dec.GetString(input);
}
here are the encrypt/decrypt functions. the decryption function is working fine.
private string DecryptStringFromBytesAes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged aesAlg = new RijndaelManaged())
{
aesAlg.Key = Key;
aesAlg.Padding = PaddingMode.Zeros;
aesAlg.Mode = CipherMode.ECB;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
private byte[] EncryptStringToBytesAes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged aesAlg = new RijndaelManaged())
{
aesAlg.Key = Key;
aesAlg.Padding = PaddingMode.Zeros;
aesAlg.Mode = CipherMode.ECB;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
What you observe is the problem of mapping arbitrary bytes (in the range 0-255) to characters. Meaningful characters are only in the range 32-255 or even only 32-127 (ASCII). Values below 32 are the so-called non-printable characters and values above 127 are dependent on the character encoding you are using. That's why the crypted text looks like junk. Mast crypto-systems therefore transform the bytes into the sensible ASCII-range. One such algorithm is BASE64. So mangling the crypted bytes through BASE64 gives characters that are all printable and that will go without problems through e-mail. Before decrypting you then have to undo the BASE64 encoding.
Another way to make the encrypted result look better is to show the hexa-decimal representation of it. For example if you have a byte value of 15 you print 0F. You may use this to represent your byte array in hex:
private string ByteArrayToHexString(byte[] data)
{
return String.Concat(data.Select(b => b.ToString("x2")));
}
In order to have your output as a hexadecimal encoding of the data, follow the methods found here. I modified them slightly to be extension methods:
public static string ToHexString(this byte[] bytes)
{
return bytes == null ? string.Empty : BitConverter.ToString(bytes).Replace("-", string.Empty);
}
public static byte[] FromHexString(this string hexString)
{
if (hexString == null)
{
return new byte[0];
}
var numberChars = hexString.Length;
var bytes = new byte[numberChars / 2];
for (var i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
}
return bytes;
}
Encrypted strings will look like garble. The way to test if the encryption is working correctly is to pass your string back through decrypt. If it works at decrypting then you know the string is correct despite looking like garbage to you.