Image Encrypting Getting Padding Error - c#

I am developing an image encrypting program. I have got two applications. One of them, converting image to byte array and encrypting with Rijndael. After it is saving encrypted byte array to a file. Second application is for decrypting. I am reading byte array from file. After i am decrypt and show image in picturebox.
But i am geting "Padding is invalid and cannot be removed." error in decryption application.
Now i am saving encrypted byte array to a file this code (I am not sure is it true way for byte array to file ?);
protected bool SaveData(string FileName, byte[] Data)
{
BinaryWriter Writer = null;
try
{
// Create a new stream to write to the file
Writer = new BinaryWriter(File.Open(FileName,FileMode.OpenOrCreate));
// Writer raw data
Writer.Write(Data);
Writer.Flush();
Writer.Close();
}
catch
{
return false;
}
return true;
}
I am giving this method save file location and encrypted byte array. And It is worked. But i dont know, is it correct way ?
And my decryption application reading encrypted byte array from file method;
protected byte[] GetData(string FileName)
{
FileInfo f = new FileInfo(FileName);
BinaryReader br = new BinaryReader(File.Open(FileName, FileMode.Open));
byte[] a = br.ReadBytes(Convert.ToInt32(f.Length));
return a;
}
And Error location decryption method;
public static byte[] DecryptBytes(byte[] encryptedBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(encryptedBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] plainBytes = new byte[encryptedBytes.Length];
int DecryptedCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length); // I am getting error this line. Padding is invalid and cannot be removed.
memoryStream.Flush();
cryptoStream.Flush();
memoryStream.Close();
cryptoStream.Close();
return plainBytes;
}
Encryption Code
public static byte[] EncryptBytes(byte[] inputBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return CipherBytes;
}
Full Code Decryption Application
namespace ImageDecrypte
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string EncPass;
private string line;
private string OkunanVeri;
private byte[] SifreliDosyaDizi;
private byte[] CozulmusDosyaDizi;
private const string SaltPass = "CodeWork";
private string Sfre;
private string dyol;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.Filter = "Şifrelenmiş Dosyalar (*.cw)|*.cw";
file.FilterIndex = 2;
file.RestoreDirectory = true;
file.CheckFileExists = false;
file.Title = "Şifrelenmiş Dosya Seçiniz..";
file.InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (file.ShowDialog() == DialogResult.OK)
{
dyol = file.FileName;
string DosyaAdi = file.SafeFileName;
label1.Text = DosyaAdi;
Sfre = textBox1.Text;
}
}
private void button2_Click(object sender, EventArgs e)
{
Sfre = textBox1.Text;
SifreliDosyaDizi = GetData(dyol);
CozulmusDosyaDizi = DecryptBytes(SifreliDosyaDizi, Sfre, SaltPass);
pictureBox1.Image = byteArrayToImage(CozulmusDosyaDizi);
}
public static byte[] DecryptBytes(byte[] encryptedBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(encryptedBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] plainBytes = new byte[encryptedBytes.Length];
int DecryptedCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
memoryStream.Flush();
cryptoStream.Flush();
memoryStream.Close();
cryptoStream.Close();
return plainBytes.Take(DecryptedCount).ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
//File To Byte Array ###################################################################
protected byte[] GetData(string FileName)
{
FileInfo f = new FileInfo(FileName);
BinaryReader br = new BinaryReader(File.Open(FileName, FileMode.Open));
byte[] a = br.ReadBytes(Convert.ToInt32(f.Length));
return a;
}
//File To Byte Array ###################################################################
}
}
Full Code Encryption Application
namespace ImageEncrypte
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string EncPass;
private byte[] byteArrayForImage;
private byte[] byteArrayCoded;
private const string SaltPass = "CodeWork";
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.Filter = "Jpeg Dosyası |*.jpg| Png Dosyası|*.png";
file.FilterIndex = 2;
file.RestoreDirectory = true;
file.CheckFileExists = false;
file.Title = "Bir İmaj Dosyası Seçiniz..";
file.InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
EncPass = textBox1.Text;
if (file.ShowDialog() == DialogResult.OK)
{
string DosyaYolu = file.FileName;
string DosyaAdi = file.SafeFileName;
label1.Text = DosyaAdi;
Image img = Image.FromFile(DosyaYolu);
pictureBox1.Image = img;
byteArrayForImage = imageToByteArray(img);
byteArrayCoded = EncryptBytes(byteArrayForImage, EncPass, SaltPass);
}
}
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog sf = new SaveFileDialog();
sf.Title = "Şifrelenmiş Dosyayı Kaydet";
sf.CheckFileExists = false;
sf.CheckPathExists = true;
sf.RestoreDirectory = true;
sf.DefaultExt = "cw";
sf.FileName = "EncodedFile";
sf.SupportMultiDottedExtensions = false;
sf.Filter = "Şifrelenmiş Dosyalar (*.cw)|*.cw";
sf.InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (sf.ShowDialog() == DialogResult.OK)
{
string DosyaYolu = sf.FileName;
bool cevap = SaveData(DosyaYolu, byteArrayCoded);
if (cevap)
{
MessageBox.Show("OK");
}
else
{
MessageBox.Show("PROBLEM");
}
}
}
//Image To Byte Array ####################################################################
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
}
//Image To Byte Array ####################################################################
//Byte Array To File ###################################################################
protected bool SaveData(string FileName, byte[] Data)
{
BinaryWriter Writer = null;
try
{
// Create a new stream to write to the file
Writer = new BinaryWriter(File.Open(FileName,FileMode.OpenOrCreate));
// Writer raw data
Writer.Write(Data);
Writer.Flush();
Writer.Close();
}
catch
{
return false;
}
return true;
}
//Bytte Array To File ###################################################################
//EncryptBytes ###################################################################
public static byte[] EncryptBytes(byte[] inputBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return CipherBytes;
}
//EncryptBytes ###################################################################
}
}
What can i do before going to be a crazy man ? Thank you and waiting your precious answers.

