예제 #1
0
	public static bool TestAlgorithms(SymmetricAlgorithm encAlgorithm, SymmetricAlgorithm decAlgorithm, int maxLength, int iterations)
	{
		Random rand = new Random();
		
		for (int i = 0; i < iterations; i++)
		{
			// Create random data, key, IV, mode
			//
			byte[] key = new byte[KeySizeBytes[rand.Next(KeySizeBytes.Length)]];
			rand.NextBytes(key);
			
			byte[] data = new byte[rand.Next(1, maxLength + 1)];
			rand.NextBytes(data);

			byte[] IV = new byte[BlockSizeBytes];
			rand.NextBytes(IV);
			
			// Encrypt the data
			//
			byte[] encryptedData;
			encAlgorithm.Key = key;
			encAlgorithm.IV = IV;

			ICryptoTransform transform = encAlgorithm.CreateEncryptor();
			encryptedData = transform.TransformFinalBlock(data, 0, data.Length);

			// Decrypt the data
			//
			byte[] decryptedData;
			decAlgorithm.Key = key;
			decAlgorithm.IV = IV;

			transform = decAlgorithm.CreateDecryptor();
			decryptedData = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

			if (!CompareBytes(data, decryptedData))
			{
				Console.WriteLine("ERROR - roundtrip encrypt/decrypt failed!\n");
				Console.WriteLine("Encryption algorithm: {0}", encAlgorithm.ToString());
				Console.WriteLine("Decryption algorithm: {0}", decAlgorithm.ToString());
				Console.WriteLine("Original data: {0}", ByteArrayToString(data));
				Console.WriteLine("Roundtrip data: {0}", ByteArrayToString(decryptedData));
				Console.WriteLine("Key: {0}", ByteArrayToString(key));
				Console.WriteLine("IV: {0}", ByteArrayToString(IV));
				return false;
			}
		}

		return true;
	}
예제 #2
0
        public string EncryptString(string plainText, string password)
        {
            // first we convert the plain text into a byte array
            byte[] plainTextBytes = Encoding.Unicode.GetBytes(plainText);

            // use a memory stream to hold the bytes
            MemoryStream myStream = new MemoryStream();

            // create the key and initialization vector using the password
            SymmetricAlgorithm sa = InitCipher();

            InitCipherObject(sa, password);

            // create the encoder that will write to the memory stream
            CryptoStream cryptStream = new CryptoStream(myStream, sa.CreateEncryptor(), CryptoStreamMode.Write);

            // we now use the crypto stream to write our byte array to the memory stream
            cryptStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptStream.FlushFinalBlock();

            // change the encrypted stream to a printable version of our encrypted string
            return(Convert.ToBase64String(myStream.ToArray()));
        }
예제 #3
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="inputdata">输入的数据</param>
        /// <param name="iv">向量128位(Iv的字符串长度为16)</param>
        /// <param name="key">加密密钥(key的长度为32)</param>
        /// <returns></returns>
        public static byte[] AESEncrypt(string encryptString, string key, string iv)
        {
            //分组加密算法
            SymmetricAlgorithm Aes = Rijndael.Create();

            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);//得到需要加密的字节数组
            //设置密钥及密钥向量
            Aes.Key = Encoding.UTF8.GetBytes(key);
            Aes.IV  = Encoding.UTF8.GetBytes(iv);;
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, Aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组
                    cs.Close();
                    ms.Close();
                    return(cipherBytes);
                    //return Convert.ToBase64String(cipherBytes); //返回字符串
                }
            }
        }
        public static async Task <string> Encrypt(string plainText, byte[] key, byte[] iv)
        {
            using (SymmetricAlgorithm aes = Rijndael.Create())
            {
                aes.Key = key;
                aes.IV  = iv;

                using (ICryptoTransform crypto = aes.CreateEncryptor())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(ms, crypto, CryptoStreamMode.Write))
                        {
                            var bytes = Encoding.UTF8.GetBytes(plainText);
                            cryptoStream.Write(bytes, 0, bytes.Length);
                            await cryptoStream.FlushAsync();
                        }
                        var encryptedBytes = ms.ToArray();
                        return(Convert.ToBase64String(encryptedBytes));
                    }
                }
            }
        }
예제 #5
0
    static void encrypt()
    {
        string ans  = "green";
        string key  = "1E14FC86752772F5DB58B99764D0168106D336563D77CCBA";
        string salt = "xXsrnq4n1jebmRiC/Ty46g==";

        byte[] key_bytes  = GetBytes(key, key.Length);
        byte[] ans_bytes  = Encoding.Unicode.GetBytes(ans);
        byte[] salt_bytes = Convert.FromBase64String(salt);

        byte[] buf = new byte[ans_bytes.Length + salt_bytes.Length];

        /*Array.Copy (salt_bytes, 0, buf, 0, salt_bytes.Length);*/
        Array.Copy(ans_bytes, 0, buf, salt_bytes.Length, ans_bytes.Length);

        Console.WriteLine("before encryption {0}", Convert.ToBase64String(buf));

        SymmetricAlgorithm alg = Rijndael.Create();

        ICryptoTransform encryptor = alg.CreateEncryptor(key_bytes, salt_bytes);

        Console.WriteLine(Convert.ToBase64String(encryptor.TransformFinalBlock(buf, 0, buf.Length)));
    }
