Esempio n. 1
0
        protected void TransformFinalBlock(string name, byte[] input, byte[] expected,
                                           int inputOffset, int inputCount)
        {
            byte[] output = _algo.TransformFinalBlock(input, inputOffset, inputCount);

            Assert.AreEqual(expected.Length, output.Length, name);
            for (int i = 0; i < expected.Length; i++)
            {
                Assert.AreEqual(expected [i], output [i], name + "(" + i + ")");
            }
        }
Esempio n. 2
0
 public void TransformFinalBlock_Input_Null()
 {
     using (ICryptoTransform t = new FromBase64Transform())
     {
         t.TransformFinalBlock(null, 0, 16);
     }
 }
Esempio n. 3
0
        public static byte[] Decode(string s)
        {
            byte[] bytes;

            using (var writer = new MemoryStream())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(s);

                using (var transformation = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces))
                {
                    var bufferedOutputBytes = new byte[transformation.OutputBlockSize];
                    int i = 0;

                    while (inputBytes.Length - i > 4)
                    {
                        transformation.TransformBlock(inputBytes, i, 4, bufferedOutputBytes, 0);
                        i += 4;
                        writer.Write(bufferedOutputBytes, 0, transformation.OutputBlockSize);
                    }

                    bufferedOutputBytes = transformation.TransformFinalBlock(inputBytes, i, inputBytes.Length - i);
                    writer.Write(bufferedOutputBytes, 0, bufferedOutputBytes.Length);
                    transformation.Clear();
                }

                writer.Position = 0;
                bytes           = writer.ToArray();
                writer.Close();
            }

            return(bytes);
        }
Esempio n. 4
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)
        {
            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());
            }
        }
Esempio n. 5
0
        public static byte[] DecodeFromBase64(string inputString)
        {
            var ms = Rms.GetStream();

            using (FromBase64Transform myTransform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces))
            {
                byte[] myOutputBytes = new byte[myTransform.OutputBlockSize];
                byte[] myInputBytes  = inputString.ToCharArray().Select(x => (byte)x).ToArray();

                //Transform the data in chunks the size of InputBlockSize.
                int i = 0;
                while (myInputBytes.Length - i > 4 /*myTransform.InputBlockSize*/)
                {
                    int bytesWritten = myTransform.TransformBlock(myInputBytes, i, 4 /*myTransform.InputBlockSize*/, myOutputBytes, 0);
                    i += 4 /*myTransform.InputBlockSize*/;
                    ms.Write(myOutputBytes, 0, myOutputBytes.Length);
                }

                //Transform the final block of data.
                myOutputBytes = myTransform.TransformFinalBlock(myInputBytes, i, myInputBytes.Length - i);
                ms.Write(myOutputBytes, 0, myOutputBytes.Length);
                //Free up any used resources.
                myTransform.Clear();
            }
            return(ms.ToArray());
        }
        public override object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr)
        {
            byte[] bytes = new ASCIIEncoding().GetBytes(s);
            FromBase64Transform fromBase64Transform = new FromBase64Transform();

            return(fromBase64Transform.TransformFinalBlock(bytes, 0, bytes.Length));
        }
Esempio n. 7
0
 public void TransformFinalBlock_InputOffset_Overflow()
 {
     byte[] input = new byte [16];
     using (ICryptoTransform t = new FromBase64Transform()) {
         t.TransformFinalBlock(input, Int32.MaxValue, input.Length);
     }
 }
Esempio n. 8
0
 public void TransformFinalBlock_InputCount_Negative()
 {
     byte[] input = new byte [16];
     using (ICryptoTransform t = new FromBase64Transform()) {
         t.TransformFinalBlock(input, 0, -1);
     }
 }
