C# getting error on decrypting byte[] from a file - c#

I wrote this code to encrypt a text and write the encrypted text to a file and then decrypt it from the file. But I get this exception: System.Security.Cryptography.CryptographicException: 'The input data is not a complete block.' When I use a byte[] for storing data, it works perfect but it seems that it cant correctly convert a file to byte[]. I also tried File.ReadAllBytes but I got the same error. Please Help me.
class Program
{
static void Main(string[] args)
{
string decrypted;
byte[] encrypted;
Console.Write("Enter a text to encrypt : ");
string plaintext = Console.ReadLine();
using (Aes aes = Aes.Create())
{
encrypted = AesEncryption.Encrypt(plaintext, aes);
File.WriteAllText(#"C:\Users\sepita\Desktop\My.txt", Encoding.UTF8.GetString(encrypted), Encoding.UTF8);
decrypted = AesEncryption.Decrypt(Encoding.UTF8.GetBytes(File.ReadAllText(#"C:\Users\sepita\Desktop\My.txt")), aes);
}
Console.WriteLine($"Encrypted : {Encoding.UTF8.GetString(encrypted)}");
Console.WriteLine($"Decrypted : {decrypted}");
}
}
static class AesEncryption
{
public static byte[] Encrypt(string plaintext, Aes aes)
{
byte[] encrypted;
ICryptoTransform encryptor = aes.CreateEncryptor();
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream stream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(plaintext);
}
encrypted = memoryStream.ToArray();
}
}
return encrypted;
}
public static string Decrypt(byte[] encrypted, Aes aes)
{
string decrypted = null;
ICryptoTransform decryptor = aes.CreateDecryptor();
using (MemoryStream memoryStream = new MemoryStream(encrypted))
{
using (CryptoStream stream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(stream))
{
decrypted = reader.ReadToEnd();
}
}
}
return decrypted;
}
}

