/// <summary> Encodes a FileStream using Base64 (see RFC 1521)</summary> /// <param name="inputStream">The stream that needs to be encoded</param> /// <param name="outputFilePath">UNC path to file will store Base64 encoded ASCII text</param> /// <example> /// <code> /// MailEncoder.ConvertBase64(Stream, "file.txt"); /// </code> /// </example> internal static void ConvertToBase64(Stream inputStream, string outputFilePath) { //Create the file streams to handle the input and output files. FileStream fout = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(0); ToBase64Transform transformer = new ToBase64Transform(); //Create variables to help with read and write below. //This is intermediate storage for the encryption: byte[] bin = new byte[inputStream.Length / transformer.InputBlockSize * transformer.OutputBlockSize]; long rdlen = 0; //This is the total number of bytes written. long totlen = inputStream.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 encrypt and write to the output file. while(rdlen < totlen) { len = inputStream.Read(bin, 0, (int)inputStream.Length); encStream.Write(bin, 0, len); //inputBlock size(3) rdlen = (rdlen + ((len / transformer.InputBlockSize) * transformer.OutputBlockSize)); } encStream.Close(); fout.Close(); }
/// <summary> /// Converts byte-array to Base64 string. /// </summary> /// <param name="inputBytes">Byte array to convert.</param> /// <returns>A Base64 string representing the input byte-array.</returns> static public string ToBase64String(byte[] inputBytes) { StringBuilder sb = new StringBuilder(); ToBase64Transform base64Transform = new ToBase64Transform(); byte[] outputBytes = new byte[base64Transform.OutputBlockSize]; // Initializie the offset size. int inputOffset = 0; // Iterate through inputBytes transforming by blockSize. int inputBlockSize = base64Transform.InputBlockSize; while ((inputBytes.Length - inputOffset) > inputBlockSize) { base64Transform.TransformBlock( inputBytes, inputOffset, inputBlockSize, outputBytes, 0); inputOffset += base64Transform.InputBlockSize; sb.Append(Encoding.UTF8.GetString( outputBytes, 0, base64Transform.OutputBlockSize)); } // Transform the final block of data. outputBytes = base64Transform.TransformFinalBlock( inputBytes, inputOffset, (inputBytes.Length - inputOffset)); sb.Append(Encoding.UTF8.GetString(outputBytes, 0, outputBytes.Length)); return sb.ToString(); }
public override void ExecuteResult(ControllerContext context) { var responsetOutStream = context.HttpContext.Response.OutputStream; var base64Transformer = new ToBase64Transform(); var inputSize = base64Transformer.InputBlockSize; var outputSize = base64Transformer.OutputBlockSize; var outputBuffer = new byte[outputSize]; var inputBuffer = new byte[inputSize]; int eof = _stream.ReadByte(), bytesRead; inputBuffer[0] = (byte)eof; while ((bytesRead = _stream.Read(inputBuffer, 1, inputBuffer.Length - 1)) != 0) { if ((eof = _stream.ReadByte()) == -1) break; base64Transformer.TransformBlock(inputBuffer, 0, bytesRead + 1, outputBuffer, 0); responsetOutStream.Write(outputBuffer, 0, outputBuffer.Length); inputBuffer[0] = (byte)eof; } bytesRead++; var finalBlock = base64Transformer.TransformFinalBlock(inputBuffer, 0, bytesRead); responsetOutStream.Write(finalBlock, 0, finalBlock.Length); }
/// <summary> /// Encodes a Specific part of a Byte Array as Base64 /// </summary> /// <param name="buffer">The Byte Array to Encode</param> /// <param name="offset">The offset to begin encoding</param> /// <param name="length">The number of bytes to encode</param> /// <returns></returns> public static String Encode(byte[] buffer, int offset, int length) { length += offset; ToBase64Transform x = new ToBase64Transform(); byte[] OutBuf; MemoryStream ms = new MemoryStream(); int pos=offset; int size = 3; if (length<3) { size = length; } do { OutBuf = x.TransformFinalBlock(buffer,pos,size); pos += size; if (length-pos<size) { size = length-pos; } ms.Write(OutBuf,0,OutBuf.Length); }while(pos<length); OutBuf = ms.ToArray(); ms.Close(); UTF8Encoding y = new UTF8Encoding(); return(y.GetString(OutBuf)); }
public void TransformBlock_Dispose () { byte[] input = new byte [3]; byte[] output = new byte [4]; ToBase64Transform t = new ToBase64Transform (); t.Clear (); t.TransformBlock (input, 0, input.Length, output, 0); }
public void Properties () { ICryptoTransform t = new ToBase64Transform (); Assert ("CanReuseTransform", t.CanReuseTransform); Assert ("CanTransformMultipleBlocks", !t.CanTransformMultipleBlocks); AssertEquals ("InputBlockSize", 3, t.InputBlockSize); AssertEquals ("OutputBlockSize", 4, t.OutputBlockSize); }
public void Properties () { ICryptoTransform t = new ToBase64Transform (); Assert.IsTrue (t.CanReuseTransform, "CanReuseTransform"); Assert.IsTrue (!t.CanTransformMultipleBlocks, "CanTransformMultipleBlocks"); Assert.AreEqual (3, t.InputBlockSize, "InputBlockSize"); Assert.AreEqual (4, t.OutputBlockSize, "OutputBlockSize"); }
// reads bytes from a stream and writes the encoded // as base64 encoded characters. ( 60 chars on each row) public void EncodeStream( Stream ins , Stream outs ) { if( ( ins == null ) || ( outs == null ) ) throw new ArgumentNullException( "The input and output streams may not " + "be null."); ICryptoTransform base64 = new ToBase64Transform(); // the buffers byte[] plainText = new byte[ base64.InputBlockSize ]; byte[] cipherText = new byte[ base64.OutputBlockSize ]; int readLength = 0; int count = 0; byte[] newln = new byte[] { 13 , 10 }; //CR LF with mail // read through the stream until there // are no more bytes left while( true ) { // read some bytes readLength = ins.Read( plainText , 0 , plainText.Length ); // break when there is no more data if( readLength < 1 ) break; // transfrom and write the blocks. If the block size // is less than the InputBlockSize then write the final block if( readLength == plainText.Length ) { base64.TransformBlock( plainText , 0 , plainText.Length , cipherText , 0 ); // write the data outs.Write( cipherText , 0 , cipherText.Length ); // do this to output lines that // are 60 chars long count += cipherText.Length; if( count == 60 ) { outs.Write( newln , 0 , newln.Length ); count = 0; } } else { // convert the final blocks of bytes and write them cipherText = base64.TransformFinalBlock( plainText , 0 , readLength ); outs.Write( cipherText , 0 , cipherText.Length ); } } outs.Write( newln , 0 , newln.Length ); }
public void TransformBlock_WrongLength () { byte[] input = new byte [6]; byte[] output = new byte [8]; ToBase64Transform t = new ToBase64Transform (); t.TransformBlock (input, 0, 6, output, 0); // note only the first block has been processed Assert.AreEqual ("41-41-41-41-00-00-00-00", BitConverter.ToString (output)); }
public void Encode(string inFileName, string outFileName) { var transform = new ToBase64Transform(); using (FileStream inFile = File.OpenRead(inFileName), outFile = File.Create(outFileName)) using (var cryptStream = new CryptoStream(outFile, transform, CryptoStreamMode.Write)) { // I'm going to use a 4k buffer, tune this as needed byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inFile.Read(buffer, 0, buffer.Length)) > 0) cryptStream.Write(buffer, 0, bytesRead); cryptStream.FlushFinalBlock(); } }
internal static byte[] InternalTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { int num = 3; int num2 = 4; int num3 = inputCount / num; int num4 = inputCount % num; byte[] array = new byte[(inputCount == 0) ? 0 : ((inputCount + 2) / num * num2)]; int num5 = 0; for (int i = 0; i < num3; i++) { ToBase64Transform.InternalTransformBlock(inputBuffer, inputOffset, num, array, num5); inputOffset += num; num5 += num2; } byte[] encodeTable = Base64Constants.EncodeTable; switch (num4) { case 1: { int num6 = (int)inputBuffer[inputOffset]; array[num5] = encodeTable[num6 >> 2]; array[num5 + 1] = encodeTable[num6 << 4 & 48]; array[num5 + 2] = 61; array[num5 + 3] = 61; break; } case 2: { int num6 = (int)inputBuffer[inputOffset]; int num7 = (int)inputBuffer[inputOffset + 1]; array[num5] = encodeTable[num6 >> 2]; array[num5 + 1] = encodeTable[(num6 << 4 & 48) | num7 >> 4]; array[num5 + 2] = encodeTable[num7 << 2 & 60]; array[num5 + 3] = 61; break; } } return(array); }
/// <summary>Converts the specified region of the input byte array to base 64 and copies the result to the specified region of the output byte array.</summary> /// <returns>The number of bytes written.</returns> /// <param name="inputBuffer">The input to compute to base 64. </param> /// <param name="inputOffset">The offset into the input byte array from which to begin using data. </param> /// <param name="inputCount">The number of bytes in the input byte array to use as data. </param> /// <param name="outputBuffer">The output to which to write the result. </param> /// <param name="outputOffset">The offset into the output byte array from which to begin writing data. </param> /// <exception cref="T:System.ObjectDisposedException">The current <see cref="T:System.Security.Cryptography.ToBase64Transform" /> object has already been disposed. </exception> /// <exception cref="T:System.Security.Cryptography.CryptographicException">The data size is not valid. </exception> /// <exception cref="T:System.ArgumentException">The <paramref name="inputBuffer" /> parameter contains an invalid offset length.-or-The <paramref name="inputCount" /> parameter contains an invalid value.</exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="inputBuffer" /> parameter is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="inputBuffer" /> parameter requires a non-negative number.</exception> public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (this.m_disposed) { throw new ObjectDisposedException("TransformBlock"); } if (inputBuffer == null) { throw new ArgumentNullException("inputBuffer"); } if (outputBuffer == null) { throw new ArgumentNullException("outputBuffer"); } if (inputCount < 0) { throw new ArgumentException("inputCount", "< 0"); } if (inputCount > inputBuffer.Length) { throw new ArgumentException("inputCount", Locale.GetText("Overflow")); } if (inputOffset < 0) { throw new ArgumentOutOfRangeException("inputOffset", "< 0"); } if (inputOffset > inputBuffer.Length - inputCount) { throw new ArgumentException("inputOffset", Locale.GetText("Overflow")); } if (outputOffset < 0) { throw new ArgumentOutOfRangeException("outputOffset", "< 0"); } if (outputOffset > outputBuffer.Length - inputCount) { throw new ArgumentException("outputOffset", Locale.GetText("Overflow")); } ToBase64Transform.InternalTransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); return(this.OutputBlockSize); }
/// <summary>Converts the specified region of the specified byte array to base 64.</summary> /// <returns>The computed base 64 conversion.</returns> /// <param name="inputBuffer">The input to convert to base 64. </param> /// <param name="inputOffset">The offset into the byte array from which to begin using data. </param> /// <param name="inputCount">The number of bytes in the byte array to use as data. </param> /// <exception cref="T:System.ObjectDisposedException">The current <see cref="T:System.Security.Cryptography.ToBase64Transform" /> object has already been disposed. </exception> /// <exception cref="T:System.ArgumentException">The <paramref name="inputBuffer" /> parameter contains an invalid offset length.-or-The <paramref name="inputCount" /> parameter contains an invalid value.</exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="inputBuffer" /> parameter is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="inputBuffer" /> parameter requires a non-negative number.</exception> public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (this.m_disposed) { throw new ObjectDisposedException("TransformFinalBlock"); } if (inputBuffer == null) { throw new ArgumentNullException("inputBuffer"); } if (inputCount < 0) { throw new ArgumentException("inputCount", "< 0"); } if (inputOffset > inputBuffer.Length - inputCount) { throw new ArgumentException("inputCount", Locale.GetText("Overflow")); } if (inputCount > this.InputBlockSize) { throw new ArgumentOutOfRangeException(Locale.GetText("Invalid input length")); } return(ToBase64Transform.InternalTransformFinalBlock(inputBuffer, inputOffset, inputCount)); }
public void TransformBlock_NullInput () { byte[] output = new byte [4]; ToBase64Transform t = new ToBase64Transform (); t.TransformBlock (null, 0, 0, output, 0); }
public void TransformBlock_OutputOffset_Overflow () { byte[] input = new byte [15]; byte[] output = new byte [16]; using (ICryptoTransform t = new ToBase64Transform ()) { t.TransformBlock (input, 0, input.Length, output, Int32.MaxValue); } }
public void TransformFinalBlock_InputCount_Overflow () { byte[] input = new byte [15]; using (ICryptoTransform t = new ToBase64Transform ()) { t.TransformFinalBlock (input, 0, Int32.MaxValue); } }
//ԭʼbase64���� public static byte[] Base64Encode(byte[] source) { if ((source == null) || (source.Length == 0)) throw new ArgumentException("source is not valid"); ToBase64Transform tb64 = new ToBase64Transform(); MemoryStream stm = new MemoryStream(); int pos = 0; byte[] buff; while (pos + 3 < source.Length) { buff = tb64.TransformFinalBlock(source, pos, 3); stm.Write(buff, 0, buff.Length); pos += 3; } buff = tb64.TransformFinalBlock(source, pos, source.Length - pos); stm.Write(buff, 0, buff.Length); return stm.ToArray(); }
public void TransformFinalBlock_InputOffset_Overflow () { byte[] input = new byte [15]; using (ICryptoTransform t = new ToBase64Transform ()) { t.TransformFinalBlock (input, Int32.MaxValue, input.Length); } }
public void TransformFinalBlock_InputCount_Negative () { byte[] input = new byte [15]; using (ICryptoTransform t = new ToBase64Transform ()) { t.TransformFinalBlock (input, 0, -1); } }
public void TransformFinalBlock_Input_Null () { using (ICryptoTransform t = new ToBase64Transform ()) { t.TransformFinalBlock (null, 0, 15); } }
public void TransformFinalBlock_InputOffset_Negative () { byte[] input = new byte [15]; using (ICryptoTransform t = new ToBase64Transform ()) { t.TransformFinalBlock (input, -1, input.Length); } }
public void ToBase64_Write () { byte[] data = Encoding.UTF8.GetBytes ("http://www.go-mono.com/"); DebugStream debug = new DebugStream (); ICryptoTransform base64 = new ToBase64Transform (); 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 ("aHR0cDovL3d3dy5nby1tb25vLmNvbS8=", result, "ToBase64_Write"); }
public void TransformBlock_NullOutput () { byte[] input = new byte [3]; ToBase64Transform t = new ToBase64Transform (); t.TransformBlock (input, 0, 3, null, 0); }
public void ToBase64_Read () { byte[] original = Encoding.UTF8.GetBytes ("http://www.go-mono.com/"); DebugStream debug = new DebugStream (original); ICryptoTransform base64 = new ToBase64Transform (); 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 ("aHR0cDovL3d3dy5nby1tb25vLmNvbS8=", result, "ToBase64_Read"); }
public void TransformFinalBlock_Null () { byte[] input = new byte [3]; ToBase64Transform t = new ToBase64Transform (); t.TransformFinalBlock (null, 0, 3); }
public string shadow_encrypt(string plainText) { fish = new Twofish(); fish.Mode = CipherMode.ECB; ms = new System.IO.MemoryStream(); //form.log("we were guna send the IM with " + plainText); byte [] plainBytes = Utils.StringToBytes(plainText); ICryptoTransform encode = new ToBase64Transform(); ICryptoTransform encrypt = fish.CreateEncryptor(form.getKey(),plainBytes); CryptoStream cryptostream = new CryptoStream(new CryptoStream(ms,encode,CryptoStreamMode.Write),encrypt,CryptoStreamMode.Write); cryptostream.Write(plainBytes,0,plainBytes.Length); cryptostream.Close(); byte[] bytOut = ms.ToArray(); form.log("We encrypted "+plainText+" to "+Utils.BytesToString(bytOut),Color.DarkRed); return Utils.BytesToString(bytOut); }
public void TransformFinalBlock_WrongLength () { byte[] input = new byte [6]; ToBase64Transform t = new ToBase64Transform (); t.TransformFinalBlock (input, 0, 6); }
public static byte[] ToBase64(this byte[] binaryData) { using (ToBase64Transform base64Transform = new ToBase64Transform()) { return GenericTransform(base64Transform, binaryData); } }
public void TransformFinalBlock_SmallLength () { byte[] input = new byte [2]; // smaller than InputBlockSize ToBase64Transform t = new ToBase64Transform (); t.TransformFinalBlock (input, 0, 2); }
public void TransformFinalBlock_Dispose () { byte[] input = new byte [3]; ToBase64Transform t = new ToBase64Transform (); t.Clear (); t.TransformFinalBlock (input, 0, input.Length); }
private static string Encode(string str, MimeEncodingMethod encoding, Encoding charset, bool doFold, int foldingLimit, int foldingOffset, string foldingString) { if (str == null) throw new ArgumentNullException("str"); if (charset == null) throw new ArgumentNullException("charset"); if (doFold) { if (foldingLimit < 1) throw new ArgumentOutOfRangeException("foldingLimit", foldingLimit, "must be greater than 1"); if (foldingOffset < 0) throw new ArgumentOutOfRangeException("foldingOffset", foldingOffset, "must be greater than zero"); if (foldingLimit <= foldingOffset) throw new ArgumentOutOfRangeException("foldingOffset", foldingOffset, "must be less than foldingLimit"); if (foldingString == null) throw new ArgumentNullException("foldingString"); } ICryptoTransform transform; char encodingChar; switch (encoding) { case MimeEncodingMethod.Base64: transform = new ToBase64Transform(); encodingChar = 'b'; break; case MimeEncodingMethod.QuotedPrintable: transform = new ToQuotedPrintableTransform(); encodingChar = 'q'; break; default: throw new System.ComponentModel.InvalidEnumArgumentException("encoding", (int)encoding, typeof(MimeEncodingMethod)); } var preambleText = string.Format("=?{0}?{1}?", charset.BodyName, encodingChar); if (!doFold) return preambleText + transform.TransformStringTo(str, charset) + "?="; // folding var ret = new StringBuilder(); var preamble = Encoding.ASCII.GetBytes(preambleText); var firstLine = true; var inputCharBuffer = str.ToCharArray(); var inputCharOffset = 0; var outputBuffer = new byte[foldingLimit]; var ambleLength = preamble.Length + mimeEncodingPostamble.Length; var outputLimit = foldingLimit - (foldingOffset + ambleLength); if (outputLimit <= 0) throw new ArgumentOutOfRangeException("foldingLimit", foldingLimit, "too short"); // copy preamble to buffer Buffer.BlockCopy(preamble, 0, outputBuffer, 0, preamble.Length); for (;;) { var inputBlockSizeLimit = (outputLimit * transform.InputBlockSize) / transform.OutputBlockSize - 1; var transformCharCount = 0; var outputCount = preamble.Length; // decide char count to transform for (transformCharCount = inputBlockSizeLimit / charset.GetMaxByteCount(1);; transformCharCount++) { if (inputCharBuffer.Length <= inputCharOffset + transformCharCount) { transformCharCount = inputCharBuffer.Length - inputCharOffset; break; } if (inputBlockSizeLimit <= charset.GetByteCount(inputCharBuffer, inputCharOffset, transformCharCount + 1)) break; } // transform chars byte[] transformed = null; for (;;) { var t = transform.TransformBytes(charset.GetBytes(inputCharBuffer, inputCharOffset, transformCharCount)); if (transformed == null || t.Length <= outputLimit) { transformed = t; if (inputCharBuffer.Length <= inputCharOffset + transformCharCount + 1) break; transformCharCount++; continue; } else { transformCharCount--; break; } } if (outputBuffer.Length < ambleLength + transformed.Length) throw new ArgumentOutOfRangeException("foldingLimit", foldingLimit, string.Format("too short, at least {0} is required", ambleLength + transformed.Length)); // copy transformed chars to buffer Buffer.BlockCopy(transformed, 0, outputBuffer, outputCount, transformed.Length); outputCount += transformed.Length; // copy postanble to buffer Buffer.BlockCopy(mimeEncodingPostamble, 0, outputBuffer, outputCount, mimeEncodingPostamble.Length); outputCount += mimeEncodingPostamble.Length; ret.Append(Encoding.ASCII.GetString(outputBuffer, 0, outputCount)); inputCharOffset += transformCharCount; if (inputCharOffset < inputCharBuffer.Length) { ret.Append(foldingString); if (firstLine) { outputLimit = foldingLimit - ambleLength; firstLine = false; } } else { break; } } return ret.ToString(); }
public void TransformBlock_OutputOffset_Negative () { byte[] input = new byte [15]; byte[] output = new byte [16]; using (ICryptoTransform t = new ToBase64Transform ()) { t.TransformBlock (input, 0, input.Length, output, -1); } }