c# base64 encoding. Invalid length error on decrpytion - c#

I'm trying to decrypt a string which is also base64 encoded, but I am receiving an when I try to decrypt the string.
The error I am receiving is:
{System.FormatException: Invalid length for a Base-64 char array or string.
at this line in the decrypt function below:
MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
Encrpyt/Decrypt functions:
//ENCRYPT
public static bool stringEncrypt(string inString,ref string outstring)
{
try
{
if(String.IsNullOrEmpty(inString)){return false;}
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms,provider.CreateEncryptor(PWbytes,PWbytes),CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);
sw.Write(inString);
sw.Flush();
cs.FlushFinalBlock();
sw.Flush();
outstring = Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length);
return true;
}
catch(Exception ex)
{
clsCommonBase.AppendToExceptionFile("Encrypt : " + ex.Message);
return false;
}
}
//DECRPYT
public static bool stringDecrypt(string inString,ref string outstring)
{
try
{
if(String.IsNullOrEmpty(inString)){return false;};
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(PWbytes,PWbytes),CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
outstring = sr.ReadToEnd();
return true;
}
catch(Exception ex)
{
clsCommonBase.AppendToExceptionFile("Decrypt : " + ex.Message);
return false;
}
}

Solved using the simple solution in the following link
How do I encode and decode a base64 string?
Also added some code in the encoding function to ensure the plain text string will be converted to a valid length base64 string.
Code:
public static string Base64Encode(string plainText)
{
//check plain text string and pad if needed
int mod4 = plainText.Length % 4;
if (mod4 > 0)
{
plainText += new string('=', 4 - mod4);
}
//convert to base64 and return
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
//decode base64 and return as string
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

Related

Converting bitmap to base 64 string format using CryptoStream

I wish to return the new data of the image in Base64 string format.
These codes below generate image file format not supported
FileInfo imageFileName = new FileInfo(imageDirectoryFullName + "/image" +
imageCounter.ToString() + "." + extension);
try
{
RC2 crypt = RC2.Create();
ICryptoTransform transform = crypt.CreateEncryptor();
var output = new CryptoStream(File.Create(imageFileName.FullName),
transform,
CryptoStreamMode.Write);
imageInfo.Bitmap.Save(output, imageFormat);
}
catch (System.Runtime.InteropServices.ExternalException)
{
return null;
}
or
FileInfo imageFileName = new FileInfo(imageDirectoryFullName + "/image" +
imageCounter.ToString() + "." + extension);
try
{
RC2 crypt = RC2.Create();
ICryptoTransform transform = crypt.CreateEncryptor();
var output = new CryptoStream(File.Create(imageFileName.FullName),
new ToBase64Transform(),
CryptoStreamMode.Write);
imageInfo.Bitmap.Save(output, imageFormat);
}
catch (System.Runtime.InteropServices.ExternalException)
{
return null;
}
How can I do this?
I found the function PerformCryptography from this SO post here which takes a ICryptoTransform and can return the result as a byte array.
From there the code looks like this:
private void Start(object sender, EventArgs e)
{
try
{
// Step 01: First load the Image and convert to a byte array
var imgByteArray = File.ReadAllBytes(#"C:\someImage.jpg");
// Step 02: Then encrypt & convert to a byte array
RC2 crypt = RC2.Create();
ICryptoTransform transform = crypt.CreateEncryptor();
var cryptByteArray = PerformCryptography(transform, imgByteArray);
// Step 03: Now convert the byte array to a Base64 String
string base64String = Convert.ToBase64String(cryptByteArray);
}
catch (System.Runtime.InteropServices.ExternalException)
{
//return null;
}
}
Here are the supporting functions:
private 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();
}
}
}
Instead of saving to a file stream you should use a memory stream. You can then convert the stream to a byte array and feed into Convert.ToBase64. Take the resulting string and do whatever you want with it.

CryptographicException: Bad PKCS7 padding. Invalid length 82