예제 #6
0
        private static byte[] Encrypt(SymmetricAlgorithm symmetricAlgorithm, byte[] bytes)
        {
            if (bytes == null || bytes.Length == 0)
            {
                Debug.LogError("The byte is null or zero length!");
                return(bytes);
            }

            if (symmetricAlgorithm == null)
            {
                throw new NullReferenceException();
            }

            using (var stream = new MemoryStream())
                using (var encryptor = symmetricAlgorithm.CreateEncryptor())
                    using (var encrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
                    {
                        encrypt.Write(bytes, 0, bytes.Length);
                        encrypt.FlushFinalBlock();

                        return(stream.ToArray());
                    }
        }
예제 #7
0
        // Return result in base64-encoded form
        public static string EncryptBySymmetricAlgorithm(string plainText, SymmetricAlgorithm aesAlgorithm)
        {
            byte[] encrypted;
            // Create an encryptor to perform the stream transform.
            var encryptor = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV);

            // Create the streams used for encryption.
            using (var msEncrypt = new MemoryStream())
            {
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (var swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }

                    encrypted = msEncrypt.ToArray();
                }
            }
            // Return encoded data.
            return(Convert.ToBase64String(encrypted));
        }
예제 #8
0
    //构造,初始化加密与解密容器,获取向量与密钥,
    //无参构造,默认使用TripleDES算法,其提供的key位数更多,加密可靠性更高。
    public void DesInit(string algorithmName = "DES") //TripleDES
    {
        SymmetricAlgorithm provider = SymmetricAlgorithm.Create(algorithmName);

        //provider.IV = Convert.FromBase64String(IV);
        switch (algorithmName)
        {
        case "DES":
            provider.Key = Encoding.UTF8.GetBytes(DesKey);
            break;

        case "TripleDES":
            provider.Key = Encoding.UTF8.GetBytes(TripleDesKey);
            break;

        default:
            throw new Exception("选择不正确,DES||TripleDES");
        }
        //密钥和初始向量
        provider.IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        encryptor   = provider.CreateEncryptor();
        decryptor   = provider.CreateDecryptor();
    }
