I need to transfer xml files and they are required to be encrypted. I have found some examples think I'm close but when I decrypt the file I end up with trailing junk characters. There are some posts about this but I have not seen any that will exactly help. Here is the encrypt and decrypt code.
private void EncryptFile(string inputFile, string outputFile, string key) {
try {
byte[] keyBytes;
keyBytes = Encoding.Unicode.GetBytes(key);
Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(key, keyBytes);
RijndaelManaged rijndaelCSP = new RijndaelManaged();
rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);
ICryptoTransform encryptor = rijndaelCSP.CreateEncryptor();
FileStream inputFileStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
byte[] inputFileData = new byte[(int)inputFileStream.Length];
inputFileStream.Read(inputFileData, 0, (int)inputFileStream.Length);
FileStream outputFileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
CryptoStream encryptStream = new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write);
encryptStream.Write(inputFileData, 0, (int)inputFileStream.Length);
encryptStream.FlushFinalBlock();
rijndaelCSP.Clear();
encryptStream.Close();
inputFileStream.Close();
outputFileStream.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Encryption Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("File Encryption Complete!");
}
private void DecryptFile(string inputFile, string outputFile, string key) {
try {
byte[] keyBytes = Encoding.Unicode.GetBytes(key);
Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(key, keyBytes);
RijndaelManaged rijndaelCSP = new RijndaelManaged();
rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);
ICryptoTransform decryptor = rijndaelCSP.CreateDecryptor();
FileStream inputFileStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
CryptoStream decryptStream = new CryptoStream(inputFileStream, decryptor, CryptoStreamMode.Read);
byte[] inputFileData = new byte[(int)inputFileStream.Length];
decryptStream.Read(inputFileData, 0, (int)inputFileStream.Length);
FileStream outputFileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
outputFileStream.Write(inputFileData, 0, inputFileData.Length);
outputFileStream.Flush();
rijndaelCSP.Clear();
decryptStream.Close();
inputFileStream.Close();
outputFileStream.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Decryption Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("File Decryption Complete!");
}
I end up with
<?xml version="1.0" encoding="UTF-8"?>
<transaction>
<header>
<qOrderNumber></qOrderNumber>
<qRequestDate></qRequestDate>
<testOrder></testOrder>
<qCustomerNumber></qCustomerNumber>
<transactionStatus></transactionStatus>
</header>
<lines>
<line>
<productID></productID>
<serialNumber></serialNumber>
</line>
<line>
<productID></productID>
<serialNumber></serialNumber>
</line>
</lines>
</transaction>NULNULNULNULNULNUL
When decrypting, pay attention to the return value from the CryptoStream.Read call. It tells you the length of the decrypted data in your byte array (usually will not match the length of the encrypted data due to padding). Try using the following in your decrypt function:
int decrypt_length = decryptStream.Read(inputFileData, 0, (int)inputFileStream.Length);
FileStream outputFileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
outputFileStream.Write(inputFileData, 0, decrypt_length);
On the RijndaelManaged object, set the Padding property to PaddingMode.ANSIX923 or PaddingMode.ISO10126.
Those null bytes were added to fill out the final encrypted block. It was padded with zeros by default, which means that no indication is given as to the actual length of the data. The other padding modes include a length in the final byte, so that the padding can be removed after decryption.
Set the padding property in both the encrypt and decrypt routine to the same value.
rijndaelCSP.Padding = PaddingMode.ANSIX923;
If it knows what to expect, then the decryption stream will remove the padding automatically, so no further changes should be necessary.
UPDATE
From looking at your code, it appears that the number of bytes that you are writing to the output file is equal to the number of bytes read in from the input file.
byte[] inputFileData = new byte[(int)inputFileStream.Length];
decryptStream.Read(inputFileData, 0, (int)inputFileStream.Length);
The decryption process is not going to completely fill up the inputFileData array, because of the padding in the input.
The output stream will then write out the entire length of the buffer, even though it wasn't completely filled.
outputFileStream.Write(inputFileData, 0, inputFileData.Length);
This is the source of your nulls.
You may want to change the way you are doing the encryption and decryption so that it no longer uses fixed-length bufferes. Alternatively, you could store the length of the encrypted data at the beginning, and only write the number of bytes that correspond to that length.
Related
I have implement code Encrypt and Decrypt method. Input string value passed to encrypt method and get the encrypt value stored in xml file . after I getting encrypted value to read xml file using Decrypt Method to read value. I am getting Error in rare case(Encrypted input value is not correct and Decrypted output value). how do i resolve this Issue . Please share to me .
Here Sample code
public static string Decrypt(string cipherText)
{
try
{
string incoming = cipherText.Replace('_', '/').Replace('-', '+');
switch (cipherText.Length % 4)
{
case 2: incoming += "=="; break;
case 3: incoming += "="; break;
}
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] cipherTextBytes = Convert.FromBase64String(incoming);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
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();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
catch (Exception ex)
{
return "Exception";
}
}
You are adding manually a padding to the end of the data, if you don't reverse that on the decipher then it would not work (it must be added after decripting as you did it before).
But, also, that padding is unnecessary, AES256 needs the data to be padded, yes, but the cryptostream will do that for you, so if you remove all that padding stuff it will work.
USE Trim() Function AND REMOVE ALL OF THE WHITE SPACES
This issue may occur when there are white spaces.
Use Trim() function to remove white spaces.
example -: cipherText.Trim()
I have the following code:
private void EncryptFile(string inputFile, string outputFile, string pass)
{
try
{
string password = #pass;
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
byte[] iv = new byte[128];
for(int i =0; i < iv.Length; i++)
{
iv[i] = Convert.ToByte(true);
}
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
MessageBox.Show(RMCrypto.BlockSize + "\n" + iv.Length);
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, iv),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch(Exception ex)
{
//MessageBox.Show("Encryption failed!", "Error");
MessageBox.Show(ex.Message);
}
}
But have a problem with the IV size. Using a simple message box I found that (probably) the block size is 128. So, I set the IV to a 128 bytes array full of "1" values to test. The first message box confirms the blocksize and the IV array length are both 128. However, I get an exception saying Specified initialization vector (IV) does not match the block size for this algorithm.
Why is this and how to fix the issue?
AES block size is 128 bits. Not bytes. Bits.
The winner of the AES contest, Rijndael, supports block and key sizes of 128, 192, and 256 bits, but in AES the block size is always 128 bits. The extra block sizes were not adopted by the AES standard
I've code to decrypt file in DES Encryption, I try I keep getting the file even though I enter the key at the time when the key decrypt the encrypted differently. But i've get the error.
while ((data = cryptostreamDecr.ReadByte()) != -1) // Message Error : Bad Data.
Which code should I add or change in order to keep the process running decrypt?
private static void DecryptFile(string sInputFilename, string sKey)
{
var DES = new DESCryptoServiceProvider();
DES.Key = Encoding.ASCII.GetBytes(sKey);
DES.IV = Encoding.ASCII.GetBytes(sKey);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
using (var fsread = new FileStream(sInputFilename, FileMode.Open,
FileAccess.ReadWrite))
{
using (var cryptostreamDecr = new CryptoStream(fsread,
desdecrypt,
CryptoStreamMode.Read))
{
int data;
fsread.Flush();
using (var ms = new MemoryStream())
{
while ((data = cryptostreamDecr.ReadByte()) != -1)
{
ms.WriteByte((byte)data);
}
cryptostreamDecr.Close();
using (var fsWrite = new FileStream(sInputFilename, FileMode.Truncate))
{
ms.WriteTo(fsWrite);
ms.Flush();
}
}
}
}
}
Encrypt Code :
public static void EncryptFile(string sInputFilename, string sKey)
{
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.ReadWrite);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsInput,
desencrypt,
CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
fsInput.SetLength(0);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.FlushFinalBlock();
cryptostream.Close();
fsInput.Close();
}
[EDIT] : remove in Encypt :
cryptostream.FlushFinalBlock();
And add in decrypt
DES.Padding = PaddingMode.None;
64 bits is the only valid key size for the DES encryption algorithm.
8 bits is equal to one ASCII character means 64 bits is equal to 8 Characters.
If you send 8 characters only then check this (C# "Bad Data" exception when decrypting encrypted file). It may solve your problem.
[Edit]
Add DES.Padding = PaddingMode.None; in DecryptFile.
i have a code in c# that encrypt and decrypt .txt file. but i need to encrypt and decrypt files with any extension like pdf, zip, jpg etc..
i searched ant tried to find stream encryption but i couldnt find any..
i am trying following code from link . i changed file path and put some pdf or ppt. it works correctly but i can not open decrypted file.
using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
namespace CSEncryptDecrypt
{
class Class1
{
// Call this function to remove the key from memory after use for security
[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")]
public static extern bool ZeroMemory(IntPtr Destination, int Length);
// Function to Generate a 64 bits Key.
static string GenerateKey()
{
// Create an instance of Symetric Algorithm. Key and IV is generated automatically.
DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
// Use the Automatically generated key for Encryption.
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
static void EncryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
{
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFilename,
FileMode.Create,
FileAccess.Write);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted,
desencrypt,
CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}
static void DecryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
//Set initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
//Create a file stream to read the encrypted file back.
FileStream fsread = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);
//Create a DES decryptor from the DES instance.
ICryptoTransform desdecrypt = DES.CreateDecryptor();
//Create crypto stream set to read and do a
//DES decryption transform on incoming bytes.
CryptoStream cryptostreamDecr = new CryptoStream(fsread,
desdecrypt,
CryptoStreamMode.Read);
//Print the contents of the decrypted file.
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}
static void Main()
{
// Must be 64 bits, 8 bytes.
// Distribute this key to the user who will decrypt this file.
string sSecretKey;
// Get the Key for the file to Encrypt.
sSecretKey = GenerateKey();
// For additional security Pin the key.
GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );
// Encrypt the file.
EncryptFile(#"C:\MyData.txt",
#"C:\Encrypted.txt",
sSecretKey);
// Decrypt the file.
DecryptFile(#"C:\Encrypted.txt",
#"C:\Decrypted.txt",
sSecretKey);
// Remove the Key from memory.
ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
gch.Free();
}
}
}
thanks for responses. i found the reason. i should use filestream not the streamwriter in the decryptFile function
following routine I'm using to serialize objects securely.
Maybe it can help you to understand how stream encryption works:
public bool Save(string filename, object toSerialize)
{
byte[] SALT = new byte[]
{0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c};
string EncryptionKey = "MYPASSWORD";
//basic serialization
IFormatter form = new BinaryFormatter();
var stream = new MemoryStream();
form.Serialize(stream, toSerialize);
//cryptography preparation
var alg = new RijndaelManaged();
var pdb = new Rfc2898DeriveBytes(EncryptionKey, SALT);
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
stream.Position = 0;
//cryptorgraphy serialization
var encStream = new MemoryStream();
var cryptoStream = new CryptoStream(encStream, alg.CreateEncryptor(), CryptoStreamMode.Write);
cryptoStream.Write(stream.ToArray(), 0, (int)stream.Length);
cryptoStream.FlushFinalBlock();
var outputFileStream = new FileStream(fileName, FileMode.Create);
outputFileStream.Write(encStream.ToArray(), 0, (int)encStream.Length);
outputFileStream.Close();
return true;
}
I can also put you sources to deserialize encrypted stream.
Hey I'm very new to encryption and decryption, or even the c# language to be honest. Basically, I have a tcp chat server that "saves" logs and encrypts the text file. This is how I encrypt (based from the MSDN sample):
public static void EncryptFile(string strInputFileName, string strOutputFileName, string strKey)
{
FileStream fsIn = new FileStream(strInputFileName, FileMode.Open, FileAccess.Read);
FileStream fsOut = new FileStream(strOutputFileName, FileMode.Create, FileAccess.Write);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = ASCIIEncoding.ASCII.GetBytes(strKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(strKey);
ICryptoTransform desencrypt = des.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsOut, desencrypt, CryptoStreamMode.Write);
byte[] byteArrayInput = new byte[fsIn.Length - 1];
fsIn.Read(byteArrayInput, 0, byteArrayInput.Length);
cryptostream.Write(byteArrayInput, 0, byteArrayInput.Length);
fsIn.Close();
fsOut.Close();
}
The method success fully encrypts files. This is my decrypt method:
public static void DecryptFile(string strInputFileName, string strOutputFileName, string strKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = ASCIIEncoding.ASCII.GetBytes(strKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(strKey);
byte[] te = new byte[1024];
FileStream fsRead = new FileStream(strInputFileName, FileMode.Open, FileAccess.Read);
ICryptoTransform desdecrypt = des.CreateDecryptor();
CryptoStream cryptostream = new CryptoStream(fsRead, desdecrypt, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter(strOutputFileName);
fsDecrypted.Write(new StreamReader(cryptostream).ReadToEnd());//This is where the "Bad Data" occurs.
fsDecrypted.Flush();
fsDecrypted.Close();
fsRead.Close();
}
And when I inspect the cryptostream object, it says that it has thrown an exception, "Stream does not support seeking".
Any help would be greatly appreciated!
Here:
cryptostream.Write(byteArrayInput, 0, byteArrayInput.Length);
fsIn.Close();
fsOut.Close();
You're closing fsOut directly, without closing cryptostream. That means the crypto stream doesn't get the chance to flush any final blocks etc.
Additionally:
Use using statements instead of manually calling Close or Dispose
You're currently calling Read once, and assuming it will read all the data - you're not checking the return value. (You're also removing the last byte of the input file for some reason... why?) In general, you should loop round, reading into a buffer and then writing out however many bytes you read, until the Read method returns 0. If you're using .NET 4, Stream.CopyTo is your friend.
objCryptStream.CopyTo(stream);
Worked for me, complete code is
public static string DecryptString(string encriptedText, string key)
{
try
{
//Convert the text into bytest
byte[] ecriptedBytes = System.Convert.FromBase64String(encriptedText);
// Create a memory stream to the passed buffer
MemoryStream objMemStream = new MemoryStream(ecriptedBytes);
//Set the legal keys and initialization verctors
objCrptoService.Key = GetLegalsecretKey(key);
objCrptoService.IV = GetLegalIV();
// Create a CryptoStream using the memory stream and the cryptographic service provider version
// of the Data Encryption stanadard algorithm key
CryptoStream objCryptStream = new CryptoStream(objMemStream, objCrptoService.CreateDecryptor(), CryptoStreamMode.Read);
// Create a StreamReader for reading the stream.
//StreamReader objstreamReader = new StreamReader(objCryptStream);
MemoryStream stream = new MemoryStream();
objCryptStream.CopyTo(stream);
stream.Position = 0;
StreamReader R = new StreamReader(stream);
string outputText = R.ReadToEnd();
// Close the streams.
R.Close();
objCryptStream.Close();
objMemStream.Close();
return outputText;
}
catch (Exception exc)
{
return "";
}
}
What fixed my issue was calling FlushFinalBlock on cryptostream, When creating the file
CryptoStream cryptostream = new CryptoStream(memoryStream, this._encryptionKeyHelper.Encryptor(), CryptoStreamMode.Write);
xmlser.Serialize(cryptostream, builderObject);
cryptostream.FlushFinalBlock();