Thanks to Maximilian Gerhardt Solution is here;
public static byte[] EncryptBytes(byte[] inputBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
RijndaelCipher.Padding = PaddingMode.PKCS7;
byte[] salt = Encoding.UTF32.GetBytes(saltValue);
//byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
cryptoStream.Flush();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return CipherBytes;
}
public static byte[] DecryptBytes(byte[] encryptedBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
RijndaelCipher.Padding = PaddingMode.PKCS7;
byte[] salt = Encoding.UTF32.GetBytes(saltValue);
//byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(encryptedBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] plainBytes = new byte[encryptedBytes.Length];
int DecryptedCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
memoryStream.Flush();
cryptoStream.Flush();
memoryStream.Close();
cryptoStream.Close();
return plainBytes.Take(DecryptedCount).ToArray();
}
public static byte[] GetData(string FileName)
{
return File.ReadAllBytes(FileName);
}
protected bool SaveData(string FileName, byte[] Data)
{
try
{
File.WriteAllBytes(FileName, Data);
return true;
}
catch
{
return false;
}
}

Related

Decryption failing despite key and packing being correct

I'm getting the infamous "Padding is invalid and cannot be removed." error. However, despite ensuring the padding mode is set as well as verifying the key is the same on both encrypt and decrypt. I can't get past the issue.
What am I doing wrong o' great sages of the internet?
//Targeting .Net 4.5.2
//Key is hard coded, ONLY while working through this error in a minimum repo.
byte[] testKey = Convert.FromBase64String("KN1df3fOkLmSPyOP4r+grlVFDC/JVlWuew1u/hDGvUU=");
//Called to Encrypt ("D:\\Assets\\", "Test.txt")
public void DoWork(string filePath, string fileName){
CryptographyUtil crypto = new CryptographyUtil(testKey);
crypto.EncryptFile(filePath, fileName));
}
//Called to Decrypt ("D:\\Assets\\", "Test.txt.dat")
public void UnDoWork(string filePath, string fileName){
CryptographyUtil crypto = new CryptographyUtil(testKey);
crypto.DecryptFile(filePath, fileName));
}
public class CryptographyUtil(){
RijndaelManaged rjndl;
RNGCryptoServiceProvider cRng;
public CryptographyUtil(byte[] key, int keySize = 256, int blockSize = 256) {
cRng = new RNGCryptoServiceProvider();
rjndl = new RijndaelManaged();
rjndl.Key = key;
rjndl.KeySize = keySize;
rjndl.BlockSize = blockSize;
rjndl.Mode = CipherMode.CBC;
rjndl.Padding = PaddingMode.PKCS7;
}
public void EncryptFile(string filePath, string fileName) {
string inputFilePath = Path.Combine(filePath, fileName);
if(!File.Exists(inputFilePath)) {
throw new FileLoadException("Unable to locate or open file.", inputFilePath);
}
string outputDirectory = Path.Combine(filePath, "Encrypted");
if(!Directory.Exists(outputDirectory)){
Directory.CreateDirectory(outputDirectory);
}
string outputPath = Path.Combine(outputDirectory, fileName + ".dat");
//Create a unique IV each time
byte[] iv = new byte[rjndl.BlockSize / 8]
cRng.GetBytes(iv);
byte[] ivSize = BitConverter.GetBytes(iv.Length);
ICryptoTransform encryptor = rjndl.CreateEncryptor(rjndl.Key, iv);
using(FileStream readStream = File.OpenRead(inputFilePath)) {
using(FileStream writeStream = new FileStream(outputPath, FileMode.Create)) {
using(CryptoStream encryptStream = new CryptoStream(writeStream, encryptor, CryptoStreamMode.Write)) {
//Write the following to the file before the encrypted data:
// - length of the IV
// - the IV
writeStream.Write(ivSize, 0, ivSize.Length);
writeStream.Write(iv, 0, iv.Length);
readStream.CopyTo(encryptStream);
readStream.Flush();
encryptStream.FlushFinalBlock();
encryptStream.Close();
}
writeStream.Close();
}
readStream.Close();
}
}
public void DecryptFile(string filePath, string fileName) {
string outputDirectory = Path.Combine(filePath, "Decrypted");
if(!Directory.Exists(outputDirectory)){
Directory.CreateDirectory(outputDirectory);
}
//Remove the ".dat" from the end of the file
string outputFilePath = Path.Combine(outputDirectory, fileName.Substring(0, fileName.LastIndexOf('.')));
if(File.Exists(outputFilePath)){
File.Delete(outputFilePath);
}
using(FileStream readStream = File.OpenRead(Path.Combine(filePath, fileName))) {
//Size buffer for IV Length (int = 4 bytes)
byte[] buffer = new byte[4];
readStream.Read(buffer, 0, buffer.Length);
int ivLength = BitConverter.ToUInt16(buffer, 0);
//Re-size buffer for IV
buffer = new byte[ivLength];
//Read IV to buffer and use to create decryptor
readStream.Read(buffer, 0, ivLength);
//Use IV in buffer to create decryptor
ICryptoTransform decryptor = rjndl.CreateDecryptor(rjndl.Key, buffer);
buffer = new byte[1024];
using(FileStream writeStream = new FileStream(outputFilePath, FileMode.Create)) {
using(CryptoStream decryptStream = new CryptoStream(readStream, decryptor, CryptoStreamMode.Read)) {
//FIXME: Padding Error
int readIdx = decryptStream.Read(buffer, 0, buffer.Length);
while(readIdx > 0) {
writeStream.Write(buffer, 0, readIdx);
readIdx = decryptStream.Read(buffer, 0, buffer.Length);
}
decryptStream.Flush();
decryptStream.Close();
}
writeStream.Close();
}
readStream.Close();
}
}
}
Using RijndaelManaged as I have to create encrypted packages for legacy software that uses it to decrypt.