예제 #9
0
        public static string Encrypt(this string clearMessage, string key, string vector)
        {
            byte[] message = Encoding.Default.GetBytes(clearMessage);
            string cipher  = string.Empty;

            SymmetricAlgorithm des3 = SymmetricAlgorithm.Create("3DES");

            des3.Key = Encoding.Default.GetBytes(key);
            des3.IV  = Encoding.Default.GetBytes(vector);

            using (MemoryStream mstream = new MemoryStream())
            {
                using (CryptoStream cstream = new CryptoStream(mstream, des3.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cstream.Write(message, 0, message.Length);
                }

                byte[] cryptostream = mstream.ToArray();
                cipher = Convert.ToBase64String(cryptostream);
            }

            return(cipher);
        }
        public override bool Encrypt(NetOutgoingMessage msg)
        {
            int unEncLenBits = msg.LengthBits;

            var ms = new MemoryStream();
            var cs = new CryptoStream(ms, m_algorithm.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(msg.m_data, 0, msg.LengthBytes);
            cs.Close();

            // get results
            var arr = ms.ToArray();

            ms.Close();

            msg.EnsureBufferSize((arr.Length + 4) * 8);
            msg.LengthBits = 0;             // reset write pointer
            msg.Write((uint)unEncLenBits);
            msg.WriteRaw(arr);
            msg.LengthBits = (arr.Length + 4) * 8;

            return(true);
        }
예제 #11
0
        /// <summary>
        /// AES加密算法
        /// </summary>
        /// <param name="plainText">明文字符串</param>
        /// <param name="strKey">密钥</param>
        /// <returns>返回加密后的密文字节数组</returns>
        public string AESEncrypt(string plainText, string strKey)
        {
            //分组加密算法
            SymmetricAlgorithm des = Rijndael.Create();

            byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组
            des.Mode    = CipherMode.ECB;
            des.Padding = PaddingMode.PKCS7;
            //设置密钥及密钥向量
            des.Key = Encoding.UTF8.GetBytes(strKey);
            des.IV  = _key1;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组
            cs.Close();
            ms.Close();
            //BitConverter.ToString(cipherBytes).Replace("-", "").ToLower()

            return(BitConverter.ToString(cipherBytes).Replace("-", "").ToLower());
        }
예제 #12
0
        public string encryptData(string rawData)
        {
            SymmetricAlgorithm sym = SymmetricAlgorithm.Create("rijndael");

            sym.Key = readKey();
            sym.Key = readKey();
            byte[]       clearData = Encoding.UTF8.GetBytes(rawData);
            MemoryStream mem       = new MemoryStream();

            sym.GenerateIV();
            mem.Write(sym.IV, 0, sym.IV.Length);


            CryptoStream cs = new CryptoStream(mem, sym.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(clearData, 0, clearData.Length);
            cs.FlushFinalBlock();
            cs.Close();
            string creptedata = Convert.ToBase64String(mem.ToArray());

            mem.Close();
            return(creptedata);
        }
예제 #13
0
        private static byte[] Encrypt(byte[] key, string value)
        {
            SymmetricAlgorithm Sa = Rijndael.Create();
            ICryptoTransform   Ct = Sa.CreateEncryptor((new PasswordDeriveBytes(value, null)).GetBytes(16), new byte[16]);

            MemoryStream Ms = new MemoryStream();
            CryptoStream Cs = new CryptoStream(Ms, Ct, CryptoStreamMode.Write);

            Cs.Write(key, 0, key.Length);
            Cs.FlushFinalBlock();

            byte[] Result = Ms.ToArray();

            Ms.Close();
            Ms.Dispose();

            Cs.Close();
            Cs.Dispose();

            Ct.Dispose();

            return(Result);
        }
예제 #14
0
        public static string encrypt(string encryptionString, string Key, string IV)
        {
            byte[] clearTextBytes = Encoding.UTF8.GetBytes(encryptionString);

            SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

            rijn.Mode      = CipherMode.ECB;
            rijn.Padding   = PaddingMode.Zeros;
            rijn.BlockSize = 256;

            MemoryStream ms = new MemoryStream();

            byte[] rgbIV = Encoding.ASCII.GetBytes(IV);

            byte[]       key = Encoding.ASCII.GetBytes(Key);
            CryptoStream cs  = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);

            cs.Write(clearTextBytes, 0, clearTextBytes.Length);

            cs.Close();

            return(Convert.ToBase64String(ms.ToArray()));
        }
예제 #15
0
        public byte[] EncodeData(byte[] text, byte[] sharedKey)
        {
            using (SymmetricAlgorithm algorithm = SymmetricAlgorithm.Create("Rijndael"))
            {
                algorithm.GenerateIV();
                algorithm.GenerateKey();
                //algorithm.Padding = PaddingMode.Zeros;
                //algorithm.Mode = CipherMode.CBC;
                var key = new byte[algorithm.Key.Length];
                var iv  = new byte[algorithm.IV.Length];

                Array.Copy(sharedKey, 0, key, 0, key.Length);
                Array.Copy(sharedKey, key.Length, iv, 0, iv.Length);

                BlockChainService.WriteLogByteArray("Crypte:Encode:key", key);
                BlockChainService.WriteLogByteArray("Crypte:Encode:iv", iv);

                using (var cryptoTransform = algorithm.CreateEncryptor(key, iv))
                {
                    return(Transform(text, cryptoTransform));
                }
            }
        }
예제 #16
0
        /// <summary>
        /// A simply rijndael aes encryption, can be used to store passwords
        /// </summary>
        /// <param name="clearText">the string to call upon</param>
        /// <returns>an encryped string in base64 form</returns>
        public static string Encrypt(this string clearText)
        {
            string returnValue = clearText;

            try {
                byte[]             clearTextBytes = Encoding.ASCII.GetBytes(clearText);
                SymmetricAlgorithm rijn           = SymmetricAlgorithm.Create();

                using (MemoryStream ms = new MemoryStream()) {
                    byte[] rgbIV = Encoding.ASCII.GetBytes(RGBIV);
                    byte[] key   = Encoding.ASCII.GetBytes(KEY);
                    using (CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write)) {
                        cs.Write(clearTextBytes, 0, clearTextBytes.Length);
                        cs.FlushFinalBlock();

                        returnValue = Convert.ToBase64String(ms.ToArray());
                    }
                }
            } catch (Exception ex) {
                LOG.ErrorFormat("Error encrypting, error: {0}", ex.Message);
            }
            return(returnValue);
        }
예제 #17
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Value"></param>
        /// <param name="p_strKey">密钥</param>
        /// <param name="p_strIV">干扰码</param>
        /// <returns></returns>
        public string EncryptString(string Value, string p_strKey, string p_strIV)
        {
            ICryptoTransform ct;

            System.IO.MemoryStream ms;
            CryptoStream           cs;

            byte[] byt;

            //ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
            ct = mCSP.CreateEncryptor(Convert.FromBase64String(p_strKey.Trim()), Convert.FromBase64String(p_strIV.Trim()));

            byt = System.Text.Encoding.UTF8.GetBytes(Value);

            ms = new System.IO.MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();

            cs.Close();

            return(Convert.ToBase64String(ms.ToArray()));
        }
예제 #18
0
        public static byte[] AESEncrypt(this string text)
        {
            byte[]             data = Encoding.Unicode.GetBytes(text);
            SymmetricAlgorithm aes  = Rijndael.Create();

            aes.Key     = keyArray;
            aes.IV      = ivArray;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                    cs.FlushFinalBlock();
                    byte[] cipherBytes = ms.ToArray(); // 得到加密后的字节数组
                    cs.Close();
                    ms.Close();
                    aes.Clear();
                    return(cipherBytes);
                }
            }
        }
