Beispiel #1
0
        //原始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());
        }
Beispiel #2
0
        public static string SignatureMessage(string certFileName, string password, byte[] dataTobeSign, string outputFileName)
        {
            byte[] pfxCert = File.ReadAllBytes(certFileName);
            //  byte[] dataTobeSign = File.ReadAllBytes(dataFileName);
            SecureString pwd = new SecureString();

            char[] pwdCharArray = password.ToCharArray();
            for (int i = 0; i < pwdCharArray.Length; i++)
            {
                pwd.AppendChar(pwdCharArray[i]);
            }
            X509Certificate2 cert   = new X509Certificate2(pfxCert, pwd);
            CmsSigner        signer = new CmsSigner(cert);

            signer.DigestAlgorithm = new Oid("1.3.14.3.2.26", "sha1");

            signer.IncludeOption = X509IncludeOption.EndCertOnly;

            ContentInfo signedData = new ContentInfo(dataTobeSign);
            SignedCms   cms        = new SignedCms(signedData, true);

            cms.ComputeSignature(signer);
            byte[] signature = cms.Encode();

            //base64
            ToBase64Transform base64Transform = new ToBase64Transform();

            byte[]       inputBytes       = signature;
            byte[]       outputBytes      = new byte[base64Transform.OutputBlockSize];
            int          inputOffset      = 0;
            int          inputBlockSize   = base64Transform.InputBlockSize;
            MemoryStream outputDataStream = new MemoryStream();

            while (inputBytes.Length - inputOffset > inputBlockSize)
            {
                base64Transform.TransformBlock(inputBytes, inputOffset, inputBytes.Length - inputOffset, outputBytes, 0);

                inputOffset += base64Transform.InputBlockSize;
                outputDataStream.Write(outputBytes, 0, base64Transform.OutputBlockSize);
            }
            outputBytes = base64Transform.TransformFinalBlock(inputBytes, inputOffset, inputBytes.Length - inputOffset);
            outputDataStream.Write(outputBytes, 0, outputBytes.Length);

            outputDataStream.Position = 0;
            byte[] outputData = new byte[outputDataStream.Length];
            outputDataStream.Read(outputData, 0, (int)outputDataStream.Length);
            outputDataStream.Close();
            if (string.IsNullOrEmpty(outputFileName))
            {
                string outputStr = System.Text.Encoding.Default.GetString(outputData);
                Console.WriteLine("输出字符");
                Console.WriteLine(outputStr);
                Console.ReadKey();
            }
            else
            {
                File.WriteAllBytes(outputFileName, outputData);
            }
            return("");
        }
 public void TransformFinalBlock_Input_Null()
 {
     using (ICryptoTransform t = new ToBase64Transform())
     {
         t.TransformFinalBlock(null, 0, 15);
     }
 }
        public void TransformFinalBlock_Null()
        {
            byte[]            input = new byte [3];
            ToBase64Transform t     = new ToBase64Transform();

            t.TransformFinalBlock(null, 0, 3);
        }
Beispiel #5
0
        // Encode inStream to outStream
        public static void Encode(Stream inStream, Stream outStream, int breakCol = 0)
        {
            using (var base64Transform = new ToBase64Transform())
            {
                var col         = 0;
                var inputBytes  = new byte[base64Transform.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 > base64Transform.InputBlockSize)
                    {
                        base64Transform.TransformBlock(
                            inputBytes,
                            offset,
                            base64Transform.InputBlockSize,
                            outputBytes,
                            0);
                        col     = Emit(outStream, outputBytes, col, breakCol);
                        offset += base64Transform.InputBlockSize;
                    }
                    if (bytesRead - offset > 0)
                    {
                        outputBytes = base64Transform.TransformFinalBlock(
                            inputBytes,
                            offset,
                            bytesRead - offset);
                        Emit(outStream, outputBytes, col, breakCol);
                    }
                    bytesRead = inStream.Read(inputBytes, 0, inputBytes.Length);
                }
            }
        }
Beispiel #6
0
        /// <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));
        }