The result of your Encrypt function is binary data. It would be pure luck if this were a valid UTF8 string, so Encoding.UTF8.GetString(encrypted) will not work in general.
Replacing it by
File.WriteAllBytes(#"C:\Users\sepita\Desktop\My.bin", encrypted);
decrypted = AesEncryption.Decrypt(File.ReadAllBytes(#"C:\Users\sepita\Desktop\My.bin"), aes);
will work.
If you want a text file, use BASE64 conversion on the binary data:
File.WriteAllText(#"C:\Users\sepita\Desktop\My.txt", Convert.ToBase64String(encrypted));
decrypted = AesEncryption.Decrypt(Convert.FromBase64String(File.ReadAllText(#"C:\Users\sepita\Desktop\My.txt")), aes);

Related

C# - Problem with AES Decryption - always get null

I am trying to implement image steganography with LSB and everything works except decrypting.
There is my class responsible for encryption and decryption of strings below. Encrypting works fine but Decrypt method always returns null:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp1
{
class Encryptor {
//text to encrypt or already decrypted
private String decryptedText = "";
//text to decrypt or already encrypted
private String encryptedText = "";
private String key = "";
public Encryptor setDecryptedText(String text)
{
decryptedText = text;
return this;
}
public Encryptor setEncryptedText(String text)
{
encryptedText = text;
return this;
}
public Encryptor setKey(String text)
{
key = text;
return this;
}
Byte[] getHash(Byte[] hash)
{
Byte[] newHash = new Byte[32];
for (int i = 0; i < 32; i++)
{
newHash[i] = hash[i];
}
return newHash;
}
Byte[] getIV(Byte[] hash)
{
Byte[] newHash = new Byte[16];
int j = 0;
for (int i = 32; i < 48; i++)
{
newHash[j++] = hash[i];
}
return newHash;
}
String EncryptAesManaged()
{
SHA512 shaM = new SHA512Managed();
Byte[] data = Encoding.UTF8.GetBytes(key);
Byte[] hash = shaM.ComputeHash(data);
try
{
return Encrypt(decryptedText, getHash(hash), getIV(hash));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
String DecryptAesManaged()
{
SHA512 shaM = new SHA512Managed();
var data = Encoding.UTF8.GetBytes(key);
Byte[] hash = shaM.ComputeHash(data);
try
{
return Decrypt(Convert.FromBase64String(encryptedText), getHash(hash), getIV(hash));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "";
}
String Encrypt(string plainText, byte[] Key, byte[] IV)
{
Byte[] encrypted;
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.Mode = CipherMode.CBC;
aes.BlockSize = 128;
aes.KeySize = 256;
ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs)) {
sw.Write(Encoding.UTF8.GetBytes(plainText));
cs.FlushFinalBlock();
encrypted = ms.ToArray();
}
}
}
aes.Clear();
}
return Convert.ToBase64String(encrypted);
}
string Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
{
string plaintext = null;
using (RijndaelManaged aes = new RijndaelManaged())
{
aes.Mode = CipherMode.CBC;
aes.BlockSize = 128;
aes.KeySize = 256;
ICryptoTransform decryptor = aes.CreateDecryptor(Key, IV);
try
{
using (MemoryStream ms = new MemoryStream(cipherText))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (StreamReader reader = new StreamReader(cs))
{
plaintext = reader.ReadToEnd(); //Here get null
}
aes.Clear();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return plaintext;
}
public String getEncrypted()
{
return EncryptAesManaged();
}
public String getDecrypted()
{
return DecryptAesManaged();
}
}
}
Why is Decrypt() returning null rather than the originally encrypted string?
You don't show how you use your Encryptor class, so your question doesn't quite include a Minimal, Complete, and Verifiable example. I was able to reproduce the problem with the following test harness:
public static void Test()
{
var key = "my key";
var plainText = "hello";
var encryptor = new Encryptor();
encryptor.setDecryptedText(plainText);
encryptor.setKey(key);
var encrypted = encryptor.getEncrypted();
Console.WriteLine(encrypted);
var deecryptor = new Encryptor();
deecryptor.setEncryptedText(encrypted);
deecryptor.setKey(key);
var decrypted = deecryptor.getDecrypted();
Console.WriteLine(decrypted);
Assert.IsTrue(plainText == decrypted);
}
Demo fiddle #1 here.
Given that, your code has 2 problems, both of which are actually in encryption rather than decryption.
Firstly, in Encrypt(string plainText, byte[] Key, byte[] IV), you are writing to the StreamWriter sw, then flushing the CryptoStream and returning the MemoryStream contents -- but you never flush or dispose sw, so its buffered contents are never forwarded to the underlying stream(s).
To fix this, your code should looks something like:
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(Encoding.UTF8.GetBytes(plainText));
}
}
encrypted = ms.ToArray();
}
Now getDecrypted() no longer returns a null result -- but instead returns a wrong result of "System.Byte[]", as shown in demo fiddle #2 here.
Secondly, again in Encrypt(...), you are effectively encoding your plainText twice at this line:
sw.Write(Encoding.UTF8.GetBytes(plainText));
Encoding.UTF8.GetBytes(plainText) converts the plain text to a byte array, but the StreamWriter is also intended to do this job, converting strings to bytes and passing them to the underlying stream. So, since you are not passing a string to Write(), the overload that gets called is StreamWriter.Write(Object):
Writes the text representation of an object to the text string or stream by calling the ToString() method on that object.
Thus what actually gets encrypted is the ToString() value of a byte array, which is "System.Byte[]".
To fix this, simply remove the call to Encoding.UTF8.GetBytes(plainText) and write the string directly. Thus your Encrypt() method should now look like:
static String Encrypt(string plainText, byte[] Key, byte[] IV)
{
string encrypted;
using (var aes = new RijndaelManaged())
{
aes.Mode = CipherMode.CBC;
aes.BlockSize = 128;
aes.KeySize = 256;
ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write, true))
{
using (var sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
}
// Calling GetBuffer() avoids the extra allocation of ToArray().
encrypted = Convert.ToBase64String(ms.GetBuffer(), 0, checked((int)ms.Length));
}
aes.Clear();
}
return encrypted;
}
Demo fiddle #3 here that now passes successfully.
Disclaimer: this answer does not attempt to to review your code for security best practices such as secure setup of salt and IV.

AES pads byte array with \0 when decrypting

Whenever I decrypt a file I end up with \0 in between each character (this is a text file) The original is fine, and the decryption is successful without errors.
When I do open the file ; "hello" would become "h\0e\0l\0..."
Here is my decryption function: (I came up with a fix of converting the byte array to utf8 then manually removing the nulls, this is obviously not a solution. )
public static void DecryptFileToFile(String fromFile, String toFile, byte[] Key)
{
byte[] encryptedFile = IO.convertFileToByte(fromFile);
using (Aes aesAlg = Aes.Create())
{
byte[] dataIV = encryptedFile.Take(16).ToArray(); //first 16 bytes is iv
byte[] encryptedData = encryptedFile.Skip(16).Take(encryptedFile.Length-16).ToArray();
aesAlg.Key = Key;
using (var decryptor = aesAlg.CreateDecryptor(Key, dataIV))
{
byte[] final = PerformCryptography(decryptor, encryptedData);
string result = System.Text.Encoding.UTF8.GetString(final);
result = result.Replace("\0", string.Empty);
IO.writeStringToFile(result,toFile);
}
}
}
private static byte[] PerformCryptography(ICryptoTransform cryptoTransform, byte[] data)
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(data, 0, data.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
to encrypt:
public static void EncryptFileToFile(String fromFile, String toFile, byte[] Key){
byte[] original = IO.convertFileToByte(fromFile);
using (Aes aesAlg = Aes.Create())
{
aesAlg.GenerateIV();
aesAlg.Key = Key;
using (var encryptor = aesAlg.CreateEncryptor(Key, aesAlg.IV))
{
byte[] encryptedData = PerformCryptography(encryptor, original);
byte[] final = Combine(aesAlg.IV,encryptedData);
IO.writeByteToFile(final, toFile);
}
}
}

Encrypting and Decrypting a file with AES generates a broken file

I'm trying to encrypt and decrypt a file using AES. The problem that I have is that when the file gets decrypted, it is broken and you can't open it. The original file has a length of 81.970 bytes and the decrypted file has a length of 81.984 bytes...so there are 14 bytes added for some reason. The problem could be in the way the file gets encrypted but I don't know what I'm doing wrong.
What am I missing here? Could it be the way I'm processing the password, the iv and the padding?
Thanks for your time!
This is the code I use to encrypt:
private AesManaged aesManaged;
private string filePathToEncrypt;
public Encrypt(AesManaged aesManaged, string filePathToEncrypt)
{
this.aesManaged = aesManaged;
this.filePathToEncrypt = filePathToEncrypt;
}
public void DoEncryption()
{
byte[] cipherTextBytes;
byte[] textBytes = File.ReadAllBytes(this.filePathToEncrypt);
using(ICryptoTransform encryptor = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV))
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(textBytes, 0, textBytes.Length);
cs.FlushFinalBlock();
cipherTextBytes = ms.ToArray();
}
File.WriteAllBytes("EncryptedFile.aes", cipherTextBytes);
}
This is the code I use to decrypt:
private AesManaged aesManaged;
private string filePathToDecrypt;
public Decrypt(AesManaged aesManaged, string filePathToDecrypt)
{
this.aesManaged = aesManaged;
this.filePathToDecrypt = filePathToDecrypt;
}
public void DoDecrypt()
{
byte[] cypherBytes = File.ReadAllBytes(this.filePathToDecrypt);
byte[] clearBytes = new byte[cypherBytes.Length];
ICryptoTransform encryptor = aesManaged.CreateDecryptor(aesManaged.Key, aesManaged.IV);
using (MemoryStream ms = new MemoryStream(cypherBytes))
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Read))
{
cs.Read(clearBytes, 0, clearBytes.Length);
clearBytes = ms.ToArray();
}
File.WriteAllBytes("DecryptedFile.gif", clearBytes);
}
And here is how I call the functions:
string filePathToEncrypt = "dilbert.gif";
string filePathToDecrypt = "EncryptedFile.aes";
string password = "Password";
string passwordSalt = "PasswordSalt";
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(passwordSalt));
var aesManaged = new AesManaged
{
Key = deriveBytes.GetBytes(128 / 8),
IV = deriveBytes.GetBytes(16),
Padding = PaddingMode.PKCS7
};
Console.WriteLine("Encrypting File...");
var encryptor = new Encrypt(aesManaged, filePathToEncrypt);
encryptor.DoEncryption();
Thread.Sleep(300);
Console.WriteLine("Decrypting File...");
var decryptor = new Decrypt(aesManaged, filePathToDecrypt);
decryptor.DoDecrypt();
Thread.Sleep(300);
Try with:
public void DoEncryption()
{
byte[] cipherBytes;
byte[] textBytes = File.ReadAllBytes(this.filePathToEncrypt);
using (ICryptoTransform encryptor = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV))
using (MemoryStream input = new MemoryStream(textBytes))
using (MemoryStream output = new MemoryStream())
using (CryptoStream cs = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
{
input.CopyTo(cs);
cs.FlushFinalBlock();
cipherBytes = output.ToArray();
}
File.WriteAllBytes("EncryptedFile.aes", cipherBytes);
}
and
public void DoDecrypt()
{
byte[] cypherBytes = File.ReadAllBytes(this.filePathToDecrypt);
byte[] textBytes;
using (ICryptoTransform decryptor = aesManaged.CreateDecryptor(aesManaged.Key, aesManaged.IV))
using (MemoryStream input = new MemoryStream(cypherBytes))
using (MemoryStream output = new MemoryStream())
using (CryptoStream cs = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
{
cs.CopyTo(output);
textBytes = output.ToArray();
}
File.WriteAllBytes("DecryptedFile.gif", textBytes);
}
Note that the code could be modified to not use temporary byte[] and read/write directly to input/output streams.
In general you can't desume the length of the plaintext from the length of the cyphertext, so this line:
new byte[cypherBytes.Length]
was totally wrong.
And please, don't use Encoding.ASCII in 2016. It is so like previous century. Use Encoding.UTF8 to support non-english characters.
The answer may be very simple. I don't see where do u try to choose a cipher mode, so by default it probably takes CBC, as IV was inited. Then, 81.970 are padded by 14 bytes, to be divisible by 32. So when it happens, the memory you allocated was just 81.970, so the padding bytes doesn't write correctly, cause of some sort of memory leak, and when decrypt is started, unpadding doesn't work correctly.

AES Encryption using RijndaelManged Class: Baes64 encoding and decoding aes encryption string

So, I am having an issue with decrypting the decoded base64 aes string. Is this possible? I wrote a small console program to work this out but no luck. Here is my example:
As depicted, I have successfully converted the base64 back the aes encrypted string, but when I try to decrypt it I get more junk. If a code snippet is need let me. Thank you all for your help :)
UPDATE: Code snippet for decrypting method
static void Main(string[] args)
{
string plainText;
string decrypted;
string decryptedFromB64EncodedDecoded;
string fromBase64ToEncryptedText;
string encryptedText;
string encryptedTextBase64;
byte[] encryptedBytes;
byte[] encryptedBytes2;
byte[] encryptedBytesBase64;
RijndaelManaged crypto = new RijndaelManaged();
UTF8Encoding UTF = new UTF8Encoding();
Console.WriteLine("Please put in the text to be encrypted.");
plainText = Console.ReadLine();
try
{
encryptedBytes = encrypt(plainText, crypto.Key, crypto.IV);
encryptedText = Encoding.ASCII.GetString(encryptedBytes);
//encryptedBytes2 = Encoding.ASCII.GetBytes(encryptedText);
encryptedTextBase64 = toBase64String(encryptedText);
encryptedBytesBase64 = fromBase64String(encryptedTextBase64);
fromBase64ToEncryptedText = Encoding.ASCII.GetString(encryptedBytesBase64);
encryptedBytes2 = Encoding.ASCII.GetBytes(fromBase64ToEncryptedText);
decrypted = decrypt(encryptedBytes, crypto.Key, crypto.IV);
decryptedFromB64EncodedDecoded = decrypt(encryptedBytes2, crypto.Key, crypto.IV);
Console.WriteLine("Start: {0}", plainText);
Console.WriteLine("Encrypted: {0}", encryptedText);
Console.WriteLine("Encrypted Base64: {0}", encryptedTextBase64);
Console.WriteLine("From Base64 To AES Encypted Text: {0}", fromBase64ToEncryptedText);
Console.WriteLine("Decrypted: {0}", decrypted);
Console.WriteLine("Decrypted From Encode and then Decode Base64 Text: {0}", decryptedFromB64EncodedDecoded);
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
Console.ReadLine();
}
public static string decrypt (byte[] textToDecrypt, byte[] key, byte[] IV)
{
RijndaelManaged crypto = new RijndaelManaged();
MemoryStream stream = new MemoryStream(textToDecrypt) ;
ICryptoTransform decryptor = null;
CryptoStream cryptoStream = null;
StreamReader readStream = null;
string text = string.Empty;
try
{
crypto.Key = key;
crypto.IV = IV;
crypto.Padding = PaddingMode.None;
decryptor = crypto.CreateDecryptor(crypto.Key, crypto.IV);
cryptoStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);
//cryptoStream.Read(textToDecrypt, 0, textToDecrypt.Length);
readStream = new StreamReader(cryptoStream);
text = readStream.ReadToEnd();
cryptoStream.Close();
byte[] decodedValue = stream.ToArray();
return text;
}
catch (Exception)
{
throw;
}
finally
{
if (crypto != null)
{
crypto.Clear();
}
stream.Flush();
stream.Close();
}
}
public static byte[] encrypt(string text, byte[] key, byte[] IV)
{
RijndaelManaged crypto = null;
MemoryStream stream = null;
//ICryptoTransform is used to perform the actual decryption vs encryption, hash function are a version crypto transforms
ICryptoTransform encryptor = null;
//CryptoStream allows for encrption in memory
CryptoStream cryptoStream = null;
UTF8Encoding byteTransform = new UTF8Encoding();
byte[] bytes = byteTransform.GetBytes(text);
try
{
crypto = new RijndaelManaged();
crypto.Key = key;
crypto.IV = IV;
stream = new MemoryStream();
encryptor = crypto.CreateEncryptor(crypto.Key, crypto.IV);
cryptoStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(bytes, 0, bytes.Length);
}
catch (Exception)
{
throw;
}
finally
{
if (crypto != null)
{
crypto.Clear();
}
cryptoStream.Close();
}
return stream.ToArray();
}
public static string toBase64String(string value)
{
UTF8Encoding UTF = new UTF8Encoding();
byte[] myarray = UTF.GetBytes(value);
return Convert.ToBase64String(myarray);
}
public static byte[] fromBase64String(string mystring)
{
//UTF8Encoding UTF = new UTF8Encoding();
//byte[] myarray = UTF.GetBytes(value);
return Convert.FromBase64String(mystring);
}
I don't know how you're decrypting but before you decrypt, you should convert the base 64 string to a byte array before sending it into the decryption.
byte[] encryptedStringAsBytes = Convert.FromBase64String(base64EncodedEncryptedValue);
Then with the byte array you can pass to the CryptoStream via a MemoryStream.
UPDATE
I believe the issue is how you're setting up your streams
using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
{
rijndaelManaged.Padding = paddingMode;
rijndaelManaged.Key = key;
rijndaelManaged.IV = initVector;
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream(valueToDecrypt);
using (ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader(cryptoStream))
{
return streamReader.ReadToEnd();
}
}
}
}
finally
{
if (memoryStream != null)
memoryStream.Dispose();
}
}
UPDATE 2
This is how you should basically perform the steps.
To encrypt
Encode your plain text string using the Encoding.GetBytes(stringToEncrypt)
pass the byte[] into the crypto API (via memory stream, etc.)
get the bytes from the encrypted stream and encode the results as Base64
To Decrypt (do the reverse)
Convert the base64 encoded string to bytes using Convert.FromBase64String(base64EncodedEncryptedValue)
pass that byte array into your decryption function above
Try:
encryptedBytes2 = Encoding.ASCII.GetBytes(encryptedText);
Based on your comment. The bytes are just that bytes, so in order to decrypt the ciphertext you need to undo any encoding or series of encodings you have done.
If you really want to go from Encrypted Bytes -> Base64String -> ASCII string -> then decrypt that ASCII string? you would need to base64 decode the ascii string then convert that string to bytes using
Encoding.ASCII.GetBytes(yourdecodedstring);
Note that base 64 decoding is not the same as using Convert.FromBase84String.