예제 #19
0
    private static byte[] EncryptBytes(
        SymmetricAlgorithm alg,
        byte[] message)
    {
        if ((message == null) || (message.Length == 0))
        {
            return(message);
        }

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

        using (var stream = new MemoryStream())
            using (var encryptor = alg.CreateEncryptor())
                using (var encrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
                {
                    encrypt.Write(message, 0, message.Length);
                    encrypt.FlushFinalBlock();
                    return(stream.ToArray());
                }
    }
예제 #20
0
파일: AES.cs 프로젝트: FineLqy/CQ
        /// <summary>
        /// AES加密算法
        /// </summary>
        /// <param name="plainText">明文字符串</param>
        /// <returns>将加密后的密文转换为Base64编码,以便显示</returns>
        public static string AESEncrypt(string plainText)
        {
            //分组加密算法
            SymmetricAlgorithm des = Rijndael.Create();

            byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组
            //设置密钥及密钥向量
            des.Key = Encoding.UTF8.GetBytes(Key);
            des.IV  = _key1;
            byte[] cipherBytes = null;
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cipherBytes = ms.ToArray();//得到加密后的字节数组
                    cs.Close();
                    ms.Close();
                }
            }
            return(Convert.ToBase64String(cipherBytes));
        }
예제 #21
0
        /// <summary>
        /// 对称加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string SymmetricEncrpyt(string str)
        {
            Guard.NotNullOrEmpty(str, "str");

            SymmetricAlgorithm cryptoObj = GetSymmetricAlgorithm(this.symmetricAlgorithmType);

            byte[] bytIn = UTF8Encoding.UTF8.GetBytes(str);
            using (MemoryStream ms = new MemoryStream())
            {
                cryptoObj.Key = GetLegalKey(cryptoObj);
                cryptoObj.IV  = GetLegalIV(cryptoObj);

                ICryptoTransform encrypto = cryptoObj.CreateEncryptor();
                using (CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write))
                {
                    cs.Write(bytIn, 0, bytIn.Length);
                    cs.FlushFinalBlock();
                    ms.Close();
                    byte[] bytOut = ms.ToArray();
                    return(Convert.ToBase64String(bytOut));
                }
            }
        }
예제 #22
0
 /// <summary>
 /// AES encoder
 /// </summary>
 /// <param name="str">string you want to encode.</param>
 /// <returns>encode string with Base64.</returns>
 public static string EncodeAES(string str)
 {
     try {
         SymmetricAlgorithm des        = Rijndael.Create();
         byte[]             inputBytes = Encoding.UTF8.GetBytes(str);
         des.Key = Encoding.UTF8.GetBytes(_aes_key);
         des.IV  = _aes_IV;
         byte[] cipherBytes = null;
         using (MemoryStream ms = new MemoryStream()) {
             using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) {
                 cs.Write(inputBytes, 0, inputBytes.Length);
                 cs.FlushFinalBlock();
                 cipherBytes = ms.ToArray();                         //get byte array
                 cs.Close();
                 ms.Close();
             }
         }
         return(Convert.ToBase64String(cipherBytes));
     } catch (Exception e) {
         XLAFInnerLog.Error(e.ToString());
     }
     return("");
 }
        public override DecryptResponse Query(DecryptRequest request, IServiceRouter router, RequestContext context)
        {
            DecryptResponse response = new DecryptResponse();

            using (SymmetricAlgorithm alg = SymmetricAlgorithm.Create(request.Algorithm))
            {
                alg.IV = request.IV;

                alg.Key = request.Key;

                using (ICryptoTransform transform = alg.CreateEncryptor())
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        memoryStream.Write(request.CipherText, 0, request.CipherText.Length);

                        memoryStream.Flush();

                        List <byte> bytes = new List <byte>();

                        using (CryptoStream stream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Read))
                        {
                            int readByte;

                            while ((readByte = stream.ReadByte()) >= 0)
                            {
                                bytes.Add((byte)readByte);
                            }
                        }

                        response.ClearText = bytes.ToArray();
                    }
                }
            }

            return(response);
        }
예제 #24
0
        public string Encrypting(string Source, string Key)
        {
            byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(Source);
            // create a MemoryStream so that the process can be done without I/O files
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            byte[] bytKey = GetLegalKey(Key);

            // set the private key
            mobjCryptoService.Key = bytKey;
            mobjCryptoService.IV  = bytKey;

            // create an Encryptor from the Provider Service instance
            ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();

            // create Crypto Stream that transforms a stream using the encryption
            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);

            // write out encrypted content into MemoryStream
            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();

            // get the output and trim the '\0' bytes
            byte[] bytOut = ms.GetBuffer();
            int    i      = 0;

            for (i = 0; i < bytOut.Length; i++)
            {
                if (bytOut[i] == 0)
                {
                    break;
                }
            }

            // convert into Base64 so that the result can be used in xml
            return(System.Convert.ToBase64String(bytOut, 0, i));
        }