Beispiel #7
0
        public static string Encode(byte[] buffer, int offset, int length)
        {
            byte[] buffer2;
            length += offset;
            ToBase64Transform transform = new ToBase64Transform();
            MemoryStream      stream    = new MemoryStream();
            int inputOffset             = offset;
            int inputCount = 3;

            if (length < 3)
            {
                inputCount = length;
            }
            do
            {
                buffer2      = transform.TransformFinalBlock(buffer, inputOffset, inputCount);
                inputOffset += inputCount;
                if ((length - inputOffset) < inputCount)
                {
                    inputCount = length - inputOffset;
                }
                stream.Write(buffer2, 0, buffer2.Length);
            }while (inputOffset < length);
            buffer2 = stream.ToArray();
            stream.Close();
            UTF8Encoding encoding = new UTF8Encoding();

            return(encoding.GetString(buffer2));
        }
Beispiel #8
0
        public static string Encode(byte[] data)
        {
            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder))
            {
                using (var transformation = new ToBase64Transform())
                {
                    var bufferedOutputBytes = new byte[transformation.OutputBlockSize];
                    int i = 0;
                    int inputBlockSize = transformation.InputBlockSize;

                    while (data.Length - i > inputBlockSize)
                    {
                        transformation.TransformBlock(data, i, data.Length - i, bufferedOutputBytes, 0);
                        i += inputBlockSize;
                        writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes, 0, bufferedOutputBytes.Length));
                    }

                    bufferedOutputBytes = transformation.TransformFinalBlock(data, i, data.Length - i);
                    writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes, 0, bufferedOutputBytes.Length));
                    transformation.Clear();
                }

                writer.Close();
            }

            return(builder.ToString());
        }
        public void TransformFinalBlock_WrongLength()
        {
            byte[]            input = new byte [6];
            ToBase64Transform t     = new ToBase64Transform();

            t.TransformFinalBlock(input, 0, 6);
        }
        public void TransformFinalBlock_SmallLength()
        {
            byte[]            input = new byte [2];  // smaller than InputBlockSize
            ToBase64Transform t     = new ToBase64Transform();

            t.TransformFinalBlock(input, 0, 2);
        }
Beispiel #11
0
        /// <summary>
        /// Converts a byte array to a base64 string one block at a time.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static string ToBase64(byte[] data)
        {
            StringBuilder builder = new StringBuilder();

            using (StringWriter writer = new StringWriter(builder))
            {
                using (ToBase64Transform transformation = new ToBase64Transform())
                {
                    // Transform the data in chunks the size of InputBlockSize.
                    byte[] bufferedOutputBytes = new byte[transformation.OutputBlockSize];
                    int    i = 0;
                    int    inputBlockSize = transformation.InputBlockSize;

                    while (data.Length - i > inputBlockSize)
                    {
                        transformation.TransformBlock(data, i, data.Length - i, bufferedOutputBytes, 0);
                        i += inputBlockSize;
                        writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes));
                    }

                    // Transform the final block of data.
                    bufferedOutputBytes = transformation.TransformFinalBlock(data, i, data.Length - i);
                    writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes));

                    // Free up any used resources.
                    transformation.Clear();
                }

                writer.Close();
            }

            return(builder.ToString());
        }
 public void TransformFinalBlock_InputOffset_Negative()
 {
     byte[] input = new byte [15];
     using (ICryptoTransform t = new ToBase64Transform()) {
         t.TransformFinalBlock(input, -1, input.Length);
     }
 }
 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_InputCount_Overflow()
 {
     byte[] input = new byte [15];
     using (ICryptoTransform t = new ToBase64Transform()) {
         t.TransformFinalBlock(input, 0, Int32.MaxValue);
     }
 }
        public void TransformFinalBlock_Dispose()
        {
            byte[]            input = new byte [3];
            ToBase64Transform t     = new ToBase64Transform();

            t.Clear();
            t.TransformFinalBlock(input, 0, input.Length);
        }