Need help converting c# encryption/Decryption to php

C#
public void start()
{
Constants.APIENCRYPTKEY = Convert.ToBase64String(Encoding.Default.GetBytes(Session(32)));
Constants.APIENCRYPTSALT = Convert.ToBase64String(Encoding.Default.GetBytes(Session(16)));
string results = EncryptService("start");
}
private static string Session(int length)
{
Random random = new Random();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public static string DecryptService(string value)
{
string message = value;
string password = Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTKEY));
SHA256 mySHA256 = SHA256Managed.Create();
byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
byte[] iv = Encoding.ASCII.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTSALT)));
string decrypted = DecryptString(message, key, iv);
return decrypted;
}
public static string DecryptString(string cipherText, byte[] key, byte[] iv)
{
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
encryptor.Key = key;
encryptor.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform aesDecryptor = encryptor.CreateDecryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);
string plainText = String.Empty;
try
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] plainBytes = memoryStream.ToArray();
plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
}
finally
{
memoryStream.Close();
cryptoStream.Close();
}
return plainText;
}
public static string EncryptService(string value)
{
string message = value;
string password = Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTKEY));
SHA256 mySHA256 = SHA256Managed.Create();
byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
byte[] iv = Encoding.ASCII.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTSALT)));
string encrypted = EncryptString(message, key, iv);
int property = Int32.Parse((OnProgramStart.AID.Substring(0, 2)));
string final = encrypted + Security.Obfuscate(property);
return final;
}
public static string EncryptString(string plainText, byte[] key, byte[] iv)
{
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
encryptor.Key = key;
encryptor.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
return cipherText;
}
This is what I got so far in PHP
function decrypt_string($msg='', $salt='', $key='')
{
$key = utf8_encode(base64_decode($key));
$key = hash('sha256', $key);
$salt = utf8_encode(base64_decode($salt));
$salt = EncodingASCII($salt);
$method = 'aes-256-cbc';
$msg = openssl_decrypt($msg, $method, $key, OPENSSL_RAW_DATA, $salt);
return $msg;
}
The encrypt and decrypt works perfect on c#, but I can't get it to decrypt on php. Haven't attempted to make the encrypt in php yet. My c# application calls on the php script with a encrypted data and needs to be decrypted on the php side then encrypted data sent back to the c# application.