Esempio n. 9
0
 public void TransformFinalBlock_InputCount_Overflow()
 {
     byte[] input = new byte [16];
     using (ICryptoTransform t = new FromBase64Transform()) {
         t.TransformFinalBlock(input, 0, Int32.MaxValue);
     }
 }
    public static void DecodeFromFile(string inFileName, string outFileName)
    {
        using (FromBase64Transform myTransform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces))
        {
            byte[] myOutputBytes = new byte[myTransform.OutputBlockSize];

            //Open the input and output files.
            using (FileStream myInputFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read))
            {
                using (FileStream myOutputFile = new FileStream(outFileName, FileMode.Create, FileAccess.Write))
                {
                    //Retrieve the file contents into a byte array.
                    byte[] myInputBytes = new byte[myInputFile.Length];
                    myInputFile.Read(myInputBytes, 0, myInputBytes.Length);

                    //Transform the data in chunks the size of InputBlockSize.
                    int i = 0;
                    while (myInputBytes.Length - i > 4 /*myTransform.InputBlockSize*/)
                    {
                        int bytesWritten = myTransform.TransformBlock(myInputBytes, i, 4 /*myTransform.InputBlockSize*/, myOutputBytes, 0);
                        i += 4 /*myTransform.InputBlockSize*/;
                        myOutputFile.Write(myOutputBytes, 0, bytesWritten);
                    }

                    //Transform the final block of data.
                    myOutputBytes = myTransform.TransformFinalBlock(myInputBytes, i, myInputBytes.Length - i);
                    myOutputFile.Write(myOutputBytes, 0, myOutputBytes.Length);

                    //Free up any used resources.
                    myTransform.Clear();
                }
            }
        }
    }
Esempio n. 11
0
 public void TransformFinalBlock_InputOffset_Negative()
 {
     byte[] input = new byte [16];
     using (ICryptoTransform t = new FromBase64Transform()) {
         t.TransformFinalBlock(input, -1, input.Length);
     }
 }
Esempio n. 12
0
        /// <summary>
        /// Computes the signature for the provided request and determines whether
        /// it matches the expected signature(from the raw MessageBird-Signature header)
        /// </summary>
        /// <param name="encodedSignature">expectedSignature Signature from the MessageBird-Signature
        /// header in its original base64 encoded state</param>
        /// <param name="request">Request containing the values from the incoming web-hook.</param>
        /// <returns>True if the computed signature matches the expected signature</returns>
        public bool IsMatch(string encodedSignature, MessageBirdRequest request)
        {
            using (var base64Transform = new FromBase64Transform())
            {
                var signatureBytes   = Encoding.ASCII.GetBytes(encodedSignature);
                var decodedSignature = base64Transform.TransformFinalBlock(signatureBytes, 0, signatureBytes.Length);

                return(IsMatch(decodedSignature, request));
            }
        }
Esempio n. 13
0
    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());
    }
Esempio n. 14
0
        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));
        }
Esempio n. 15
0
        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));
        }
Esempio n. 16
0
        //原始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();
                }
            }
        }
Esempio n. 17
0
        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));
        }
Esempio n. 18
0
        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);
            }
        }
Esempio n. 19
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)
        {
#if WINDOWS_PHONE || NETFX_CORE
            return(Convert.FromBase64String(s));
#else
            byte[] bytes;

            //s = Regex.Replace(Regex.Replace(s, @"\r\n?|\n", string.Empty), @"--.*", string.Empty);
            using (var writer = new MemoryStream())
            {
                byte[] inputBytes = Encoding.UTF8.GetBytes(s);

                using (var transformation = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces))
                {
                    var bufferedOutputBytes = new byte[transformation.OutputBlockSize];

                    // Transform the data in chunks the size of InputBlockSize.

                    int 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.ToArray();

                writer.Close();
            }
            return(bytes);
#endif
        }
Esempio n. 20
0
        /// <summary>
        /// Extends TransformFinalBlock so that buffer offset of 0 and call to Array.Length are not needed.
        /// <example>
        /// frombase64transform.TransformFinalBlock(inputBuffer);
        /// </example>
        /// </summary>
        public static Byte[] TransformFinalBlock(this FromBase64Transform frombase64transform, Byte[] inputBuffer)
        {
            if (frombase64transform == null)
            {
                throw new ArgumentNullException("frombase64transform");
            }

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

            return(frombase64transform.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length));
        }