Trying to implement Encryption/Decryption.. the way is to serialize the data into a JSON and then encrypting that JSON to save it. sometimes, it works without any issue while sometimes I get this bad padding error. is there anything that I am missing? tried switching to Rijndael but getting a similar exception.
Save/Load Mechanics
public static void SaveGameJson()
{
Debug.Log("TRYING TO SAVE THE GMAE THROUGH Json File");
SaveManager data = new SaveManager();
string jsonData = JsonUtility.ToJson(data); // encrypting the json data..
// string jsonData = JsonConvert.SerializeObject(data); // encrypting the json data..
string encryptedJsonData = EncryptionRijndael.Encrypt(jsonData);
WriteToFile(JsonfileName, encryptedJsonData);
Debug.LogError("Json data Saved: " + jsonData);
Debug.LogError("Json Encrypted data: " + encryptedJsonData);
}
public static SaveManager LoadGameJson()
{
string path = GetFilePath(JsonfileName);
Debug.Log("TRYING TO LOAD THE GMAE THROUGH FILE");
if (File.Exists(path))
{
string encryptedJsonData = ReadFromFile(JsonfileName); // reading encrypted data from json Encrypted file
string jsonData = EncryptionRijndael.Decrypt(encryptedJsonData); // decrypting json data from encrypted string
Debug.LogError("Json data Load: " + jsonData);
Debug.LogError("Encrypted Data: " + encryptedJsonData);
SaveManager data = JsonUtility.FromJson<SaveManager>(jsonData);
//SaveManager data = JsonConvert.DeserializeObject<SaveManager>(jsonData);
return data;
}
else
{
Debug.LogError("save file not found on:" + path);
return null;
}
}
Additional Function
static void WriteToFile(string fileName, string json) {
string path = GetFilePath(fileName);
FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate);
using (StreamWriter writer = new StreamWriter(fileStream)) {
writer.Write(json);
}
}
Encryption
public static string Encrypt(string strPlain)
{
string password = strPassword;
if (!useSecure)
return strPlain;
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, GetIV(), Iterations);
byte[] key = rfc2898DeriveBytes.GetBytes(8);
using (var memoryStream = new MemoryStream())
using (var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, GetIV()), CryptoStreamMode.Write))
{
memoryStream.Write(GetIV(), 0, GetIV().Length);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(strPlain);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
return Convert.ToBase64String(memoryStream.ToArray());
}
}
catch (Exception e)
{
Debug.LogWarning("Encrypt Exception: " + e);
return strPlain;
}
}
Decryption
public static string Decrypt(string strEncript)
{
string password = strPassword;
if (!useSecure)
return strEncript;
try
{
byte[] cipherBytes = Convert.FromBase64String(strEncript);
using (var memoryStream = new MemoryStream(cipherBytes))
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] iv = GetIV();
memoryStream.Read(iv, 0, iv.Length);
// use derive bytes to generate key from password and IV
var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, iv, Iterations);
byte[] key = rfc2898DeriveBytes.GetBytes(8);
using (var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
using (var streamReader = new StreamReader(cryptoStream))
{
string strPlain = streamReader.ReadToEnd();
return strPlain;
}
}
}
catch (Exception e)
{
Debug.LogWarning("Decrypt Exception: " + e);
return strEncript;
}
}
JSON getting saved
Loading JSON from encrypted string
PS: it seems like the encryption is working fine in the logs but when it tries to decrypt the string, it throughs this exception. Is there any better option for this?

C# DES Decryption Issue

