Beispiel #1
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());
        }
Beispiel #2
0
        public static void RoundtripCryptoStream(int length)
        {
            byte[] expected = RandomNumberGenerator.GetBytes(length);
            var    ms       = new MemoryStream();

            using (var toBase64 = new ToBase64Transform())
                using (var stream = new CryptoStream(ms, toBase64, CryptoStreamMode.Write, leaveOpen: true))
                {
                    stream.Write(expected);
                }

            ms.Position = 0;

            byte[] actual = new byte[expected.Length];
            using (var fromBase64 = new FromBase64Transform())
                using (var stream = new CryptoStream(ms, fromBase64, CryptoStreamMode.Read, leaveOpen: true))
                {
                    int totalRead = 0, bytesRead;
                    while ((bytesRead = stream.Read(actual.AsSpan(totalRead))) != 0)
                    {
                        totalRead += bytesRead;
                    }
                    Assert.Equal(actual.Length, totalRead);
                    AssertExtensions.SequenceEqual(expected, actual);
                }
        }
Beispiel #3
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));
        }
 public void TransformFinalBlock_Input_Null()
 {
     using (ICryptoTransform t = new ToBase64Transform())
     {
         t.TransformFinalBlock(null, 0, 15);
     }
 }
        public async Task CanEncryptAndDecryptMergedStream(MergedStream mergedStream, string expectedData)
        {
            using (var aes = Aes.Create())
            {
                aes.Mode    = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.GenerateKey();
                aes.GenerateIV();

                using (var encryptor = aes.CreateEncryptor())
                    using (var encryptedStream = new CryptoStream(mergedStream, encryptor, CryptoStreamMode.Read))
                        using (var toBase64Transform = new ToBase64Transform())
                            using (var encodedStream = new CryptoStream(encryptedStream, toBase64Transform, CryptoStreamMode.Read))
                                using (var fromBase64Transform = new FromBase64Transform())
                                    using (var decodedStream = new CryptoStream(encodedStream, fromBase64Transform, CryptoStreamMode.Read))
                                        using (var decryptor = aes.CreateDecryptor())
                                            using (var decryptedStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read))
                                                using (var streamReader = new StreamReader(decryptedStream))
                                                {
                                                    var data = await streamReader.ReadToEndAsync();

                                                    Assert.Equal(expectedData, data);
                                                }
            }
        }
Beispiel #6
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);
     }
 }
Beispiel #8
0
            /// <summary>
            /// 加密 对用户名和密码进行加密的方法
            /// </summary>
            /// <param name="text"></param>
            /// <returns></returns>
            private string Encrypt(string text)
            {
                Rijndael crypt = Rijndael.Create();

                byte[] key = new byte[32] {
                    0XA6, 0X7D, 0XE1, 0X3F, 0X35, 0X0E, 0XE1, 0XA9, 0X83, 0XA5, 0X62, 0XAA, 0X7A, 0XAE, 0X79, 0X98, 0XA7, 0X33, 0X49, 0XFF, 0XE6, 0XAE, 0XBF, 0X8D, 0X8D, 0X20, 0X8A, 0X49, 0X31, 0X3A, 0X12, 0X40
                };

                byte[] iv = new byte[16] {
                    0XF8, 0X8B, 0X01, 0XFB, 0X08, 0X85, 0X9A, 0XA4, 0XBE, 0X45, 0X28, 0X56, 0X03, 0X42, 0XF6, 0X19
                };
                crypt.Key = key;
                crypt.IV  = iv;

                MemoryStream ms = new MemoryStream();

                ICryptoTransform transtormEncode = new ToBase64Transform();
                //Base64编码
                CryptoStream csEncode = new CryptoStream(ms, transtormEncode, CryptoStreamMode.Write);

                CryptoStream csEncrypt = new CryptoStream(csEncode, crypt.CreateEncryptor(), CryptoStreamMode.Write);

                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                byte[] rawData = enc.GetBytes(text);

                csEncrypt.Write(rawData, 0, rawData.Length);
                csEncrypt.FlushFinalBlock();

                byte[] encryptedData = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(encryptedData, 0, (int)ms.Length);

                return(enc.GetString(encryptedData));
            }
        public void TransformBlock_NullInput()
        {
            byte[]            output = new byte [4];
            ToBase64Transform t      = new ToBase64Transform();

            t.TransformBlock(null, 0, 0, output, 0);
        }
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string AESEncrypt(string text)
        {
            Rijndael rijndael = Rijndael.Create();

            byte[] buffer = new byte[] {
                0xa6, 0x7d, 0xe1, 0x3f, 0x35, 14, 0xe1, 0xa9, 0x83, 0xa5, 0x62, 170, 0x7a, 0xae, 0x79, 0x98,
                0xa7, 0x33, 0x49, 0xff, 230, 0xae, 0xbf, 0x8d, 0x8d, 0x20, 0x8a, 0x49, 0x31, 0x3a, 0x12, 0x40
            };
            byte[] buffer2 = new byte[] { 0xf8, 0x8b, 1, 0xfb, 8, 0x85, 0x9a, 0xa4, 190, 0x45, 40, 0x56, 3, 0x42, 0xf6, 0x19 };
            rijndael.Key = buffer;
            rijndael.IV  = buffer2;
            MemoryStream     stream    = new MemoryStream();
            ICryptoTransform transform = new ToBase64Transform();
            CryptoStream     stream2   = new CryptoStream(stream, transform, CryptoStreamMode.Write);
            CryptoStream     stream3   = new CryptoStream(stream2, rijndael.CreateEncryptor(), CryptoStreamMode.Write);
            UTF8Encoding     encoding  = new UTF8Encoding();

            byte[] bytes = encoding.GetBytes(text);
            stream3.Write(bytes, 0, bytes.Length);
            stream3.FlushFinalBlock();
            byte[] buffer4 = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(buffer4, 0, (int)stream.Length);
            return(encoding.GetString(buffer4));
        }
        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);
        }
 public void TransformFinalBlock_InputCount_Negative()
 {
     byte[] input = new byte [15];
     using (ICryptoTransform t = new ToBase64Transform()) {
         t.TransformFinalBlock(input, 0, -1);
     }
 }