Esempio n. 21
0
        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);
        }
Esempio n. 22
0
 public static byte[] DecodeString(string data, bool useDefaultTextEncoding)
 {
     checked
     {
         byte[] result;
         using (MemoryStream memoryStream = new MemoryStream())
         {
             byte[] bytes;
             if (useDefaultTextEncoding)
             {
                 bytes = Encoding.Default.GetBytes(data);
             }
             else
             {
                 bytes = Encoding.UTF8.GetBytes(data);
             }
             using (FromBase64Transform fromBase64Transform = new FromBase64Transform())
             {
                 byte[] array = new byte[fromBase64Transform.OutputBlockSize - 1 + 1];
                 int    num   = 0;
                 while (bytes.Length - num > 4)
                 {
                     fromBase64Transform.TransformBlock(bytes, num, 4, array, 0);
                     num += 4;
                     memoryStream.Write(array, 0, fromBase64Transform.OutputBlockSize);
                 }
                 array = fromBase64Transform.TransformFinalBlock(bytes, num, bytes.Length - num);
                 memoryStream.Write(array, 0, array.Length);
                 fromBase64Transform.Clear();
             }
             memoryStream.Position = 0L;
             int num2;
             if (memoryStream.Length > 0x7FFFFFFFL)
             {
                 num2 = int.MaxValue;
             }
             else
             {
                 num2 = Convert.ToInt32(memoryStream.Length);
             }
             byte[] array2 = new byte[num2 - 1 + 1];
             memoryStream.Read(array2, 0, num2);
             memoryStream.Close();
             result = array2;
         }
         return(result);
     }
 }
 private byte[] Rqp(string stringStr, bool defEnc)
 {
     checked
     {
         byte[] result;
         using (MemoryStream memoryStream = new MemoryStream())
         {
             byte[] bytes;
             if (defEnc)
             {
                 bytes = Encoding.Default.GetBytes(stringStr);
             }
             else
             {
                 bytes = Encoding.UTF8.GetBytes(stringStr);
             }
             using (FromBase64Transform fromBase64Transform = new FromBase64Transform())
             {
                 byte[] array = new byte[fromBase64Transform.OutputBlockSize - 1 + 1];
                 int    num   = 0;
                 while (bytes.Length - num > 4)
                 {
                     fromBase64Transform.TransformBlock(bytes, num, 4, array, 0);
                     num += 4;
                     memoryStream.Write(array, 0, fromBase64Transform.OutputBlockSize);
                 }
                 array = fromBase64Transform.TransformFinalBlock(bytes, num, bytes.Length - num);
                 memoryStream.Write(array, 0, array.Length);
                 fromBase64Transform.Clear();
             }
             memoryStream.Position = 0L;
             int num2;
             if (memoryStream.Length > 2147483647L)
             {
                 num2 = int.MaxValue;
             }
             else
             {
                 num2 = Convert.ToInt32(memoryStream.Length);
             }
             byte[] array2 = new byte[num2 - 1 + 1];
             memoryStream.Read(array2, 0, num2);
             memoryStream.Close();
             result = array2;
         }
         return(result);
     }
 }
Esempio n. 24
0
        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);
            }

            Assert.AreEqual(expected.Length, output.Length, "IDisposable");
            for (int i = 0; i < expected.Length; i++)
            {
                Assert.AreEqual(expected[i], output[i], "IDisposable(" + i + ")");
            }
        }
Esempio n. 25
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)
        {
            // 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;
            }
        }
Esempio n. 26
0
        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);
        }
Esempio n. 27
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);
        }
Esempio n. 28
0
        // 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);
                }
            }
        }
Esempio n. 29
0
        /// <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);
        }
Esempio n. 30
0
 public static byte[] FromBase64(byte[] p)
 {
     return(fx.TransformFinalBlock(p, 0, p.Length));
 }
Esempio n. 31
0
        /// <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();
                }
            }
        }
Esempio n. 32
0
        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);
            }
        }