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.
Related
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?
What i would like to do is decrypt a file and save the Hex to a array. Problem im currently having is when i do extract it its in decimal representation of the hex value which i cannot convert back
code:
int bits;
DecryptFile
(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
#"\Akd3\CFS.exe");
}
private void DecryptFile(string input)
{
string password = #"treeessss";
byte[] Key = Encoding.ASCII.GetBytes(password);
RijndaelManaged AES = new RijndaelManaged();
FileStream FCrypted = new FileStream(input, FileMode.Open);
CryptoStream cs = new CryptoStream(FCrypted,
AES.CreateDecryptor(Key, Key), CryptoStreamMode.Read);
int data;
while ((data = cs.ReadByte()) != -1)
if((data = cs.ReadByte()) != -1)
{
bits = bits + data;
}
any ideas on how to extract the bytes or convert the decimal representation would be very helpful thank you
You can get a byte[] from a CryptoStream using the following code:
byte[] result;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
{
cs.Write(inputData, 0, inputData.Length);
}
result = ms.ToArray();
}
Obviously the cs.Write... line can be replaced with a call to another stream to copy into cs
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.
I was searching for the correct solution to decompress the string in java coming from c# code.I tried myself with lot of techniques in java like(gzip,inflatter etc.).but didn't get the solution.i got some error while trying to decompress the string in java from compressed string from c# code.
My C# code to compress the string is,
public static string CompressString(string text)
{
byte[] byteArray = Encoding.GetEncoding(1252).GetBytes(text);// Encoding.ASCII.GetBytes(text);
using (var ms = new MemoryStream())
{
// Compress the text
using (var ds = new DeflateStream(ms, CompressionMode.Compress))
{
ds.Write(byteArray, 0, byteArray.Length);
}
return Convert.ToBase64String(ms.ToArray());
}
}
And decompress the string in java using,
private static void compressAndDecompress(){
try {
// Encode a String into bytes
String string = "xxxxxxSAMPLECOMPRESSEDSTRINGxxxxxxxxxx";
// // Compress the bytes
byte[] decoded = Base64.decodeBase64(string.getBytes());
byte[] output = new byte[4096];
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(decoded);
int resultLength = decompresser.inflate(output);
decompresser.end();
// Decode the bytes into a String
String outputString = new String(output, 0, resultLength, "UTF-8");
System.out.println(outputString);
} catch(java.io.UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (java.util.zip.DataFormatException ex) {
ex.printStackTrace();
}
}
I get this exception when running the above code:
java.util.zip.DataFormatException: incorrect header check
Kindly give me the sample code in java to decompress the string java.Thanks
My C# code to compress is
private string Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
MemoryStream outStream = new MemoryStream();
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String(gzBuffer);
}
Java code to decompress the text is
private String Decompress(String compressedText)
{
byte[] compressed = compressedText.getBytes("UTF8");
compressed = org.apache.commons.codec.binary.Base64.decodeBase64(compressed);
byte[] buffer=new byte[compressed.length-4];
buffer = copyForDecompression(compressed,buffer, 4, 0);
final int BUFFER_SIZE = 32;
ByteArrayInputStream is = new ByteArrayInputStream(buffer);
GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
StringBuilder string = new StringBuilder();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1)
{
string.append(new String(data, 0, bytesRead));
}
gis.close();
is.close();
return string.toString();
}
private byte[] copyForDecompression(byte[] b1,byte[] b2,int srcoffset,int dstoffset)
{
for(int i=0;i<b2.length && i<b1.length;i++)
{
b2[i]=b1[i+4];
}
return b2;
}
This code works perfectly fine for me.
Had exactly the same issue. Could solve it via
byte[] compressed = Base64Utils.decodeFromString("mybase64encodedandwithc#zippedcrap");
Inflater decompresser = new Inflater(true);
decompresser.setInput(compressed);
byte[] result = new byte[4096];
decompresser.inflate(result);
decompresser.end();
System.out.printf(new String(result));
The magic happens with the boolen parameter on instantiating the Inflator
BW Hubert
For beloved googlers,
As #dbw mentioned,
according to post How to decompress stream deflated with java.util.zip.Deflater in .NET?,
java.util.zip.deflater equivalent in c# the default deflater used in C#
is not having any java equivalent that's why users prefer Gzip, Ziplib
or some other zip techniques.
a relatively simple method would be using GZip.
And for the accepted answer, one problem is that in this method you should append the data size to the compressed string yourself, and more importantly as per my own experience in our production app, It is buggy when the string reaches ~2000 chars!
the bug is in the System.io.Compression.GZipStream
any way using SharpZipLib in c# the problem goes away and everything would be as simple as following snippets:
JAVA:
import android.util.Base64;
import com.google.android.gms.common.util.IOUtils;
import org.jetbrains.annotations.Nullable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class CompressionHelper {
#Nullable
public static String compress(#Nullable String data) {
if(data == null || data.length() == 0)
return null;
try {
// Create an output stream, and a gzip stream to wrap over.
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
// Compress the input string
gzip.write(data.getBytes());
gzip.close();
byte[] compressed;
// Convert to base64
compressed = Base64.encode(bos.toByteArray(),Base64.NO_WRAP);
bos.close();
// return the newly created string
return new String(compressed);
} catch(IOException e) {
return null;
}
}
#Nullable
public static String decompress(#Nullable String compressedText) {
if(compressedText == null || compressedText.length() == 0)
return null;
try {
// get the bytes for the compressed string
byte[] compressed = compressedText.getBytes("UTF-8");
// convert the bytes from base64 to normal string
compressed = Base64.decode(compressed, Base64.NO_WRAP);
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
byte[] bytes = IOUtils.toByteArray(gis);
return new String(bytes, "UTF-8");
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
and c#:
using ICSharpCode.SharpZipLib.GZip; //PM> Install-Package SharpZipLib
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeneralTools
{
public static class CompressionTools
{
public static string CompressString(string text)
{
if (string.IsNullOrEmpty(text))
return null;
byte[] buffer = Encoding.UTF8.GetBytes(text);
using (var compressedStream = new MemoryStream())
{
GZip.Compress(new MemoryStream(buffer), compressedStream, false);
byte[] compressedData = compressedStream.ToArray();
return Convert.ToBase64String(compressedData);
}
}
public static string DecompressString(string compressedText)
{
if (string.IsNullOrEmpty(compressedText))
return null;
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
using (var memoryStream = new MemoryStream())
{
using (var compressedStream = new MemoryStream(gZipBuffer))
{
var decompressedStream = new MemoryStream();
GZip.Decompress(compressedStream, decompressedStream, false);
return Encoding.UTF8.GetString(decompressedStream.ToArray()).Trim();
}
}
}
}
}
you may also find the codes here
If anyone still interested, here's my full solution with outputstream to handle unknown string size. Using C# DeflateStream and Java Inflater (based on Hubert Ströbitzer answer).
C# Compression:
string CompressString(string raw)
{
byte[] uncompressedData = Encoding.UTF8.GetBytes(raw);
MemoryStream output = new MemoryStream();
using (DeflateStream dStream = new DeflateStream(output, CompressionLevel.Optimal))
{
dStream.Write(uncompressedData, 0, uncompressedData.Length);
}
string compressedString = Convert.ToBase64String(output.ToArray());
return compressedString;
}
Java decompress:
String decompressString(String compressedString) {
byte[] compressed = Base64Utils.decodeFromString(compressedString);
Inflater inflater = new Inflater(true);
inflater.setInput(compressed);
//Using output stream to handle unknown size of decompressed string
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
try {
while(!inflater.finished()){
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
inflater.end();
outputStream.close();
} catch (DataFormatException e) {
//Handle DataFormatException
} catch (IOException e) {
//Handle IOException
}
return outputStream.toString();
}
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;
}
}