How to encrypt and decrypt data using memorystream, cryptostream and utf8 encoding correctly?

Actually i had wrote the coding for the program in c#, but when the Encrypt Part is empty, i cannot decrypt my encrypted data lonely. It is because my byte[] cipherdata is empty at the earlier part. How can I correct my coding?
I use this program for bigger file. Need it to be faster and precise.
private void buttonEncrypt_Click(object sender, EventArgs e)
{
AesCryptoServiceProvider triple = new AesCryptoServiceProvider();
UTF8Encoding u = new UTF8Encoding();
triple.Key = Encoding.ASCII.GetBytes("1234567890123456");
triple.Mode = CipherMode.ECB;
triple.Padding = PaddingMode.Zeros;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, triple.CreateEncryptor(), CryptoStreamMode.Write);
encrypted = Encoding.UTF8.GetBytes(textBoxOpen1.Text);
cs.Write(encrypted, 0, encrypted.Length);
cs.Close();
cipherdata = ms.ToArray();
ms.Close();
textBoxEncrypt.Text = Encoding.UTF8.GetString(cipherdata);
MessageBox.Show(" Done encrypting ");
}
private void buttonDecrypt_Click(object sender, EventArgs e)
{
MemoryStream ms = new MemoryStream();
AesCryptoServiceProvider triple = new AesCryptoServiceProvider();
UTF8Encoding u = new UTF8Encoding();
//MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
//chipherdata = textBox1.Text;
triple.Key = Encoding.ASCII.GetBytes("1234567890123456"); //md5.ComputeHash(u.GetBytes(textBox3.Text));
triple.Mode = CipherMode.ECB;
triple.Padding = PaddingMode.Zeros;
MemoryStream ms1 = new MemoryStream(cipherdata);
CryptoStream cs1 = new CryptoStream(ms1, triple.CreateDecryptor(), CryptoStreamMode.Read);
//decrypted = Encoding.UTF8.GetBytes(textBoxOpen2.Text);
cs1.Read(cipherdata, 0, cipherdata.Length);
recipherdata = ms1.ToArray();
cs1.Close();
ms1.Close();
textBoxDecrypt.Text = Encoding.UTF8.GetString(recipherdata);
MessageBox.Show(" Done decrypting ");
}