Beispiel #17
0
        public void InvalidInput_ToBase64Transform()
        {
            byte[]           data_3bytes = Text.Encoding.ASCII.GetBytes("aaa");
            ICryptoTransform transform   = new ToBase64Transform();

            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_3bytes, 0, 3, null, 0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("inputCount", () => transform.TransformBlock(Array.Empty <byte>(), 0, 1, null, 0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("inputCount", () => transform.TransformBlock(data_3bytes, 0, 1, new byte[10], 0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("inputCount", () => transform.TransformBlock(new byte[4], 0, 4, new byte[10], 0));
            AssertExtensions.Throws <ArgumentOutOfRangeException>("outputBuffer", () => transform.TransformBlock(data_3bytes, 0, 3, new byte[1], 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));
        }
Beispiel #18
0
        public static void ValidateToBase64TransformFinalBlock(string data, string expected)
        {
            using (var transform = new ToBase64Transform())
            {
                byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data);
                Assert.True(inputBytes.Length > 4);

                // Test passing blocks > 4 characters to TransformFinalBlock (not supported)
                Assert.Throws <ArgumentOutOfRangeException>("offsetOut", () => transform.TransformFinalBlock(inputBytes, 0, inputBytes.Length));
            }
        }
Beispiel #19
0
    public static byte[] Base64Encode(byte[] source)
    {
        if (source == null || source.Length == 0)
        {
            throw new ArgumentException("source is not valid");
        }
        ToBase64Transform toBase64Transform = new ToBase64Transform();
        MemoryStream      memoryStream      = new MemoryStream();
        int i;

        byte[] array;
        for (i = 0; i + 3 < source.Length; i += 3)
        {
            array = toBase64Transform.TransformFinalBlock(source, i, 3);
            memoryStream.Write(array, 0, array.Length);
        }
        array = toBase64Transform.TransformFinalBlock(source, i, source.Length - i);
        memoryStream.Write(array, 0, array.Length);
        return(memoryStream.ToArray());
    }
Beispiel #20
0
        public void InvalidInput_ToBase64Transform()
        {
            byte[] data_5bytes = Text.Encoding.ASCII.GetBytes("aaaaa");

            using (var transform = new ToBase64Transform())
            {
                InvalidInput_Base64Transform(transform);

                // These exceptions only thrown in ToBase
                Assert.Throws <ArgumentOutOfRangeException>("offsetOut", () => transform.TransformFinalBlock(data_5bytes, 0, 5));
            }
        }
        public void InvalidInput_ToBase64Transform()
        {
            byte[] data_5bytes = Text.Encoding.ASCII.GetBytes("aaaaa");

            using (var transform = new ToBase64Transform())
            {
                InvalidInput_Base64Transform(transform);

                // These exceptions only thrown in ToBase
                Assert.Throws<ArgumentOutOfRangeException>("offsetOut", () => transform.TransformFinalBlock(data_5bytes, 0, 5));
            }
        }
Beispiel #22
0
        public static void ValidateToBase64TransformFinalBlock(string data, string expected)
        {
            using (var transform = new ToBase64Transform())
            {
                byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data);
                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);
            }
        }
        /// <summary>
        /// Extends TransformFinalBlock so that buffer offset of 0 and call to Array.Length are not needed.
        /// <example>
        /// tobase64transform.TransformFinalBlock(inputBuffer);
        /// </example>
        /// </summary>
        public static Byte[] TransformFinalBlock(this ToBase64Transform tobase64transform, Byte[] inputBuffer)
        {
            if (tobase64transform == null)
            {
                throw new ArgumentNullException("tobase64transform");
            }

            if (inputBuffer == null)
            {
                throw new ArgumentNullException("inputBuffer");
            }

            return(tobase64transform.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length));
        }
Beispiel #24
0
        public static byte[] EncodeBase64Byte(this byte[] source)
        {
            byte[] buffer2;
            if ((source == null) || (source.Length == 0))
            {
                throw new ArgumentException("source is not valid");
            }
            ToBase64Transform transform = new ToBase64Transform();
            MemoryStream      stream    = new MemoryStream();
            int inputOffset             = 0;

            try
            {
                byte[] buffer;
                while ((inputOffset + 3) < source.Length)
                {
                    buffer = transform.TransformFinalBlock(source, inputOffset, 3);
                    stream.Write(buffer, 0, buffer.Length);
                    inputOffset += 3;
                }
                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);
        }