DES-ECB encryption and decryption

I'm using DES-ECB + base64 encryption in my application. That's the code of the class I called "Crypto"
public class Crypto
{
public static string Decrypt(string encryptedString)
{
DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
desProvider.Mode = CipherMode.ECB;
desProvider.Padding = PaddingMode.PKCS7;
desProvider.Key = Encoding.ASCII.GetBytes("e5d66cf8");
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(encryptedString)))
{
using (CryptoStream cs = new CryptoStream(stream, desProvider.CreateDecryptor(), CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs, Encoding.ASCII))
{
return sr.ReadToEnd();
}
}
}
}
public static string Encrypt(string decryptedString)
{
DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
desProvider.Mode = CipherMode.ECB;
desProvider.Padding = PaddingMode.PKCS7;
desProvider.Key = Encoding.ASCII.GetBytes("e5d66cf8");
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(stream, desProvider.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] data = Encoding.Default.GetBytes(decryptedString);
cs.Write(data, 0, data.Length);
return Convert.ToBase64String(stream.ToArray());
}
}
}
}
but when I encrypt a string, then decrypt it again and encrypt one more time, the encrypted string is not the same as previous encrypted was. So that's the first encrypted string:
kEN0HUp/dqz8kXA7nYivJG6Jl3haLJjhBq1UfEtQTwaPwizW//03M0UxF8dBuYZo2BoZ5vsVcXRJF1LpFZLWxDsdeKAC43L2K2OoYRxTn/dA6KmM13YS9xOezGiROQfVj5qrkdokJRCvj0gYfFoH2oeDGyN+EAw5Dgzsp697kj4=
and here comes the second encrypted string:
kEN0HUp/dqz8kXA7nYivJG6Jl3haLJjhBq1UfEtQTwaPwizW//03M0UxF8dBuYZo2BoZ5vsVcXRJF1LpFZLWxDsdeKAC43L2K2OoYRxTn/dA6KmM13YS9xOezGiROQfVj5qrkdokJRCvj0gYfFoH2oeDGyN+EAw5
They are almost same, except this "Dgzsp697kj4=" in the first string.
What's wrong?
Thanks in advance.
You are losing data. In your Encrypt() method you need to call EncryptFinalBlock() to let the padding algorithm know that you are done so that it can add the padding:
using (CryptoStream cs = new CryptoStream(stream, desProvider.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] data = Encoding.Default.GetBytes(decryptedString);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock(); // <-- Add this
return Convert.ToBase64String(stream.ToArray());
}
I had a similar problem. You should check that white space is not getting appended to the end of the decrypted string. You might need to trim the white space off.

Categories

Resources