예제 #25
0
 /// <summary>
 /// Encrypts a byte array
 /// </summary>
 /// <param name="Data">Data to encrypt</param>
 /// <param name="Key">Key to use to encrypt the data (can use PasswordDeriveBytes, Rfc2898DeriveBytes, etc. Really anything that implements DeriveBytes)</param>
 /// <param name="AlgorithmUsing">Algorithm to use for encryption (defaults to AES)</param>
 /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
 /// <param name="KeySize">Can be 64 (DES only), 128 (AES), 192 (AES and Triple DES), or 256 (AES)</param>
 /// <returns>An encrypted byte array</returns>
 public static byte[] Encrypt(this byte[] Data,
                              DeriveBytes Key,
                              SymmetricAlgorithm AlgorithmUsing = null,
                              string InitialVector = "OFRna73m*aze01xY",
                              int KeySize          = 256)
 {
     if (Data.IsNull())
     {
         return(null);
     }
     AlgorithmUsing = AlgorithmUsing.NullCheck(new RijndaelManaged());
     InitialVector.ThrowIfNullOrEmpty("InitialVector");
     using (DeriveBytes DerivedPassword = Key)
     {
         using (SymmetricAlgorithm SymmetricKey = AlgorithmUsing)
         {
             SymmetricKey.Mode = CipherMode.CBC;
             byte[] CipherTextBytes = null;
             using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(DerivedPassword.GetBytes(KeySize / 8), InitialVector.ToByteArray()))
             {
                 using (MemoryStream MemStream = new MemoryStream())
                 {
                     using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                     {
                         CryptoStream.Write(Data, 0, Data.Length);
                         CryptoStream.FlushFinalBlock();
                         CipherTextBytes = MemStream.ToArray();
                         MemStream.Close();
                         CryptoStream.Close();
                     }
                 }
             }
             SymmetricKey.Clear();
             return(CipherTextBytes);
         }
     }
 }
예제 #26
0
        private void CodeButton_Click(object sender, EventArgs e)
        {
            // cipher
            SymmetricAlgorithm sa = TripleDES.Create();

            sa.GenerateKey();
            key        = sa.Key;
            sa.Mode    = CipherMode.ECB;
            sa.Padding = PaddingMode.PKCS7;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(), CryptoStreamMode.Write);

            byte[] plainbytes = Encoding.Default.GetBytes(plainTextBox.Text);
            cs.Write(plainbytes, 0, plainbytes.Length);
            cs.Close();
            cipherbytes = ms.ToArray();
            ms.Close();
            // show ciphered text
            str = Encoding.Default.GetString(cipherbytes);
            cipherTextBox.Text = str;
            // decipher
            te = new byte[str.Length];
            te = Encoding.Default.GetBytes(str);
            SymmetricAlgorithm sa2 = TripleDES.Create();

            sa2.Key     = key;
            sa2.Mode    = CipherMode.ECB;
            sa2.Padding = PaddingMode.PKCS7;
            MemoryStream ms2 = new MemoryStream(te);
            CryptoStream cs2 = new CryptoStream(ms2, sa2.CreateDecryptor(), CryptoStreamMode.Read);

            byte[] plainbytes2 = new byte[te.Length];
            cs2.Read(plainbytes2, 0, te.Length);
            cs2.Close();
            ms2.Close();
            textBox.Text = Encoding.Default.GetString(plainbytes2);
        }
예제 #27
0
        public static byte[] EncryptData(SymmetricAlgorithms symmetricAlgorithm, byte[] inputBytes, byte[] key)
        {
            byte[] result;

            using (SymmetricAlgorithm algorithm = GetSymmetricAlgorithm(symmetricAlgorithm))
            {
                byte[] encrypted;
                byte[] salt       = new byte[PBKDF2_SaltSizeBytes];
                int    maxKeySize = GetLegalKeySizes(algorithm).Max();

                _rng.GetBytes(salt);
                using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(key, salt, PBKDF2_Iterations))
                {
                    algorithm.Key = pbkdf2.GetBytes(maxKeySize);
                }

                using (ICryptoTransform cryptoTransform = algorithm.CreateEncryptor())
                {
                    using (MemoryStream inputStream = new MemoryStream(inputBytes), transformedStream = new MemoryStream())
                    {
                        using (CryptoStream cryptoStream = new CryptoStream(inputStream, cryptoTransform, CryptoStreamMode.Read))
                        {
                            cryptoStream.CopyTo(transformedStream);
                        }

                        encrypted = transformedStream.ToArray();
                    }
                }

                result = new byte[salt.Length + algorithm.IV.Length + encrypted.Length];
                Buffer.BlockCopy(salt, 0, result, 0, salt.Length);
                Buffer.BlockCopy(algorithm.IV, 0, result, salt.Length, algorithm.IV.Length);
                Buffer.BlockCopy(encrypted, 0, result, salt.Length + algorithm.IV.Length, encrypted.Length);
            }

            return(result);
        }
예제 #28
0
        private static Stream CreateStream(Stream s, bool bEncrypt, byte[] pbKey, byte[] pbIV)
        {
            StandardAesEngine.ValidateArguments(s, bEncrypt, pbKey, pbIV);

            byte[] pbLocalIV = new byte[16];
            Array.Copy(pbIV, pbLocalIV, 16);

            byte[] pbLocalKey = new byte[32];
            Array.Copy(pbKey, pbLocalKey, 32);

#if KeePassUAP
            return(StandardAesEngineExt.CreateStream(s, bEncrypt, pbLocalKey, pbLocalIV));
#else
            SymmetricAlgorithm a = CryptoUtil.CreateAes();
            if (a.BlockSize != 128)            // AES block size
            {
                Debug.Assert(false);
                a.BlockSize = 128;
            }

            a.IV      = pbLocalIV;
            a.KeySize = 256;
            a.Key     = pbLocalKey;
            a.Mode    = m_rCipherMode;
            a.Padding = m_rCipherPadding;

            ICryptoTransform iTransform = (bEncrypt ? a.CreateEncryptor() : a.CreateDecryptor());
            Debug.Assert(iTransform != null);
            if (iTransform == null)
            {
                throw new SecurityException("Unable to create AES transform!");
            }

            return(new CryptoStream(s, iTransform, bEncrypt ? CryptoStreamMode.Write :
                                    CryptoStreamMode.Read));
#endif
        }