Beispiel #25
0
        public void ToBase64_TransformFinalBlock_MatchesConvert()
        {
            for (int i = 0; i < 100; i++)
            {
                byte[] input = new byte[i];
                Random.Shared.NextBytes(input);

                string expected = Convert.ToBase64String(input);

                using var transform = new ToBase64Transform();
                string actual = string.Concat(transform.TransformFinalBlock(input, 0, input.Length).Select(b => char.ToString((char)b)));

                Assert.Equal(expected, actual);
            }
        }
Beispiel #26
0
        /// <summary>
        /// Transforms string to byte array
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] Transform(string str)
        {
            // Create a new ToBase64Transform object to convert to base 64.
            ToBase64Transform base64Transform = new ToBase64Transform();

            // Create a new byte array with the size of the output block size.
            byte[] outputBytes = new byte[base64Transform.OutputBlockSize];

            // Retrieve the file contents into a byte array.
            byte[] inputBytes = HexStringToByteArray(str);

            // Verify that multiple blocks can not be transformed.
            if (!base64Transform.CanTransformMultipleBlocks)
            {
                // 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,
                        inputBytes.Length - inputOffset,
                        outputBytes,
                        0);

                    inputOffset += base64Transform.InputBlockSize;
                }

                // Transform the final block of data.
                outputBytes = base64Transform.TransformFinalBlock(
                    inputBytes,
                    inputOffset,
                    inputBytes.Length - inputOffset);

                //Determine if the current transform can be reused.
                if (!base64Transform.CanReuseTransform)
                {
                    // Free up any used resources.
                    base64Transform.Clear();
                }
            }
            return(outputBytes);
        }
Beispiel #27
0
        /// <summary>
        ///     Converts a byte array to a base64 string one block at a time.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static string ToBase64(byte[] data)
        {
#if WINDOWS_PHONE || NETFX_CORE
            return(Convert.ToBase64String(data));
#else
            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder))
            {
                using (var transformation = new ToBase64Transform())
                {
                    // Transform the data in chunks the size of InputBlockSize.

                    var bufferedOutputBytes = new byte[transformation.OutputBlockSize];

                    int i = 0;

                    int inputBlockSize = transformation.InputBlockSize;

                    while (data.Length - i > inputBlockSize)
                    {
                        transformation.TransformBlock(data, i, data.Length - i, bufferedOutputBytes, 0);


                        i += inputBlockSize;


                        writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes, 0, bufferedOutputBytes.Length));
                    }

                    // Transform the final block of data.

                    bufferedOutputBytes = transformation.TransformFinalBlock(data, i, data.Length - i);

                    writer.Write(Encoding.UTF8.GetString(bufferedOutputBytes, 0, bufferedOutputBytes.Length));

                    // Free up any used resources.

                    transformation.Clear();
                }

                writer.Close();
            }
            return(builder.ToString());
#endif
        }