C# RijndaelManaged cryptographic storage key

my doubt is about the key to decrypt a encrypted string, without the same key used to encrypt the string i dont get the original string ok, but I need to protect this key not use her in hardcode because any hacker could decompiling a dll and see this key, if I to store this key in any archive, the hacker could copy this archive and my method and decrypt my text, how can i prevent this attack? following my code implementation, here the salt and key are static I'm trying to think in anyway to safe these datas
private static byte[] salt = new byte[255];
private static byte[] key;
internal static string EncryptString(string InputText)
{
System.Security.Cryptography.RijndaelManaged RijndaelCipher =
new System.Security.Cryptography.RijndaelManaged();
RNGCryptoServiceProvider rcs = new RNGCryptoServiceProvider();
rcs.GetBytes(salt);
key = RijndaelCipher.Key;
byte[] plainText = System.Text.Encoding.Unicode.GetBytes(InputText);
System.Security.Cryptography.PasswordDeriveBytes SecretKey =
new System.Security.Cryptography.PasswordDeriveBytes(RijndaelCipher.Key, salt);
System.Security.Cryptography.ICryptoTransform Encryptor =
RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
System.Security.Cryptography.CryptoStream cryptoStream =
new System.Security.Cryptography.CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string EncryptedData = Convert.ToBase64String(CipherBytes);
return EncryptedData;
}
internal static string DecryptString(string text)
{
System.Security.Cryptography.RijndaelManaged RijndaelCipher =
new System.Security.Cryptography.RijndaelManaged();
byte[] EncryptedData = Convert.FromBase64String(text);
System.Security.Cryptography.PasswordDeriveBytes SecretKey =
new System.Security.Cryptography.PasswordDeriveBytes(RijndaelCipher.Key, salt);
ICryptoTransform Decryptor =
RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(EncryptedData);
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] PlainText = new byte[EncryptedData.Length];
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
memoryStream.Close();
cryptoStream.Close();
string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
return DecryptedData;
}
#endregion
}

Bad Data: CryptographicException was unhandled during DES decryption

With the below Encrypt method I am succesfully able to encrypt the xml files, but for to decrypt those xml files when I inspect into DESDecrypt method, It throws error
const string DESKey = "AQWSEDRF";
const string DESIV = "HGFEDCBA";
public static string DESDecrypt(string stringToDecrypt)//Decrypt the content
{
byte[] key;
byte[] IV;
byte[] inputByteArray;
try
{
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
stringToDecrypt = stringToDecrypt.Replace(" ", "+");
int len = stringToDecrypt.Length; inputByteArray = Convert.FromBase64String(stringToDecrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8; return encoding.GetString(ms.ToArray());
}
catch (System.Exception ex)
{
throw ex;
}
}
public static string DESEncrypt(string stringToEncrypt)// Encrypt the content
{
byte[] key;
byte[] IV;
byte[] inputByteArray;
try
{
key = Convert2ByteArray(DESKey);
IV = Convert2ByteArray(DESIV);
inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception ex)
{
throw ex;
}
}
static byte[] Convert2ByteArray(string strInput)
{
int intCounter; char[] arrChar;
arrChar = strInput.ToCharArray();
byte[] arrByte = new byte[arrChar.Length];
for (intCounter = 0; intCounter <= arrByte.Length - 1; intCounter++)
arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);
return arrByte;
}
It throws exception, "Bad Data". CryptographicException was unhandled. How can this error be resolved, Any help would be appreciated.

Categories

Resources