예제 #29
0
        private byte[] Encrypt(byte[] byteData)
        {
            MemoryStream       memoryStream       = new MemoryStream();
            SymmetricAlgorithm symmetricAlgorithm = DES.Create();

            symmetricAlgorithm.Key = new byte[]
            {
                115,
                17,
                147,
                32,
                91,
                245,
                111,
                7
            };
            symmetricAlgorithm.IV = new byte[]
            {
                14,
                177,
                19,
                167,
                154,
                220,
                12,
                15
            };
            byte[] result;
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cryptoStream.Write(byteData, 0, byteData.Length);
                cryptoStream.Close();
                byte[] array = memoryStream.ToArray();
                result = array;
            }
            return(result);
        }
예제 #30
0
        static byte[] Encrypt(string PlainText, SymmetricAlgorithm key)
        {
            try
            {
                // Create a memory stream.
                MemoryStream ms = new MemoryStream();

                // Create a CryptoStream using the memory stream and the
                // CSP DES key.
                CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);

                // Create a StreamWriter to write a string
                // to the stream.
                StreamWriter sw = new StreamWriter(encStream);

                // Write the plaintext to the stream.
                sw.WriteLine(PlainText);

                // Close the StreamWriter and CryptoStream.
                sw.Close();
                encStream.Close();

                // Get an array of bytes that represents
                // the memory stream.
                byte[] buffer = ms.ToArray();

                // Close the memory stream.
                ms.Close();

                // Return the encrypted byte array.
                return(buffer);
            }
            catch
            {
                return(null);
            }
        }
예제 #31
0
        public static Stream GetEncryptedStream(Stream inStream, SymmetricAlgorithm provider)
        {
            if (inStream == null)
            {
                throw new ArgumentNullException("Invalid stream.", "inStream");
            }
            if (provider == null)
            {
                throw new ArgumentNullException("Invalid provider.", "provider");
            }

            Stream compStream = CompressStream(inStream);

            MemoryStream outStream = new MemoryStream();

            CryptoStream encryptStream = new CryptoStream(outStream, provider.CreateEncryptor(), CryptoStreamMode.Write);

            // Read the in stream in 1024 byte chunks
            byte[] buffer    = new byte[1024];
            int    bytesRead = 0;

            do
            {
                bytesRead = compStream.Read(buffer, 0, 1024);

                if (bytesRead > 0)
                {
                    encryptStream.Write(buffer, 0, bytesRead);
                }
            }while (bytesRead > 0);

            encryptStream.FlushFinalBlock();

            outStream.Position = 0;

            return(outStream);
        }
예제 #32
0
    public CounterModeCryptoTransform(SymmetricAlgorithm symmetricAlgorithm, byte[] key, byte[] counter)
    {
        if (symmetricAlgorithm == null) throw new ArgumentNullException("symmetricAlgorithm");
        if (key == null) throw new ArgumentNullException("key");
        if (counter == null) throw new ArgumentNullException("counter");
        if (counter.Length != symmetricAlgorithm.BlockSize / 8)
            throw new ArgumentException(String.Format("Counter size must be same as block size (actual: {0}, expected: {1})",
                counter.Length, symmetricAlgorithm.BlockSize / 8));

        _symmetricAlgorithm = symmetricAlgorithm;
        _counter = counter;

        var zeroIv = new byte[_symmetricAlgorithm.BlockSize / 8];
        _counterEncryptor = symmetricAlgorithm.CreateEncryptor(key, zeroIv);
    }