Beispiel #28
0
        // 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);
        }
    // Read in the specified source file and write out an encoded target file.
    private static void EncodeFromFile(string sourceFile, string targetFile)
    {
        // Verify members.cs exists at the specified directory.
        if (!File.Exists(sourceFile))
        {
            Console.Write("Unable to locate source file located at ");
            Console.WriteLine(sourceFile + ".");
            Console.Write("Please correct the path and run the ");
            Console.WriteLine("sample again.");
            return;
        }

        // Retrieve the input and output file streams.
        using (FileStream inputFileStream =
                   new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
        {
            using (FileStream outputFileStream =
                       new FileStream(targetFile, FileMode.Create, FileAccess.Write))
            {
                // Create a new ToBase64Transform object to convert to base 64.
                ToBase64Transform base64Transform = new ToBase64Transform();

                // Create a new byte array with the size of the output block size.
                byte[] outputBytes = new byte[base64Transform.OutputBlockSize];

                // Retrieve the file contents into a byte array.
                byte[] inputBytes = new byte[inputFileStream.Length];
                inputFileStream.Read(inputBytes, 0, inputBytes.Length);

                // Verify that multiple blocks can not be transformed.
                if (!base64Transform.CanTransformMultipleBlocks)
                {
                    // 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,
                            inputBytes.Length - inputOffset,
                            outputBytes,
                            0);

                        inputOffset += base64Transform.InputBlockSize;
                        outputFileStream.Write(
                            outputBytes,
                            0,
                            base64Transform.OutputBlockSize);
                    }

                    // Transform the final block of data.
                    outputBytes = base64Transform.TransformFinalBlock(
                        inputBytes,
                        inputOffset,
                        inputBytes.Length - inputOffset);

                    outputFileStream.Write(outputBytes, 0, outputBytes.Length);
                    Console.WriteLine("Created encoded file at " + targetFile);
                }

                // Determine if the current transform can be reused.
                if (!base64Transform.CanReuseTransform)
                {
                    // Free up any used resources.
                    base64Transform.Clear();
                }
            }
        }
    }
        public static void ValidateToBase64TransformFinalBlock(string data, string expected)
        {
            using (var transform = new ToBase64Transform())
            {
                byte[] inputBytes = Text.Encoding.ASCII.GetBytes(data);
                Assert.True(inputBytes.Length > 4);

                // Test passing blocks > 4 characters to TransformFinalBlock (not supported)
                Assert.Throws<ArgumentOutOfRangeException>("offsetOut", () => transform.TransformFinalBlock(inputBytes, 0, inputBytes.Length));
            }
        }
        /// <summary>
        /// Returns a Base64 encoded string.
        /// </summary>
        /// <returns>String</returns>
        public string ToBase64String()
        {
            if (base64EncodedFile != string.Empty)
            {
                return(base64EncodedFile);
            }

            // This memory stream will hold the InfoPath file attachment buffer before Base64 encoding.
            MemoryStream ms = new MemoryStream();

            // Get the file information.
            using (BinaryReader br = new BinaryReader(File.Open(fullyQualifiedFileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
            {
                string fileName = Path.GetFileName(fullyQualifiedFileName);

                uint fileNameLength = (uint)fileName.Length + 1;

                byte[] fileNameBytes = Encoding.Unicode.GetBytes(fileName);

                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    // Write the InfoPath attachment signature.
                    bw.Write(new byte[] { 0xC7, 0x49, 0x46, 0x41 });

                    // Write the default header information.
                    bw.Write((uint)0x14);       // size
                    bw.Write((uint)0x01);       // version
                    bw.Write((uint)0x00);       // reserved

                    // Write the file size.
                    bw.Write((uint)br.BaseStream.Length);

                    // Write the size of the file name.
                    bw.Write((uint)fileNameLength);

                    // Write the file name (Unicode encoded).
                    bw.Write(fileNameBytes);

                    // Write the file name terminator. This is two nulls in Unicode.
                    bw.Write(new byte[] { 0, 0 });

                    // Iterate through the file reading data and writing it to the outbuffer.
                    byte[] data      = new byte[64 * 1024];
                    int    bytesRead = 1;

                    while (bytesRead > 0)
                    {
                        bytesRead = br.Read(data, 0, data.Length);
                        bw.Write(data, 0, bytesRead);
                    }
                }
            }


            // This memorystream will hold the Base64 encoded InfoPath attachment.
            MemoryStream msOut = new MemoryStream();

            using (BinaryReader br = new BinaryReader(new MemoryStream(ms.ToArray())))
            {
                // Create a Base64 transform to do the encoding.
                ToBase64Transform tf = new ToBase64Transform();

                byte[] data    = new byte[tf.InputBlockSize];
                byte[] outData = new byte[tf.OutputBlockSize];

                int bytesRead = 1;

                while (bytesRead > 0)
                {
                    bytesRead = br.Read(data, 0, data.Length);

                    if (bytesRead == data.Length)
                    {
                        tf.TransformBlock(data, 0, bytesRead, outData, 0);
                    }
                    else
                    {
                        outData = tf.TransformFinalBlock(data, 0, bytesRead);
                    }

                    msOut.Write(outData, 0, outData.Length);
                }
            }

            msOut.Close();

            return(base64EncodedFile = Encoding.ASCII.GetString(msOut.ToArray()));
        }
        //methods
        /// <summary>
        /// Converts file to base64 encoding.
        /// </summary>
        /// <param name="srcFile">File containing data to be encoded.</param>
        /// <param name="targetFile">Output file that will contain the base64 encoded data.</param>
        /// <param name="st">A StatusTimer object to use for timing the encode operation.</param>
        public void EncodeFileToBase64(string srcFile, string targetFile, StatusTimer st)
        {
            byte[]       bytes          = new byte[BufferSize];
            FileStream   fs             = null;
            StreamWriter sw             = null;
            FileStream   fsOut          = null;
            int          bytesRead      = 0;
            long         totalBytesRead = 0;
            bool         errorOccurred  = false;

            // Open srcFile in read-only mode.
            try
            {
                if (st == null)
                {
                    throw new ArgumentNullException("StatusTime must be specified for this routine.");
                }
                st.NumSecondsInterval = _statusReportIntervalSeconds;

                fs = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize);
                long sourceSize = new FileInfo(srcFile).Length;

                if (sourceSize <= BufferSize)
                {
                    // Open stream writer
                    sw        = new StreamWriter(targetFile, false, Encoding.ASCII);
                    bytesRead = fs.Read(bytes, 0, BufferSize);

                    if (bytesRead > 0)
                    {
                        if (currentStatusReport != null)
                        {
                            if (st.StatusReportDue())
                            {
                                currentStatusReport("EncodeToBase64", "In Progress", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                            }
                        }
                        string base64String = Convert.ToBase64String(bytes, 0, bytesRead);
                        totalBytesRead += bytesRead;
                        sw.Write(base64String);
                        if (currentStatusReport != null)
                        {
                            if (st.StatusReportDue())
                            {
                                currentStatusReport("EncodeToBase64", "Completed", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                            }
                        }
                    }
                }
                else
                {
                    // Instantiate a ToBase64Transform object.
                    ToBase64Transform transf = new ToBase64Transform();
                    // Arrays to hold input and output bytes.
                    byte[] inputBytes  = new byte[transf.InputBlockSize];
                    byte[] outputBytes = new byte[transf.OutputBlockSize];
                    int    bytesWritten;

                    fsOut = new FileStream(targetFile, FileMode.Create, FileAccess.Write);

                    do
                    {
                        if (currentStatusReport != null)
                        {
                            if (st.StatusReportDue())
                            {
                                currentStatusReport("EncodeToBase64", "In Progress", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                            }
                        }
                        bytesRead       = fs.Read(inputBytes, 0, inputBytes.Length);
                        totalBytesRead += bytesRead;
                        bytesWritten    = transf.TransformBlock(inputBytes, 0, bytesRead, outputBytes, 0);
                        fsOut.Write(outputBytes, 0, bytesWritten);
                    } while (sourceSize - totalBytesRead > transf.InputBlockSize);

                    // Transform the final block of data.
                    bytesRead       = fs.Read(inputBytes, 0, inputBytes.Length);
                    totalBytesRead += bytesRead;
                    byte[] finalOutputBytes = transf.TransformFinalBlock(inputBytes, 0, bytesRead);
                    fsOut.Write(finalOutputBytes, 0, finalOutputBytes.Length);

                    if (currentStatusReport != null)
                    {
                        currentStatusReport("EncodeToBase64", "Completed", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                    }

                    // Clear Base64Transform object.
                    transf.Clear();
                }
            }
            catch (IOException ex)
            {
                errorOccurred = true;
                _msg.Length   = 0;
                _msg.Append(AppMessages.FormatErrorMessage(ex));
                throw new IOException(_msg.ToString());
            }
            catch (SecurityException ex)
            {
                errorOccurred = true;
                _msg.Length   = 0;
                _msg.Append(AppMessages.FormatErrorMessage(ex));
                throw new SecurityException(_msg.ToString());
            }
            catch (UnauthorizedAccessException ex)
            {
                errorOccurred = true;
                _msg.Length   = 0;
                _msg.Append(AppMessages.FormatErrorMessage(ex));
                throw new UnauthorizedAccessException(_msg.ToString());
            }
            finally
            {
                if (errorOccurred)
                {
                    if (currentStatusReport != null)
                    {
                        currentStatusReport("EncodeToBase64", "ErrorCancel", totalBytesRead, (int)st.GetElapsedTime().TotalSeconds, st.GetFormattedElapsedTime());
                    }
                }

                if (sw != null)
                {
                    sw.Close();
                }
                if (fs != null)
                {
                    fs.Dispose();
                    fs.Close();
                }
                if (fsOut != null)
                {
                    fsOut.Dispose();
                    fsOut.Close();
                }
            }
        }