I've a problem implementing symmetric encryption algorithm,the problem is that: randomly the decrypted data is incorrect(rubbish) and only happening on the deployment environment(IIS8 on Win Server 2012 R2)
I started with an AES implementation,when the problem showed up i did a remote debugging on the server and confirmed same encrypted input with the same key/vector is giving different result(rubbish) from my development environment(visual studio on win10 x64)
I've converted to DES but still the same problem exists,below is my DES class for reference:
public class SimpleDES
{
// Change these keys
private byte[] Key = { x, x, x, x, x, x, x, x};
private byte[] Vector;
private string salt = "********";
private ICryptoTransform EncryptorTransform, DecryptorTransform;
private System.Text.UTF8Encoding UTFEncoder;
public SimpleDES(string iVector)
{
this.Vector = this.StrToByteArray(iVector);
Array.Resize(ref this.Vector, 16);
//This is our encryption method
DESCryptoServiceProvider ObjDES = new DESCryptoServiceProvider();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = ObjDES.CreateEncryptor(this.Key, this.Vector);
DecryptorTransform = ObjDES.CreateDecryptor(this.Key, this.Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// ----------- The commonly used methods ------------------------------
/// Encrypt some text and return a string suitable for passing in a URL.
public string EncryptToString(string TextValue)
{
return ByteArrToString(Encrypt(TextValue + salt));
}
/// Encrypt some text and return an encrypted byte array.
public byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);
return EncryptBin(bytes);
}
/// Encrypt some binary and return an encrypted byte array.
public byte[] EncryptBin(Byte[] bytes)
{
byte[] encrypted;
//Used to stream the data in and out of the CryptoStream.
using (MemoryStream memoryStream = new MemoryStream())
{
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
using (CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write))
{
#region Write the decrypted value to the encryption stream
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
}
memoryStream.Close();
}
return encrypted;
}
/// The other side: Decryption methods
public string DecryptString(string EncryptedString)
{
return Decrypt(StrToByteArray(EncryptedString)).Replace(salt, string.Empty);
}
/// Decryption when working with byte arrays.
public string Decrypt(byte[] EncryptedValue)
{
Byte[] decryptedBytes;
using (MemoryStream encryptedStream = new MemoryStream())
{
using (CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write))
{
#region Write the encrypted value to the decryption stream
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
#endregion
}
}
// remove trailing zero bytes
//int lastIndex = Array.FindLastIndex(decryptedBytes, b => b != 0);
//Array.Resize(ref decryptedBytes, lastIndex + 1);
return UTFEncoder.GetString(decryptedBytes);
}
public byte[] DecryptBin(byte[] EncryptedValue)
{
#region Write the encrypted value to the decryption stream
MemoryStream encryptedStream = new MemoryStream();
CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
Byte[] decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
encryptedStream.Close();
#endregion
return decryptedBytes;
}
/// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
// return encoding.GetBytes(str);
// However, this results in character values that cannot be passed in a URL. So, instead, I just
// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
public byte[] StrToByteArray(string str)
{
if (str.Length == 0)
throw new Exception("Invalid string value in StrToByteArray");
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
byte val;
byte[] byteArr = new byte[str.Length / 3];
int i = 0;
int j = 0;
do
{
val = byte.Parse(str.Substring(i, 3));
byteArr[j++] = val;
i += 3;
}
while (i < str.Length);
return byteArr;
}
// Same comment as above. Normally the conversion would use an ASCII encoding in the other direction:
// System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
// return enc.GetString(byteArr);
public string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
}
I hope somebody can have an explanation/suggestion
Edit : sample usage that i've remotely debugged:
byte[] binData;
SimpleDES AES = new SimpleDES("xxxxxxx");
long sz = objRdr.GetBytes(2, 0, null, 0, 0);
if (sz > 0)
{
binData = new byte[sz];
objRdr.GetBytes(2, 0, binData, 0, binData.Length);
string Name = AES.Decrypt(binData);
}
Clarification:-
The class might not be cleanly finalized i had issues with padding(AES implementation) but i had to include for reference
The Core of the problem lies in Decrypt method: same key,vector and input byte array resulted in different decrypted byte array

3DES : Receive Different Byte Array of encoding String from Registry