예제 #33
0
    static bool Test(SymmetricAlgorithm cipher, byte[] key, byte[] iv, byte[] input, byte[] expected)
    {
        cipher.Mode = CipherMode.ECB;
        cipher.KeySize = key.Length * 8;
        cipher.Padding = PaddingMode.Zeros;

        byte[] output = new byte [input.Length];
        ICryptoTransform encryptor = cipher.CreateEncryptor (key, iv);
        encryptor.TransformBlock (input, 0, input.Length, output, 0);
        if (!Compare (output, expected))
            return false;

        byte[] original = new byte [output.Length];
        ICryptoTransform decryptor = cipher.CreateDecryptor (key, iv);
        decryptor.TransformBlock (output, 0, output.Length, original, 0);
        return Compare (original, input);
    }
	// Perform a primitive ECB encryption on a block.
	private void ECBBlock(byte[] buf, int index,
						  SymmetricAlgorithm alg, byte[] key)
			{
				ICryptoTransform encryptor;
				CipherMode mode = alg.Mode;
				PaddingMode padding = alg.Padding;
				alg.Mode = CipherMode.ECB;
				alg.Padding = PaddingMode.None;
				encryptor = alg.CreateEncryptor(key, null);
				alg.Mode = mode;
				alg.Padding = padding;
				encryptor.TransformBlock(buf, index, alg.BlockSize / 8,
										 buf, index);
				encryptor.Dispose();
			}
	// Run a cipher mode test.
	private void RunModeTest(SymmetricAlgorithm alg, CipherMode mode,
							 PaddingMode padding, String input)
			{
				// Set the algorithm modes.
				alg.Mode = mode;
				alg.Padding = padding;

				// Get the raw and padded versions of the input.
				byte[] rawInput = Encoding.ASCII.GetBytes(input);
				byte[] paddedInput = StringToBytes(input, alg);

				// Generate key and IV values.
				byte[] key = CreateKey(alg);
				byte[] iv = CreateIV(alg);

				// Encrypt the raw input in the selected mode.
				int size = alg.BlockSize / 8;
				int cutoff = rawInput.Length - rawInput.Length % size;
				ICryptoTransform encryptor;
				encryptor = alg.CreateEncryptor(key, iv);
				Assert(GetError("encryptor cannot transform multiple blocks",
								alg, input),
					   encryptor.CanTransformMultipleBlocks);
				if(mode == CipherMode.ECB || mode == CipherMode.CBC)
				{
					AssertEquals(GetError("encryptor has wrong input size",
										  alg, input),
								 size, encryptor.InputBlockSize);
					AssertEquals(GetError("encryptor has wrong output size",
										  alg, input),
								 size, encryptor.OutputBlockSize);
				}
				else
				{
					AssertEquals(GetError("encryptor has wrong input size",
										  alg, input),
								 1, encryptor.InputBlockSize);
					AssertEquals(GetError("encryptor has wrong output size",
										  alg, input),
								 1, encryptor.OutputBlockSize);
				}
				byte[] rawOutput = new byte [rawInput.Length + 256];
				int len = encryptor.TransformBlock
					(rawInput, 0, cutoff, rawOutput, 0);
				byte[] rawTail = encryptor.TransformFinalBlock
					(rawInput, cutoff, rawInput.Length - cutoff);
				Array.Copy(rawTail, 0, rawOutput, len, rawTail.Length);
				len += rawTail.Length;
				((IDisposable)encryptor).Dispose();

				// Reverse the ciphertext back to the original.
				cutoff = len - len % size;
				ICryptoTransform decryptor;
				decryptor = alg.CreateDecryptor(key, iv);
				Assert(GetError("decryptor cannot transform multiple blocks",
								alg, input),
					   decryptor.CanTransformMultipleBlocks);
				if(mode == CipherMode.ECB || mode == CipherMode.CBC)
				{
					AssertEquals(GetError("decryptor has wrong input size",
										  alg, input),
								 size, decryptor.InputBlockSize);
					AssertEquals(GetError("decryptor has wrong output size",
										  alg, input),
								 size, decryptor.OutputBlockSize);
				}
				else
				{
					AssertEquals(GetError("decryptor has wrong input size",
										  alg, input),
								 1, decryptor.InputBlockSize);
					AssertEquals(GetError("decryptor has wrong output size",
										  alg, input),
								 1, decryptor.OutputBlockSize);
				}
				byte[] rawReverse = new byte [rawInput.Length + 256];
				int rlen = decryptor.TransformBlock
					(rawOutput, 0, cutoff, rawReverse, 0);
				rawTail = decryptor.TransformFinalBlock
					(rawOutput, cutoff, len - cutoff);
				Array.Copy(rawTail, 0, rawReverse, rlen, rawTail.Length);
				rlen += rawTail.Length;
				((IDisposable)decryptor).Dispose();

				// Compare the reversed plaintext with the original.
				if(padding != PaddingMode.None)
				{
					AssertEquals(GetError
							("reversed plaintext has incorrect length",
							 alg, input), rawInput.Length, rlen);
					if(!IdenticalBlock(rawInput, 0, rawReverse, 0, rlen))
					{
						Fail(GetError
							("reversed plaintext is not the same as original",
							 alg, input));
					}
				}
				else
				{
					if(rawInput.Length > rlen)
					{
						Fail(GetError
							("reversed plaintext has incorrect length",
							 alg, input));
					}
					if(!IdenticalBlock(rawInput, 0, rawReverse, 0,
									   rawInput.Length))
					{
						Fail(GetError
							("reversed plaintext is not the same as original",
							 alg, input));
					}
				}

				// Encrypt the padded plaintext using a primitive
				// algorithm simulation to verify the expected output.
				byte[] paddedOutput;
				switch(mode)
				{
					case CipherMode.ECB:
					{
						paddedOutput = DoECB(paddedInput, alg, key);
					}
					break;

					case CipherMode.CBC:
					{
						paddedOutput = DoCBC(paddedInput, alg, key, iv);
					}
					break;

					case CipherMode.OFB:
					{
						paddedOutput = DoOFB(paddedInput, alg, key, iv);
					}
					break;

					case CipherMode.CFB:
					{
						paddedOutput = DoCFB(paddedInput, alg, key, iv);
					}
					break;

					case CipherMode.CTS:
					default:
					{
						paddedOutput = DoCTS(paddedInput, alg, key, iv);
					}
					break;
				}

				// Compare the actual output with the expected output.
				AssertEquals(GetError("ciphertext has incorrect length",
									  alg, input),
							 paddedOutput.Length, len);
				if(!IdenticalBlock(paddedOutput, 0, rawOutput, 0, len))
				{
					Fail(GetError("ciphertext was not the expected value",
								  alg, input));
				}
			}
	// Run a symmetric algorithm test.
	protected void RunSymmetric(SymmetricAlgorithm alg, byte[] key,
								byte[] plaintext, byte[] expected)
			{
				// Set up the algorithm the way we want.
				alg.Mode = CipherMode.ECB;
				alg.Padding = PaddingMode.None;

				// Create an encryptor and run the test forwards.
				ICryptoTransform encryptor = alg.CreateEncryptor(key, null);
				byte[] output = new byte [plaintext.Length * 2];
				byte[] tail;
				int len = encryptor.TransformBlock
						(plaintext, 0, plaintext.Length,
						 output, 0);
				AssertEquals("ECB encrypt length mismatch",
							 len, expected.Length);
				tail = encryptor.TransformFinalBlock
						(plaintext, 0, 0);
				AssertNotNull("ECB encrypt tail should be non-null");
				AssertEquals("ECB encrypt tail should be zero length",
							 tail.Length, 0);
				if(!IdenticalBlock(expected, 0, output, 0,
								   expected.Length))
				{
					Fail("did not encrypt to the expected output");
				}
				encryptor.Dispose();

				// Create a decryptor and run the test backwards.
				ICryptoTransform decryptor = alg.CreateDecryptor(key, null);
				len = decryptor.TransformBlock
						(expected, 0, expected.Length, output, 0);
				AssertEquals("ECB decrypt length mismatch",
							 len, expected.Length);
				tail = decryptor.TransformFinalBlock
						(expected, 0, 0);
				AssertNotNull("ECB decrypt tail should be non-null");
				AssertEquals("ECB decrypt tail should be zero length",
							 tail.Length, 0);
				if(!IdenticalBlock(plaintext, 0, output, 0,
								   plaintext.Length))
				{
					Fail("did not decrypt to the original plaintext");
				}
				decryptor.Dispose();
			}