Beispiel #14
0
        public static void EnormousWrite()
        {
            // 0x6000_0000 / 3 => 0x2000_0000 * 4 => 0x8000_0000 (overflow)
            // (input bytes) / (input block size) * (output block size) => (output bytes to write)
            const int InputBufferLength = 0x60000000;

            byte[] buffer;

            try
            {
                buffer = new byte[InputBufferLength];
            }
            catch (OutOfMemoryException)
            {
                throw new SkipTestException("Could not create a large enough array");
            }

            // In the Read scenario the overflow comes from a reducing transform.
            // In the Write scenario it comes from an expanding transform.
            //
            // When making the write not overflow change the test to use an output stream
            // that isn't bounded by Array.MaxLength.  e.g. a counting stream, or a stream
            // that just computes some hash of the input (so total correctness can be measured)
            byte[] output = Array.Empty <byte>();

            using (MemoryStream stream = new MemoryStream(output))
                using (ICryptoTransform transform = new ToBase64Transform())
                    using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write, leaveOpen: true))
                    {
                        Assert.Throws <OverflowException>(() => cryptoStream.Write(buffer, 0, buffer.Length));
                    }
        }
        public void TransformBlock_NullOutput()
        {
            byte[]            input = new byte [3];
            ToBase64Transform t     = new ToBase64Transform();

            t.TransformBlock(input, 0, 3, null, 0);
        }
Beispiel #16
0
 public static void ValidateToBase64CryptoStream(string data, string encoding)
 {
     using (var transform = new ToBase64Transform())
     {
         ValidateCryptoStream(encoding, data, transform);
     }
 }
Beispiel #17
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));
        }
        public void TransformFinalBlock_Null()
        {
            byte[]            input = new byte [3];
            ToBase64Transform t     = new ToBase64Transform();

            t.TransformFinalBlock(null, 0, 3);
        }
Beispiel #19
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 #20
0
        /// <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();
        }
Beispiel #21
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_InputCount_Overflow()
 {
     byte[] input = new byte [15];
     using (ICryptoTransform t = new ToBase64Transform()) {
         t.TransformFinalBlock(input, 0, Int32.MaxValue);
     }
 }
 public void TransformFinalBlock_InputOffset_Overflow()
 {
     byte[] input = new byte [15];
     using (ICryptoTransform t = new ToBase64Transform()) {
         t.TransformFinalBlock(input, Int32.MaxValue, input.Length);
     }
 }
Beispiel #24
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());
        }
 public void TransformUsageFlags_ToBase64Transform()
 {
     using (var transform = new ToBase64Transform())
     {
         Assert.False(transform.CanTransformMultipleBlocks);
         Assert.True(transform.CanReuseTransform);
     }
 }
 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 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);
     }
 }
        public void TransformFinalBlock_Dispose()
        {
            byte[]            input = new byte [3];
            ToBase64Transform t     = new ToBase64Transform();

            t.Clear();
            t.TransformFinalBlock(input, 0, input.Length);
        }
 public void Blocksizes_ToBase64Transform()
 {
     using (var transform = new ToBase64Transform())
     {
         Assert.Equal(3, transform.InputBlockSize);
         Assert.Equal(4, transform.OutputBlockSize);
     }
 }
    public static string Encrypt_HMACSHA1(string key, byte[] data)
    {
        HMACSHA1          hmascha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key));
        ToBase64Transform tbt      = new ToBase64Transform();

        byte[] encrypteddata = hmascha1.ComputeHash(data);
        return(Convert.ToBase64String(encrypteddata));
    }
Beispiel #31
0
 static void Main( )
 {
     Stream stm = new FileStream ( "foo.txt" , FileMode.Open , FileAccess.Read ) ;
     ICryptoTransform ict = new ToBase64Transform ( ) ;
     CryptoStream cs = new CryptoStream ( stm , ict, CryptoStreamMode.Read ) ;
     TextReader tr = new StreamReader ( cs ) ;
     string s = tr.ReadToEnd ( ) ;
     Console.WriteLine ( s ) ;
 }
        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 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));
            }
        }
 public static void ValidateToBase64CryptoStream(string data, string encoding)
 {
     using (var transform = new ToBase64Transform())
     {
         ValidateCryptoStream(encoding, data, transform);
     }
 }