public void InvalidInput_FromBase64Transform() { byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa"); ICryptoTransform transform = new FromBase64Transform(); InvalidInput_Base64Transform(transform); // These exceptions only thrown in FromBase transform.Dispose(); Assert.Throws<ObjectDisposedException>(() => transform.TransformBlock(data_4bytes, 0, 4, null, 0)); Assert.Throws<ObjectDisposedException>(() => transform.TransformFinalBlock(Array.Empty<byte>(), 0, 0)); }
public static void ValidateFromBase64_NoPadding(string data) { using (var transform = new FromBase64Transform()) { byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data); byte[] outputBytes = new byte[100]; using (var ms = new MemoryStream(inputBytes)) using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Read)) { int bytesRead = cs.Read(outputBytes, 0, outputBytes.Length); // Missing padding bytes not supported (no exception, however) Assert.NotEqual(inputBytes.Length, bytesRead); } } }
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]); } }
/// <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; } }
public static byte[] DecodeFromFile(string inFileName) { FromBase64Transform myTransform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces); byte[] myOutputBytes = new byte[myTransform.OutputBlockSize]; //Open the input and output files. FileStream myInputFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read); //Retrieve the file contents into a byte array. byte[] myInputBytes = new byte[myInputFile.Length]; myInputFile.Read(myInputBytes, 0, myInputBytes.Length); MemoryStream outputDataStream = new MemoryStream(myInputBytes.Length); //Transform the data in chunks the size of InputBlockSize. int i = 0; int inputBlockSize = 4; while (myInputBytes.Length - i > inputBlockSize) { int nOutput = myTransform.TransformBlock(myInputBytes, i, inputBlockSize, myOutputBytes, 0); i += inputBlockSize; if (nOutput > 0) { outputDataStream.Write(myOutputBytes, 0, nOutput); } } //Transform the final block of data. myOutputBytes = myTransform.TransformFinalBlock(myInputBytes, i, myInputBytes.Length - i); outputDataStream.Write(myOutputBytes, 0, myOutputBytes.Length); //Free up any used resources. myTransform.Clear(); myInputFile.Close(); outputDataStream.Position = 0; byte[] outputData = new byte[outputDataStream.Length]; outputDataStream.Read(outputData, 0, (int)outputDataStream.Length); outputDataStream.Close(); return(outputData); }
public static async Task <Stream> DecryptBased64(string password, Stream inputStream) { await using var based64Stream = new MemoryStream(); await inputStream.CopyToAsync(based64Stream); await inputStream.DisposeAsync(); based64Stream.Position = 0; using var transformer = new FromBase64Transform(); await using var encryptedStream = new MemoryStream(); await using var cryptoStream = new CryptoStream(based64Stream, transformer, CryptoStreamMode.Read); await cryptoStream.CopyToAsync(encryptedStream); encryptedStream.Position = 0; var resultStream = await Decrypt(password, encryptedStream); return(resultStream); }
public static byte[] Base64Decode(byte[] source) { if (source == null || source.Length == 0) { throw new ArgumentException("source is not valid"); } FromBase64Transform fromBase64Transform = new FromBase64Transform(); MemoryStream memoryStream = new MemoryStream(); int i; byte[] array; for (i = 0; i + 4 < source.Length; i += 4) { array = fromBase64Transform.TransformFinalBlock(source, i, 4); memoryStream.Write(array, 0, array.Length); } array = fromBase64Transform.TransformFinalBlock(source, i, source.Length - i); memoryStream.Write(array, 0, array.Length); return(memoryStream.ToArray()); }
public void InvalidInput_FromBase64Transform() { byte[] data_4bytes = Text.Encoding.ASCII.GetBytes("aaaa"); ICryptoTransform transform = new FromBase64Transform(); AssertExtensions.Throws <ArgumentNullException>("inputBuffer", () => transform.TransformBlock(null, 0, 0, null, 0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("inputOffset", () => transform.TransformBlock(Array.Empty <byte>(), -1, 0, null, 0)); AssertExtensions.Throws <ArgumentNullException>("outputBuffer", () => transform.TransformBlock(data_4bytes, 0, 4, null, 0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("inputCount", () => transform.TransformBlock(Array.Empty <byte>(), 0, 1, null, 0)); AssertExtensions.Throws <ArgumentException>(null, () => transform.TransformBlock(Array.Empty <byte>(), 1, 0, null, 0)); AssertExtensions.Throws <ArgumentNullException>("inputBuffer", () => transform.TransformFinalBlock(null, 0, 0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("inputOffset", () => transform.TransformFinalBlock(Array.Empty <byte>(), -1, 0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("inputOffset", () => transform.TransformFinalBlock(Array.Empty <byte>(), -1, 0)); AssertExtensions.Throws <ArgumentException>(null, () => transform.TransformFinalBlock(Array.Empty <byte>(), 1, 0)); // These exceptions only thrown in FromBase transform.Dispose(); Assert.Throws <ObjectDisposedException>(() => transform.TransformBlock(data_4bytes, 0, 4, null, 0)); Assert.Throws <ObjectDisposedException>(() => transform.TransformFinalBlock(Array.Empty <byte>(), 0, 0)); }
/// <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) { try { 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()); } } catch (Exception) { return(new byte[0]); } }
/// <summary> /// Converts a base64 string to a byte array. /// </summary> /// <param name="s">The s.</param> /// <returns></returns> public static byte[] FromBase64(string s) { byte[] bytes; using (var writer = new MemoryStream()) { byte[] bufferedOutputBytes; //char[] inputBytes = s.ToCharArray(); byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(s); using (FromBase64Transform transformation = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces)) { bufferedOutputBytes = new byte[transformation.OutputBlockSize]; // Transform the data in chunks the size of InputBlockSize. var i = 0; while (inputBytes.Length - i > 4) { transformation.TransformBlock(inputBytes, i, 4, bufferedOutputBytes, 0); i += 4; writer.Write(bufferedOutputBytes, 0, transformation.OutputBlockSize); } // Transform the final block of data. bufferedOutputBytes = transformation.TransformFinalBlock(inputBytes, i, inputBytes.Length - i); writer.Write(bufferedOutputBytes, 0, bufferedOutputBytes.Length); // Free up any used resources. transformation.Clear(); } writer.Position = 0; bytes = writer.GetBuffer(); writer.Close(); } return(bytes); }
//原始base64解码 public static byte[] Base64Decode(byte[] source) { if ((source == null) || (source.Length == 0)) { throw new ArgumentException("source is not valid"); } FromBase64Transform fb64 = null; MemoryStream stm = null; try { fb64 = new FromBase64Transform(); 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()); } finally { if (fb64 != null) { fb64.Dispose(); } if (stm != null) { stm.Dispose(); } } }
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 async Task Base64EncodeAndDecodeMergedStream(MergedStream mergedStream, string expectedData) { using (var toBase64Transform = new ToBase64Transform()) using (var encodedStream = new CryptoStream(mergedStream, toBase64Transform, CryptoStreamMode.Read)) using (var memoryStream = new MemoryStream()) { await encodedStream.CopyToAsync(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(memoryStream, Encoding.ASCII, true, 1024, true)) _output.WriteLine(await streamReader.ReadToEndAsync()); memoryStream.Seek(0, SeekOrigin.Begin); using (var fromBase64Transform = new FromBase64Transform()) using (var decodedStream = new CryptoStream(memoryStream, fromBase64Transform, CryptoStreamMode.Read)) using (var streamReader = new StreamReader(decodedStream)) { var data = await streamReader.ReadToEndAsync(); Assert.Equal(expectedData, data); } } }
public static byte[] DecodeBase64Byte(this byte[] source) { byte[] buffer2; if ((source == null) || (source.Length == 0)) { throw new ArgumentException("source is not valid"); } FromBase64Transform transform = new FromBase64Transform(); MemoryStream stream = new MemoryStream(); int inputOffset = 0; try { byte[] buffer; while ((inputOffset + 4) < source.Length) { buffer = transform.TransformFinalBlock(source, inputOffset, 4); stream.Write(buffer, 0, buffer.Length); inputOffset += 4; } buffer = transform.TransformFinalBlock(source, inputOffset, source.Length - inputOffset); stream.Write(buffer, 0, buffer.Length); buffer2 = stream.ToArray(); } catch (Exception exception) { throw exception; } finally { if (stream != null) { stream.Close(); } } return(buffer2); }
// Decode inStream to outStream private static void Decode(Stream inStream, Stream outStream) { using (var base64Transform = new FromBase64Transform()) { const int inputBlockSize = 4; // base64Transform.InputBlockSize is inexplicably == 1 var inputBytes = new byte[inputBlockSize * BucketSize]; var outputBytes = new byte[base64Transform.OutputBlockSize]; var bytesRead = inStream.Read(inputBytes, 0, inputBytes.Length); while (bytesRead != 0) { var offset = 0; while (bytesRead - offset > inputBlockSize) { var bytesTransformed = base64Transform.TransformBlock( inputBytes, offset, inputBlockSize, outputBytes, 0); outStream.Write(outputBytes, 0, bytesTransformed); offset += inputBlockSize; } if (bytesRead - offset > 0) { outputBytes = base64Transform.TransformFinalBlock( inputBytes, offset, bytesRead - offset); outStream.Write(outputBytes, 0, outputBytes.Length); } bytesRead = inStream.Read(inputBytes, 0, inputBytes.Length); } } }
public void SetUp() { _algo = new FromBase64Transform(); }
public static void ValidateFromBase64CryptoStream(string data, string encoding) { using (var transform = new FromBase64Transform()) { ValidateCryptoStream(data, encoding, transform); } }
public static void ValidateWhitespace(string expected, string data) { byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data); byte[] outputBytes = new byte[100]; // Verify default of FromBase64TransformMode.IgnoreWhiteSpaces using (var base64Transform = new FromBase64Transform()) using (var ms = new MemoryStream(inputBytes)) using (var cs = new CryptoStream(ms, base64Transform, CryptoStreamMode.Read)) { int bytesRead = cs.Read(outputBytes, 0, outputBytes.Length); string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, bytesRead); Assert.Equal(expected, outputString); } // Verify explicit FromBase64TransformMode.IgnoreWhiteSpaces using (var base64Transform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces)) using (var ms = new MemoryStream(inputBytes)) using (var cs = new CryptoStream(ms, base64Transform, CryptoStreamMode.Read)) { int bytesRead = cs.Read(outputBytes, 0, outputBytes.Length); string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, bytesRead); Assert.Equal(expected, outputString); } // Verify FromBase64TransformMode.DoNotIgnoreWhiteSpaces using (var base64Transform = new FromBase64Transform(FromBase64TransformMode.DoNotIgnoreWhiteSpaces)) using (var ms = new MemoryStream(inputBytes)) using (var cs = new CryptoStream(ms, base64Transform, CryptoStreamMode.Read)) { Assert.Throws<FormatException>(() => cs.Read(outputBytes, 0, outputBytes.Length)); } }
public static void ValidateFromBase64TransformFinalBlock(string expected, string encoding) { using (var transform = new FromBase64Transform()) { byte[] inputBytes = Text.Encoding.ASCII.GetBytes(encoding); Assert.True(inputBytes.Length > 4); // Test passing blocks > 4 characters to TransformFinalBlock (supported) byte[] outputBytes = transform.TransformFinalBlock(inputBytes, 0, inputBytes.Length); string outputString = Text.Encoding.ASCII.GetString(outputBytes, 0, outputBytes.Length); Assert.Equal(expected, outputString); } }
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); } }
/// <summary> /// Converts a file encoded in base64 back to its original encoding. /// </summary> /// <param name="srcFile">Input from Base64 encoded data file..</param> /// <param name="targetFile">Output containing decoded data.</param> public void DecodeFileFromBase64(string srcFile, string targetFile) { TextReader reader = null; FileStream fs = null; FileStream fsIn = null; long sourceSize = new FileInfo(srcFile).Length; try { fs = new FileStream(targetFile, FileMode.Create, FileAccess.Write); // Read entire file in a single operation. if (sourceSize <= CharsToRead) { reader = new StreamReader(srcFile, Encoding.ASCII); string encodedChars = reader.ReadToEnd(); try { byte[] bytes = Convert.FromBase64String(encodedChars); fs.Write(bytes, 0, bytes.Length); } catch (FormatException ex) { _msg.Length = 0; _msg.Append(AppMessages.FormatErrorMessage(ex)); throw new FormatException(_msg.ToString()); } } else { // Read file as a stream into a buffer. // Instantiate a FromBase64Transform object. FromBase64Transform transf = new FromBase64Transform(); // Arrays to hold input and output bytes. byte[] inputBytes = new byte[transf.InputBlockSize]; byte[] outputBytes = new byte[transf.OutputBlockSize]; int bytesRead = 0; int bytesWritten = 0; long totalBytesRead = 0; fsIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read); do { bytesRead = fsIn.Read(inputBytes, 0, inputBytes.Length); totalBytesRead += bytesRead; bytesWritten = transf.TransformBlock(inputBytes, 0, bytesRead, outputBytes, 0); fs.Write(outputBytes, 0, bytesWritten); } while (sourceSize - totalBytesRead > transf.InputBlockSize); // Transform the final block of data. bytesRead = fsIn.Read(inputBytes, 0, inputBytes.Length); byte[] finalOutputBytes = transf.TransformFinalBlock(inputBytes, 0, bytesRead); fs.Write(finalOutputBytes, 0, finalOutputBytes.Length); // Clear Base64Transform object. transf.Clear(); } } catch (IOException ex) { _msg.Length = 0; _msg.Append(AppMessages.FormatErrorMessage(ex)); throw new IOException(_msg.ToString()); } finally { if (reader != null) { reader.Close(); } if (fs != null) { fs.Close(); fs.Dispose(); } if (fsIn != null) { fsIn.Close(); fs.Dispose(); } } }
/// <summary> /// Captures page screenshot. /// </summary> /// <param name="webview">The WebView control.</param> /// <param name="settings">The capture settings or null.</param> /// <param name="targetStream">A stream to save the captured image to.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The task object representing the asynchronous operation.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="webview"/> or <paramref name="targetStream"/> is null. /// </exception> /// <exception cref="DevToolsProtocolException"> /// An error occurred while trying to execute a DevTools Protocol method. /// </exception> /// <exception cref="InvalidOperationException">Other error occurred.</exception> public static async Task CaptureScreenshotAsync(this IChromiumWebView webview, PageCaptureSettings settings, Stream targetStream, CancellationToken cancellationToken) { if (webview is null) { throw new ArgumentNullException(nameof(webview)); } if (targetStream is null) { throw new ArgumentNullException(nameof(targetStream)); } CefDictionaryValue args; if (settings is null) { args = null; } else { args = new CefDictionaryValue(); if (settings.Format == ImageCompressionFormat.Jpeg) { args.SetString("format", "jpeg"); if (settings.Quality.HasValue) { args.SetInt("quality", settings.Quality.Value); } } if (!settings.FromSurface) { args.SetBool("fromSurface", false); } if (settings.Viewport != null) { PageViewport viewport = settings.Viewport; var viewportDict = new CefDictionaryValue(); viewportDict.SetDouble("x", viewport.X); viewportDict.SetDouble("y", viewport.Y); viewportDict.SetDouble("width", viewport.Width); viewportDict.SetDouble("height", viewport.Height); viewportDict.SetDouble("scale", viewport.Scale); args.SetDictionary("clip", viewportDict); } if (settings.CaptureBeyondViewport) { args.SetBool("captureBeyondViewport", true); } } byte[] rv = await ExecuteDevToolsMethodInternalAsync(webview, "Page.captureScreenshot", args, cancellationToken).ConfigureAwait(false); if (rv != null && rv.Length > 11 && rv[rv.Length - 1] == '}' && rv[rv.Length - 2] == '"' && "{\"data\":\"".Equals(Encoding.ASCII.GetString(rv, 0, 9), StringComparison.Ordinal)) { using (var input = new MemoryStream(rv, 9, rv.Length - 11)) using (var base64Transform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces)) using (var cryptoStream = new CryptoStream(input, base64Transform, CryptoStreamMode.Read)) { await cryptoStream.CopyToAsync(targetStream, 4096, cancellationToken).ConfigureAwait(false); await targetStream.FlushAsync(cancellationToken).ConfigureAwait(false); } } else { throw new InvalidOperationException(); } }
/// <summary> /// This encrypts our data using twofish and then converts to base64 and then reverses the process /// </summary> /// <param name="Key">The Key to use for the encryption stage</param> /// <param name="plainText">The plain text to encrypt and encode and then to compare when it has been decoded and decrypted</param> static void Cascade(ref byte[] Key, ref byte[] plainText) { Twofish fish = new Twofish(); fish.Mode = CipherMode.ECB; System.IO.MemoryStream ms = new System.IO.MemoryStream(); // create an encoder ICryptoTransform encode = new ToBase64Transform(); //create Twofish Encryptor from this instance ICryptoTransform encrypt = fish.CreateEncryptor(Key, plainText); // we use the plainText as the IV as in ECB mode the IV is not used // we have to work backwords defining the last link in the chain first CryptoStream cryptostreamEncode = new CryptoStream(ms, encode, CryptoStreamMode.Write); CryptoStream cryptostream = new CryptoStream(cryptostreamEncode, encrypt, CryptoStreamMode.Write); // or we could do this as we don't need to use cryptostreamEncode //CryptoStream cryptostream = new CryptoStream(new CryptoStream(ms,encode,CryptoStreamMode.Write), // encrypt,CryptoStreamMode.Write); cryptostream.Write(plainText, 0, plainText.Length); cryptostream.Close(); //long pos = ms.Position; // our stream is closed so we cannot find out what the size of the buffer is - daft byte[] bytOut = ms.ToArray(); // and now we undo what we did // create a decoder ICryptoTransform decode = new FromBase64Transform(); //create DES Decryptor from our des instance ICryptoTransform decrypt = fish.CreateDecryptor(Key, plainText); System.IO.MemoryStream msD = new System.IO.MemoryStream(); //create crypto stream set to read and do a Twofish decryption transform on incoming bytes CryptoStream cryptostreamD = new CryptoStream(msD, decrypt, CryptoStreamMode.Write); CryptoStream cryptostreamDecode = new CryptoStream(cryptostreamD, decode, CryptoStreamMode.Write); // again we could do the following //CryptoStream cryptostreamDecode = new CryptoStream(new CryptoStream(msD,decrypt,CryptoStreamMode.Write), // decode,CryptoStreamMode.Write); //write out the decrypted stream cryptostreamDecode.Write(bytOut, 0, bytOut.Length); cryptostreamDecode.Close(); byte[] bytOutD = msD.ToArray(); // we should now have our plain text back for (int i = 0; i < plainText.Length; i++) { if (bytOutD[i] != plainText[i]) { Trace.Write("Plaintext match failure"); break; } } }
private static void Dispose(FileStream outputFileStream, FromBase64Transform transform) { transform.Clear(); outputFileStream.Close(); }
public static async IAsyncEnumerable <RequestMessage> UnpackJsonRequestBodyAsync( Stream body, CancellationToken cancellationToken ) { var document = await JsonDocument.ParseAsync(body, new JsonDocumentOptions { AllowTrailingCommas = true, //CommentHandling = JsonCommentHandling.Allow, MaxDepth = 100 }, cancellationToken); var rootRequests = document.RootElement.EnumerateArray(); foreach (var request in rootRequests) { var requestObject = request.EnumerateObject(); string requestProtocolVersion = "1.1"; string requestMethod = null; string requestUri = null; HeaderCollection requestHeaders = null; Stream requestBody = null; foreach (var objProperty in requestObject) { switch (objProperty.Name.ToLower()) { case "protocol-version": { requestProtocolVersion = objProperty.Value.GetString(); break; } case "method": { requestMethod = objProperty.Value.GetString(); break; } case "uri": { requestUri = objProperty.Value.GetString(); break; } case "headers": { requestHeaders = new HeaderCollection(HttpHeaderType.RequestHeader); foreach (var header in objProperty.Value.EnumerateObject()) { switch (header.Value.ValueKind) { case JsonValueKind.Array: requestHeaders.Add(header.Name, header.Value.EnumerateArray().Cast <string>().ToList()); break; case JsonValueKind.String: requestHeaders.Add(header.Name, header.Value.GetString()); break; case JsonValueKind.Undefined: break; default: throw new NotSupportedException(); } } break; } case "body": { switch (objProperty.Value.ValueKind) { case JsonValueKind.Null: case JsonValueKind.Undefined: break; case JsonValueKind.Object: throw new NotImplementedException(); break; case JsonValueKind.Array: throw new NotImplementedException(); break; case JsonValueKind.String: using (var transform = new FromBase64Transform()) { requestBody = new CryptoStream( new MemoryStream(Encoding.ASCII.GetBytes(objProperty.Value.GetString())), transform, CryptoStreamMode.Read ); } break; case JsonValueKind.Number: throw new NotImplementedException(); break; case JsonValueKind.True: throw new NotImplementedException(); break; case JsonValueKind.False: throw new NotImplementedException(); break; default: throw new ArgumentOutOfRangeException(); } break; } default: { throw new RedTransportException("UnknownJsonRequestKey"); } } } if (string.IsNullOrWhiteSpace(requestMethod)) { requestMethod = "GET"; //throw new RedTransportException("UnknownJsonRequestMethod"); } if (string.IsNullOrWhiteSpace(requestUri)) { throw new RedTransportException("UnknownJsonRequestUri"); } if (System.Uri.CheckHostName(requestUri) == UriHostNameType.Unknown) { string path; string queryString; var questionMarkIndex = requestUri.IndexOf('?'); if (questionMarkIndex >= 0) { path = requestUri.Substring(0, questionMarkIndex); queryString = requestMethod.Substring(questionMarkIndex + 1); } else { path = requestUri; queryString = string.Empty; } if (!path.StartsWith('/')) { path = '/' + path; } var scheme = "http"; var host = string.Empty; var pathBase = string.Empty; var rawTarget = string.Empty; yield return(new RequestMessage( requestProtocolVersion, scheme, host, pathBase, path, queryString, rawTarget, requestMethod, requestHeaders, requestBody )); } else { var uri = new Uri(requestUri); yield return(new RequestMessage( requestProtocolVersion, uri, requestMethod, requestHeaders, requestBody )); } } }
/// <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 = Util.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 void TransformFinalBlock_Input_Null() { using (ICryptoTransform t = new FromBase64Transform()) { t.TransformFinalBlock(null, 0, 16); } }