예제 #37
0
    private static bool TestRoundTrip(SymmetricAlgorithm testAlgorithm, SymmetricAlgorithm baseline, List<byte[]> data, out byte[] result)
    {
        result = null;

        try
        {
            byte[] testCipherValue;
            byte[] baselineCipherValue;

            using (MemoryStream testEncrypted = new MemoryStream())
            using (MemoryStream baselineEncrypted = new MemoryStream())
            {
                using (CryptoStream testEncryptor = new CryptoStream(testEncrypted, testAlgorithm.CreateEncryptor(), CryptoStreamMode.Write))
                using (CryptoStream baselineEncryptor = new CryptoStream(baselineEncrypted, baseline.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    foreach (byte[] blocks in data)
                    {
                        testEncryptor.Write(blocks, 0, blocks.Length);
                        baselineEncryptor.Write(blocks, 0, blocks.Length);
                    }

                    testEncryptor.Close();
                    baselineEncryptor.Close();

                    testCipherValue = testEncrypted.ToArray();
                    baselineCipherValue = baselineEncrypted.ToArray();
                }
            }

            byte[] testRoundtrip;
            byte[] baselineRoundtrip;

            using (MemoryStream testDecrypted = new MemoryStream())
            using (MemoryStream baselineDecrypted = new MemoryStream())
            {
                using (CryptoStream testDecryptor = new CryptoStream(testDecrypted, testAlgorithm.CreateDecryptor(), CryptoStreamMode.Write))
                using (CryptoStream baselineDecryptor = new CryptoStream(baselineDecrypted, baseline.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    testDecryptor.Write(baselineCipherValue, 0, baselineCipherValue.Length);
                    testDecryptor.Close();

                    baselineDecryptor.Write(testCipherValue, 0, testCipherValue.Length);
                    baselineDecryptor.Close();

                    testRoundtrip = testDecrypted.ToArray();
                    baselineRoundtrip = baselineDecrypted.ToArray();
                }
            }

            if (!CompareBytes(testRoundtrip, baselineRoundtrip))
            {
                Console.WriteLine("Roundtrip bytes do not match");
                Console.WriteLine("Test data: {0}", ByteArrayToString(testRoundtrip));
				Console.WriteLine("Baseline data: {0}", ByteArrayToString(baselineRoundtrip));
				Console.WriteLine("Key: {0}", ByteArrayToString(testAlgorithm.Key));
				Console.WriteLine("IV: {0}", ByteArrayToString(testAlgorithm.IV));
				Console.WriteLine("Cipher mode: {0}", testAlgorithm.Mode.ToString());
				Console.WriteLine("Padding mode: {0}", testAlgorithm.Padding.ToString());
				return false;
            }

            result = testRoundtrip;
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine("Got an exception, fail");
            Console.WriteLine(e);
            return false;
        }
    }
예제 #38
0
 static void Speed(SymmetricAlgorithm cipher, int block)
 {
     byte[] input = new byte [block];
     byte[] output = new byte [block];
     DateTime now = DateTime.UtcNow;
     long size = 0;
     ICryptoTransform transform = cipher.CreateEncryptor ();
     while ((DateTime.UtcNow - now).TotalSeconds < 30) {
         transform.TransformBlock (input, 0, input.Length, output, 0);
         size += input.Length;
     }
     transform.TransformFinalBlock (input, 0, input.Length);
     size += input.Length;
     double speed = size / (DateTime.UtcNow - now).TotalSeconds;
     Console.WriteLine ("{0}: {1}: {2} Mbytes/sec", block, cipher, speed / 1024 / 1024);
 }