private static void DecryptFile(string filepath) { Console.WriteLine("-------------------------"); Console.WriteLine("File: " + Path.GetFileName(filepath)); Console.WriteLine("-------------------------"); Console.WriteLine("Encrypt as flash object? (Y/N)"); bool isFlashObj = Console.ReadLine().Trim().ToLower() == "y"; string filename = Path.GetFileNameWithoutExtension(filepath); // Base64 decode byte[] encodedBuf; using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(filepath))) { FromBase64Transform trans = new FromBase64Transform(); using (CryptoStream cryptStream = new CryptoStream(ms, trans, CryptoStreamMode.Read)) { byte[] buf = new byte[1024]; int read = 0; using (MemoryStream msResult = new MemoryStream()) { do { read = cryptStream.Read(buf, 0, buf.Length); if (read > 0) { msResult.Write(buf, 0, read); } } while (read > 0); encodedBuf = msResult.ToArray(); } } } // Flash objects needs to be pulled via Flash Decompiler.. if (isFlashObj) { string flashObjPath = Path.Combine(Directory.GetCurrentDirectory(), filename + ".swf"); if (File.Exists(flashObjPath)) { File.Delete(flashObjPath); } File.WriteAllBytes(flashObjPath, encodedBuf); Console.WriteLine("Data exported to \"" + Path.GetFileName(flashObjPath) + "\""); Console.Read(); return; } // Decrypt real XML using BlowFish algo string keyFromDummyAs = "O99vUyAPaGXHNo"; using (MemoryStream streamDataEncoded = new MemoryStream(encodedBuf)) { var keyData = Encoding.UTF8.GetBytes(keyFromDummyAs); var pkcs = new PKCS5(); var blowKey = new BlowFishKey(keyData); var ecbMode = new ECBMode(blowKey, pkcs); pkcs.BlockSize = ecbMode.BlockSize; byte[] bufFinal = ecbMode.Decrypt(streamDataEncoded); string xmlPath = Path.Combine(Directory.GetCurrentDirectory(), filename + ".xml"); if (File.Exists(xmlPath)) { File.Delete(xmlPath); } File.WriteAllBytes(xmlPath, bufFinal); } }
public static void ConvertFromBase64(string inputFilePath, string outputFilePath) { //Create the file streams to handle the input and output files. FileStream fin = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(0); FromBase64Transform transformer = new FromBase64Transform(); //Create variables to help with read and write below. //This is intermediate storage for the decryption: byte[] bin = new byte[fin.Length / transformer.InputBlockSize * transformer.OutputBlockSize]; long rdlen = 0; //This is the total number of bytes written. long totlen = fin.Length; //This is the total length of the input file. int len; //This is the number of bytes to be written at a time. CryptoStream encStream = new CryptoStream(fout, transformer, CryptoStreamMode.Write); //Read from the input file, then decrypt and write to the output file. while(rdlen < totlen) { len = fin.Read(bin, 0, (int)fin.Length); encStream.Write(bin, 0, len); rdlen = (rdlen + ((len / transformer.InputBlockSize) * transformer.OutputBlockSize)); } encStream.Close(); fout.Close(); fin.Close(); }
/// <summary> /// Decodes a base64 encoded string into the bytes it describes /// </summary> /// <param name="base64Encoded">The string to decode</param> /// <returns>A byte array that the base64 string described</returns> public static byte[] Decode(string base64Encoded) { using (var memoryStream = new MemoryStream()) { base64Encoded = base64Encoded.Replace("\r\n", ""); base64Encoded = base64Encoded.Replace("\t", ""); base64Encoded = base64Encoded.Replace(" ", ""); var inputBytes = Encoding.ASCII.GetBytes(base64Encoded); using (var transform = new FromBase64Transform(FromBase64TransformMode.DoNotIgnoreWhiteSpaces)) { var outputBytes = new byte[transform.OutputBlockSize]; // Transform the data in chunks the size of InputBlockSize. const int inputBlockSize = 4; var currentOffset = 0; while (inputBytes.Length - currentOffset > inputBlockSize) { transform.TransformBlock(inputBytes, currentOffset, inputBlockSize, outputBytes, 0); currentOffset += inputBlockSize; memoryStream.Write(outputBytes, 0, transform.OutputBlockSize); } // Transform the final block of data. outputBytes = transform.TransformFinalBlock(inputBytes, currentOffset, inputBytes.Length - currentOffset); memoryStream.Write(outputBytes, 0, outputBytes.Length); } return memoryStream.ToArray(); } }
public void A0 () { byte[] input = { 114, 108, 112, 55, 81, 115, 110, 69 }; byte[] expected = { 174, 90, 123, 66, 201, 196 }; _algo = new FromBase64Transform (FromBase64TransformMode.DoNotIgnoreWhiteSpaces); TransformFinalBlock ("#A0", input, expected); }
/// <summary> /// Decodes a Base64 Encoding, and returns the Byte Array /// </summary> /// <param name="Text">The Encoding</param> /// <returns></returns> public static byte[] Decode(String Text) { FromBase64Transform x = new FromBase64Transform(); UTF8Encoding y = new UTF8Encoding(); byte[] OutBuf; Byte[] buffer = y.GetBytes(Text); OutBuf = new byte[buffer.Length * 3]; int BytesWritten = x.TransformBlock(buffer, 0, buffer.Length, OutBuf, 0); Byte[] NewBuf = new Byte[BytesWritten]; Array.Copy(OutBuf, 0, NewBuf, 0, NewBuf.Length); return(NewBuf); }
public void Decode(string inFileName, string outFileName) { var transform = new FromBase64Transform(); using (FileStream inFile = File.OpenRead(inFileName), outFile = File.Create(outFileName)) using (var cryptStream = new CryptoStream(inFile, transform, CryptoStreamMode.Read)) { var buffer = new byte[4096]; int bytesRead; while ((bytesRead = cryptStream.Read(buffer, 0, buffer.Length)) > 0) outFile.Write(buffer, 0, bytesRead); outFile.Flush(); } }
/// <summary> /// Decodes a base64 encoded string into the bytes it describes /// </summary> /// <param name="base64Encoded">The string to decode</param> /// <returns>A byte array that the base64 string described</returns> public static byte[] Decode(string base64Encoded) { // According to http://www.tribridge.com/blog/crm/blogs/brandon-kelly/2011-04-29/Solving-OutOfMemoryException-errors-when-attempting-to-attach-large-Base64-encoded-content-into-CRM-annotations.aspx // System.Convert.ToBase64String may leak a lot of memory // An OpenPop user reported that OutOfMemoryExceptions were thrown, and supplied the following // code for the fix. This should not have memory leaks. // The code is nearly identical to the example on MSDN: // http://msdn.microsoft.com/en-us/library/system.security.cryptography.frombase64transform.aspx#exampleToggle try { using (MemoryStream memoryStream = new MemoryStream()) { base64Encoded = base64Encoded.Replace("\r\n", ""); base64Encoded = base64Encoded.Replace("\t", ""); base64Encoded = base64Encoded.Replace(" ", ""); byte[] inputBytes = Encoding.ASCII.GetBytes(base64Encoded); using (FromBase64Transform transform = new FromBase64Transform(FromBase64TransformMode.DoNotIgnoreWhiteSpaces)) { byte[] outputBytes = new byte[transform.OutputBlockSize]; // Transform the data in chunks the size of InputBlockSize. const int inputBlockSize = 4; int currentOffset = 0; while (inputBytes.Length - currentOffset > inputBlockSize) { transform.TransformBlock(inputBytes, currentOffset, inputBlockSize, outputBytes, 0); currentOffset += inputBlockSize; memoryStream.Write(outputBytes, 0, transform.OutputBlockSize); } // Transform the final block of data. outputBytes = transform.TransformFinalBlock(inputBytes, currentOffset, inputBytes.Length - currentOffset); memoryStream.Write(outputBytes, 0, outputBytes.Length); } return memoryStream.ToArray(); } } catch (FormatException e) { DefaultLogger.Log.LogError("Base64: (FormatException) " + e.Message + "\r\nOn string: " + base64Encoded); throw; } }
//ԭʼbase64���� public static byte[] Base64Decode(byte[] source) { if ((source == null) || (source.Length == 0)) throw new ArgumentException("source is not valid"); FromBase64Transform fb64 = new FromBase64Transform(); MemoryStream stm = new MemoryStream(); int pos = 0; byte[] buff; while (pos + 4 < source.Length) { buff = fb64.TransformFinalBlock(source, pos, 4); stm.Write(buff, 0, buff.Length); pos += 4; } buff = fb64.TransformFinalBlock(source, pos, source.Length - pos); stm.Write(buff, 0, buff.Length); return stm.ToArray(); }
/// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> public static object LLSDParseOne(XmlTextReader reader) { SkipWS(reader); if (reader.NodeType != XmlNodeType.Element) throw new LLSDParseException("Expected an element"); string dtype = reader.LocalName; object ret = null; switch (dtype) { case "undef": { if (reader.IsEmptyElement) { reader.Read(); return null; } reader.Read(); SkipWS(reader); ret = null; break; } case "boolean": { if (reader.IsEmptyElement) { reader.Read(); return false; } reader.Read(); string s = reader.ReadString().Trim(); if (s == String.Empty || s == "false" || s == "0") ret = false; else if (s == "true" || s == "1") ret = true; else throw new LLSDParseException("Bad boolean value " + s); break; } case "integer": { if (reader.IsEmptyElement) { reader.Read(); return 0; } reader.Read(); ret = Convert.ToInt32(reader.ReadString().Trim()); break; } case "real": { if (reader.IsEmptyElement) { reader.Read(); return 0.0f; } reader.Read(); ret = Convert.ToDouble(reader.ReadString().Trim()); break; } case "uuid": { if (reader.IsEmptyElement) { reader.Read(); return UUID.Zero; } reader.Read(); ret = new UUID(reader.ReadString().Trim()); break; } case "string": { if (reader.IsEmptyElement) { reader.Read(); return String.Empty; } reader.Read(); ret = reader.ReadString(); break; } case "binary": { if (reader.IsEmptyElement) { reader.Read(); return new byte[0]; } if (reader.GetAttribute("encoding") != null && reader.GetAttribute("encoding") != "base64") { throw new LLSDParseException("Unknown encoding: " + reader.GetAttribute("encoding")); } reader.Read(); FromBase64Transform b64 = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces); byte[] inp = Encoding.UTF8.GetBytes(reader.ReadString()); ret = b64.TransformFinalBlock(inp, 0, inp.Length); break; } case "date": { reader.Read(); throw new Exception("LLSD TODO: date"); } case "map": { return LLSDParseMap(reader); } case "array": { return LLSDParseArray(reader); } default: throw new LLSDParseException("Unknown element <" + dtype + ">"); } if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != dtype) { throw new LLSDParseException("Expected </" + dtype + ">"); } reader.Read(); return ret; }
public override object ParseValue (string s, XmlNameTable nameTable, NSResolver nsmgr) { // If it isnt ASCII it isnt valid base64 data byte[] inArr = new System.Text.ASCIIEncoding().GetBytes(s); FromBase64Transform t = new FromBase64Transform(); return t.TransformFinalBlock(inArr, 0, inArr.Length); }
public void TransformFinalBlock_InputCount_Overflow () { byte[] input = new byte [16]; using (ICryptoTransform t = new FromBase64Transform ()) { t.TransformFinalBlock (input, 0, Int32.MaxValue); } }
public void TransformFinalBlock_InputCount_Negative () { byte[] input = new byte [16]; using (ICryptoTransform t = new FromBase64Transform ()) { t.TransformFinalBlock (input, 0, -1); } }
public void TransformFinalBlock_InputOffset_Overflow () { byte[] input = new byte [16]; using (ICryptoTransform t = new FromBase64Transform ()) { t.TransformFinalBlock (input, Int32.MaxValue, input.Length); } }
public void TransformFinalBlock_InputOffset_Negative () { byte[] input = new byte [16]; using (ICryptoTransform t = new FromBase64Transform ()) { t.TransformFinalBlock (input, -1, input.Length); } }
public void TransformFinalBlock_Input_Null () { using (ICryptoTransform t = new FromBase64Transform ()) { t.TransformFinalBlock (null, 0, 16); } }
public void TransformBlock_OutputOffset_Overflow () { byte[] input = new byte [16]; byte[] output = new byte [16]; using (ICryptoTransform t = new FromBase64Transform ()) { t.TransformBlock (input, 0, input.Length, output, Int32.MaxValue); } }
static Boolean RunBase64Test() { string origninal = "Hello from RSA Crypto."; byte[] origin = ConvertToByteArray(origninal); string transformed = Convert.ToBase64String(origin); byte[] ba1 = ConvertToByteArray(transformed); List<byte> b = new List<byte>(ba1); b.Insert(0, 0x0d); b.Insert(5, 0x0a); byte[] ba2 = b.ToArray(); MemoryStream ms1 = new MemoryStream(); CryptoStream cs1 = new CryptoStream(ms1, new FromBase64Transform(), CryptoStreamMode.Write); cs1.Write(ba1, 0, ba1.Length); cs1.Close(); MemoryStream ms2 = new MemoryStream(); CryptoStream cs2 = new CryptoStream(ms2, new FromBase64Transform(), CryptoStreamMode.Write); cs2.Write(ba2, 0, (int)ba2.Length); cs2.Close(); FromBase64Transform f = new FromBase64Transform(); if (f.CanReuseTransform == false) { Log.Comment("Transofrm should be able to be reused"); return false; } f.Clear(); if (!Compare(ms1.ToArray(), ms2.ToArray())) return false; if (!Compare(ms1.ToArray(), origin)) return false; return true; }
public string shadow_decrypt(string encyptedText) { fish = new Twofish(); fish.Mode = CipherMode.ECB; ms = new System.IO.MemoryStream(); //form.log("we were sent the IM with " + encyptedText); byte[] encyptedBytes = Utils.StringToBytes(encyptedText); ICryptoTransform decode = new FromBase64Transform(); //create DES Decryptor from our des instance ICryptoTransform decrypt = fish.CreateDecryptor(form.getKey(), encyptedBytes); System.IO.MemoryStream msD = new System.IO.MemoryStream(); CryptoStream cryptostreamDecode = new CryptoStream(new CryptoStream(msD,decrypt,CryptoStreamMode.Write),decode,CryptoStreamMode.Write); cryptostreamDecode.Write(encyptedBytes, 0, encyptedBytes.Length); cryptostreamDecode.Close(); byte[] bytOutD = msD.ToArray(); // we should now have our plain text back form.log("We decrypted "+encyptedText+" to " + Utils.BytesToString(bytOutD),Color.Red); return ""+this.indicator+""+Utils.BytesToString(bytOutD); }
public void SetUp () { _algo = new FromBase64Transform (); }
public void Dispose () { byte[] input = { 114, 108, 112, 55, 81, 115, 61, 61 }; byte[] expected = { 174, 90, 123, 66 }; byte[] output = null; using (ICryptoTransform t = new FromBase64Transform ()) { output = t.TransformFinalBlock (input, 0, input.Length); } AssertEquals ("IDisposable", expected.Length, output.Length); for (int i = 0; i < expected.Length; i++) AssertEquals ("IDisposable(" + i + ")", expected [i], output [i]); }
public void FromBase64_Read () { byte[] original = Encoding.UTF8.GetBytes ("aHR0cDovL3d3dy5nby1tb25vLmNvbS8="); DebugStream debug = new DebugStream (original); ICryptoTransform base64 = new FromBase64Transform (); cs = new CryptoStream (debug, base64, CryptoStreamMode.Read); byte[] data = new byte [1024]; int length = cs.Read (data, 0, data.Length); cs.Close (); string result = Encoding.UTF8.GetString (data, 0, length); Assert.AreEqual ("http://www.go-mono.com/", result, "ToBase64_Read"); }
public void FromBase64_Write () { string expected = "http://www.go-mono.com/"; byte[] data = Encoding.UTF8.GetBytes (expected); string temp = Convert.ToBase64String (data, 0, data.Length); data = Encoding.UTF8.GetBytes (temp); DebugStream debug = new DebugStream (); ICryptoTransform base64 = new FromBase64Transform (); cs = new CryptoStream (debug, base64, CryptoStreamMode.Write); cs.Write (data, 0, data.Length); cs.FlushFinalBlock (); byte[] encoded = debug.ToArray (); string result = Encoding.UTF8.GetString (encoded); Assert.AreEqual (expected, result, "FromBase64_Write"); }
public void TransformBlock_Output_Null () { byte[] input = new byte [16]; using (ICryptoTransform t = new FromBase64Transform ()) { t.TransformBlock (input, 0, input.Length, null, 0); } }
public static byte[] FromBase64(byte[] base64Data) { using (FromBase64Transform base64Transform = new FromBase64Transform()) { return GenericTransform(base64Transform, base64Data); } }
public static string Decode(string str, out MimeEncodingMethod encoding, out Encoding charset) { if (str == null) throw new ArgumentNullException("str"); charset = null; encoding = MimeEncodingMethod.None; Encoding lastCharset = null; var lastEncoding = MimeEncodingMethod.None; lock (mimeEncodedWordRegex) { var ret = mimeEncodedWordRegex.Replace(str, delegate(Match m) { // charset lastCharset = EncodingUtils.GetEncoding(m.Groups[1].Value); if (lastCharset == null) throw new FormatException(string.Format("{0} is an unsupported or invalid charset", m.Groups[1].Value)); // encoding ICryptoTransform transform; switch (m.Groups[2].Value) { case "b": case "B": lastEncoding = MimeEncodingMethod.Base64; transform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces); break; case "q": case "Q": lastEncoding = MimeEncodingMethod.QuotedPrintable; transform = new FromQuotedPrintableTransform(); break; default: throw new FormatException(string.Format("{0} is an invalid encoding", m.Groups[2].Value)); } return transform.TransformStringFrom(m.Groups[3].Value, lastCharset); }); charset = lastCharset; encoding = lastEncoding; return ret; } }
public void TransformBlock_OutputOffset_Negative () { byte[] input = new byte [16]; byte[] output = new byte [16]; using (ICryptoTransform t = new FromBase64Transform ()) { t.TransformBlock (input, 0, input.Length, output, -1); } }