Tool : Visual Studio 2012. Windows 7 64bit.
Keywords : C#,registry,Triple DES Encryption Decryption.
I have created one demo program to read and write (Encrypted string) to registry.
Concept behind this program is : I want to Encrypt and Decrypt Data using Triple DES(I have Used TripleDESCryptoServiceProvider Class.).After Encryption, encrypted byte array is stored in Registry as a string. Upto this, it work perfectly. But when I get this string from registry and convert it in byte array for decryption, the size of array is different and during encryption it display error :
Length of the data to decrypt is invalid.
Below is my code :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
namespace TripleDES_in_Memory
{
class Program
{
static void Main(string[] args)
{
try
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("MyCompanyName\\"))
{
if (key != null)
{
object o = key.GetValue("TrialPeriod");
if (o != null)
{
string result = Convert.ToString(o);
byte[] Data = Encoding.UTF8.GetBytes(result);
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, o);
byte[] narray = ms.ToArray();
}
TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();
string keybyjaimesh = "MyEncryptKey";
tDESalg.Key = Encoding.UTF8.GetBytes(keybyjaimesh.PadRight(24, ' '));
string ipmanual = "ivmanual";
tDESalg.IV = Encoding.UTF8.GetBytes(ipmanual.PadRight(8, ' '));
byte[] iv = tDESalg.IV;
tDESalg.IV = iv;
string Final = DecryptTextFromMemory(Data, tDESalg.Key, tDESalg.IV); //decrypt
Console.WriteLine(Final);
}
}
else
{
TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();
string sData = "aaaaaaaaaaaaaaaaaaaaaaaa";
DateTime today = DateTime.Today;
DateTime answer = today.AddDays(1);
string keybyjaimesh = "MyEncryptKey";
tDESalg.Key = Encoding.UTF8.GetBytes(keybyjaimesh.PadRight(24, ' '));
string ipmanual = "ivmanual";
tDESalg.IV = Encoding.UTF8.GetBytes(ipmanual.PadRight(8, ' '));
byte[] iv = tDESalg.IV;
byte[] Data = EncryptTextToMemory(sData, tDESalg.Key, tDESalg.IV);
Console.WriteLine("Encrypted data main function : " + System.Text.Encoding.UTF8.GetString(Data));
Microsoft.Win32.RegistryKey key1;
key1 = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("MyCompanyName");
key1.SetValue("TrialPeriod", System.Text.Encoding.UTF8.GetString(Data));
key1.SetValue("IV", System.Text.Encoding.UTF8.GetString(iv));
key1.Close();
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV)
{
try
{
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream,
new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
CryptoStreamMode.Write);
byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);
string result = System.Text.Encoding.UTF8.GetString(toEncrypt);
Console.WriteLine("byte to array : " + result);
cStream.Write(toEncrypt, 0, toEncrypt.Length);
cStream.FlushFinalBlock();
byte[] ret = mStream.ToArray();
Console.WriteLine("Encrypted data : " + System.Text.Encoding.UTF8.GetString(ret));
cStream.Close();
mStream.Close();
return ret;
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
{
try
{
MemoryStream msDecrypt = new MemoryStream(Data);
CryptoStream csDecrypt = new CryptoStream(msDecrypt,
new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
CryptoStreamMode.Read);
byte[] fromEncrypt = new byte[Data.Length];
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return new ASCIIEncoding().GetString(fromEncrypt);
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
}
}
Encrypted String in registry :
Please suggest your opinion on this.
How can I solve this?
I have Solved it.
I have store Encrypted string in registry after convert it in TOBase64String.
string base64 = Convert.ToBase64String(encrypted string);
For Decrypt, Get string using :
string encrypteddatafromregistry = (string)key.GetValue("TrialPeriod",typeof(String));
And then convert to 64 base string :
byte[] encoded = Convert.FromBase64String(encrypteddatafromregistry );
And apply this array to Decryption.

Decryption Key value not match

public class TrippleENCRSPDESCSP
{
public TrippleENCRSPDESCSP()
{
}
public void EncryptIt(string sData,ref byte[] sEncData,ref byte[] Key1,ref byte[] Key2)
{
try
{
// Create a new TripleDESCryptoServiceProvider object
// to generate a key and initialization vector (IV).
TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();
// Create a string to encrypt.
// Encrypt the string to an in-memory buffer.
byte[] Data = EncryptTextToMemory(sData,tDESalg.Key,tDESalg.IV);
sEncData = Data;
Key1 = tDESalg.Key;
Key2 = tDESalg.IV;
}
catch (Exception)
{
throw;
}
}
public string DecryptIt(byte[] sEncData)
{
//byte[] toEncrypt = new ASCIIEncoding().GetBytes(sEncData);
//XElement xParser = null;
//XmlDocument xDoc = new XmlDocument();
try
{
//string Final = "";
string sPwd = null;
string sKey1 = null;
string sKey2 = null;
//System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string soutxml = "";
//soutxml = encoding.GetString(sEncData);
soutxml = ASCIIEncoding.ASCII.GetString(sEncData);
sPwd = soutxml.Substring(18, soutxml.LastIndexOf("</EncPwd>") - 18);
sKey1 = soutxml.Substring(18 + sPwd.Length + 15, soutxml.LastIndexOf("</Key1>") - (18 + sPwd.Length + 15));
sKey2 = soutxml.Substring(18 + sPwd.Length + 15 + sKey1.Length + 13, soutxml.LastIndexOf("</Key2>") - (18 + sPwd.Length + 15 + sKey1.Length + 13));
//xDoc.LoadXml(soutxml);
//xParser = XElement.Parse(soutxml);
//IEnumerable<XElement> elemsValidations =
// from el in xParser.Elements("EmailPwd")
// select el;
#region OldCode
//XmlNodeList objXmlNode = xDoc.SelectNodes("EmailPwd");
//foreach (XmlNode xmllist in objXmlNode)
//{
// XmlNode xmlsubnode;
// xmlsubnode = xmllist.SelectSingleNode("EncPwd");
// xmlsubnode = xmllist.SelectSingleNode("Key1");
// xmlsubnode = xmllist.SelectSingleNode("Key2");
//}
#endregion
//foreach (XElement elemValidation in elemsValidations)
//{
// sPwd = elemValidation.Element("EncPwd").Value;
// sKey1 = elemValidation.Element("Key1").Value;
// sKey2 = elemValidation.Element("Key2").Value;
//}
//byte[] Key1 = encoding.GetBytes(sKey1);
//byte[] Key2 = encoding.GetBytes(sKey2);
//byte[] Data = encoding.GetBytes(sPwd);
byte[] Key1 = ASCIIEncoding.ASCII.GetBytes(sKey1);
byte[] Key2 = ASCIIEncoding.ASCII.GetBytes(sKey2);
byte[] Data = ASCIIEncoding.ASCII.GetBytes(sPwd);
// Decrypt the buffer back to a string.
string Final = DecryptTextFromMemory(Data, Key1, Key2);
return Final;
}
catch (Exception)
{
throw;
}
}
public static byte[] EncryptTextToMemory(string Data,byte[] Key,byte[] IV)
{
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream(mStream,
new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
CryptoStreamMode.Write);
// Convert the passed string to a byte array.
//byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);
byte[] toEncrypt = ASCIIEncoding.ASCII.GetBytes(Data);
// Write the byte array to the crypto stream and flush it.
cStream.Write(toEncrypt, 0, toEncrypt.Length);
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch (CryptographicException e)
{
MessageBox.Show("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream(Data);
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream(msDecrypt,
new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
CryptoStreamMode.Write);
csDecrypt.Write(Data, 0, Data.Length);
//csDecrypt.FlushFinalBlock();
msDecrypt.Position = 0;
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[msDecrypt.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
msDecrypt.Read(fromEncrypt, 0, msDecrypt.ToArray().Length);
//csDecrypt.Close();
MessageBox.Show(ASCIIEncoding.ASCII.GetString(fromEncrypt));
//Convert the buffer into a string and return it.
return new ASCIIEncoding().GetString(fromEncrypt);
}
catch (CryptographicException e)
{
MessageBox.Show("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
}
The same key (Key) and initialization vector (IV) used to encrypt the file must be used to decrypt it. I can't fully check this code currently so there may be one or two small problems but give it a try and let me know if it works, hopefully you get the idea:
public static string DecryptTextFromMemory(byte[] Data, byte[] Key, byte[] IV)
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream();
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream(msDecrypt,
new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
CryptoStreamMode.Write);
csDecrypt.Write(Data, 0, Data.Length);
csDecrypt.FlushFinalBlock();
msDecrypt.Position = 0;
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[msDecrypt.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
msDecrypt.Read(fromEncrypt, 0, msDecrypt.ToArray().Length);
csDecrypt.Close();
//Convert the buffer into a string and return it.
return new UTF8Encoding().GetString(fromEncrypt);
}
catch (CryptographicException e)
{
MessageBox.Show("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}

Categories

Resources