Ejemplo n.º 1
0
        public static string Encrypt(string input, string pwdValue)
        {
            try
            {
                byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input);
                byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue);
                // AesManaged - 高级加密标准(AES) 对称算法的管理类
                System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();
                // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数)             // 通过 密码 和 salt 派生密钥
                System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
                aes.Key       = rfc.GetBytes(aes.KeySize / 8);
                aes.IV        = rfc.GetBytes(aes.BlockSize / 8);
                // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象
                System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor();
                // 加密后的输出流
                System.IO.MemoryStream encryptStream = new System.IO.MemoryStream();
                // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接
                System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream(encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);
                // 将一个字节序列写入当前 CryptoStream (完成加密的过程)
                encryptor.Write(data, 0, data.Length);
                encryptor.Close();
                // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串
                string encryptedString = Convert.ToBase64String(encryptStream.ToArray());

                return(encryptedString);
            }
            catch
            {
            }
            return(input);
        }
Ejemplo n.º 2
0
        public static string decode(string plainStr)
        {
            System.Security.Cryptography.AesManaged aaa = new System.Security.Cryptography.AesManaged();
            aaa.Mode      = System.Security.Cryptography.CipherMode.CBC;
            aaa.KeySize   = 256;
            aaa.BlockSize = 128;
            aaa.Padding   = System.Security.Cryptography.PaddingMode.PKCS7;

            string keyStr = "cGFzc3dvcmQAejABCAAAAA==";
            string ivStr  = "cGFzc3dvcmQAAAenAAABCA==";

            byte[] ivArr  = Convert.FromBase64String(keyStr);
            byte[] keyArr = Convert.FromBase64String(ivStr);
            aaa.IV  = ivArr;
            aaa.Key = keyArr;

            // This array will contain the plain text in bytes
            byte[] plainText = Convert.FromBase64String(plainStr);

            // Creates Symmetric encryption and decryption objects
            System.Security.Cryptography.ICryptoTransform decrypto = aaa.CreateDecryptor();
            // The result of the encrypion and decryption
            byte[] decryptedText = decrypto.TransformFinalBlock(plainText, 0, plainText.Length);

            string decryptedString = ASCIIEncoding.UTF8.GetString(decryptedText);

            return(decryptedString);
        }
Ejemplo n.º 3
0
 static byte[] Encrypt(string plainText, byte[] Key, byte[] IV)
 {
     byte[] encrypted;
     // Create a new AesManaged.
     using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged())
     {
         // Create encryptor
         System.Security.Cryptography.ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);
         // Create MemoryStream
         using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
         {
             // Create crypto stream using the CryptoStream class. This class is the key to encryption
             // and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream
             // to encrypt
             using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
             {
                 // Create StreamWriter and write data to a stream
                 using (System.IO.StreamWriter sw = new System.IO.StreamWriter(cs))
                     sw.Write(plainText);
                 encrypted = ms.ToArray();
             }
         }
     }
     // Return encrypted data
     return(encrypted);
 }
Ejemplo n.º 4
0
        public List <byte> Decrypt(string encodedEncPayload)
        {
            if (_key.Count() == 0)
            {
                throw new Exception("Key hasn't been derived yet, encryption isn't available");
            }

            var result       = new List <byte>();
            var encPayloadIV = Convert.FromBase64String(encodedEncPayload);
            var IV           = encPayloadIV.Take(16);
            var payload      = encPayloadIV.Skip(16).ToList();

            byte[] key = null;

            using (var aes = new System.Security.Cryptography.AesManaged())
            {
                aes.Mode    = System.Security.Cryptography.CipherMode.CBC;
                aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                key         = _key.ToArray();
                System.Security.Cryptography.ProtectedMemory.Unprotect(key, System.Security.Cryptography.MemoryProtectionScope.SameProcess);
                aes.Key = key;
                aes.IV  = IV.ToArray();
                var enc = aes.CreateDecryptor();
                return(enc.TransformFinalBlock(payload.ToArray(), 0, payload.Count()).ToList());
            }
        }
Ejemplo n.º 5
0
        private static void Usingcertificate(ref MqttServerOptions options)
        {
            var certificate = new X509Certificate(@"C:\certs\test\test.cer", "");

            options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
            var aes = new System.Security.Cryptography.AesManaged();
        }
Ejemplo n.º 6
0
        private static byte[] Decrypt(byte[] cipherKey, byte[] ciphertext)
        {
            var cipher = new System.Security.Cryptography.AesManaged();

            cipher.Key     = cipherKey;
            cipher.Mode    = System.Security.Cryptography.CipherMode.CBC;
            cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

            var ivSize = cipher.IV.Length;
            var iv     = new byte[ivSize];

            Array.Copy(ciphertext, iv, ivSize);
            cipher.IV = iv;

            var data = new byte[ciphertext.Length - ivSize];

            Array.Copy(ciphertext, ivSize, data, 0, data.Length);

            using (var ms = new System.IO.MemoryStream())
            {
                using (var cs = new System.Security.Cryptography.CryptoStream(
                           ms, cipher.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                }

                var plaintext = ms.ToArray();
                return(plaintext);
            }
        }
        private static byte[] Decrypt(byte[] cipherKey, byte[] ciphertext)
        {
            var cipher = new System.Security.Cryptography.AesManaged();
            cipher.Key = cipherKey;
            cipher.Mode = System.Security.Cryptography.CipherMode.CBC;
            cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

            var ivSize = cipher.IV.Length;
            var iv = new byte[ivSize];
            Array.Copy(ciphertext, iv, ivSize);
            cipher.IV = iv;

            var data = new byte[ciphertext.Length - ivSize];
            Array.Copy(ciphertext, ivSize, data, 0, data.Length);

            using (var ms = new System.IO.MemoryStream())
            {
                using (var cs = new System.Security.Cryptography.CryptoStream(
                    ms, cipher.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                }

                var plaintext = ms.ToArray();
                return plaintext;
            }
        }
Ejemplo n.º 8
0
 public static void Main(string[] args)
 {
     Console.WriteLine("Hello World!");
     System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();
     System.Security.Cryptography.Xml.EncryptedReference eer = null;
     Console.WriteLine("Muu");
     ISet<string> newSet;
 }
        /// <summary>
        /// AES 解密 Byte -> String
        /// </summary>
        /// <param name="cipherText"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string ByteAesDecToString(byte[] cipherText, string key, string iv)
        {
            #region AES 解密 Byte -> String

            // 检查参数
            if (cipherText.IsEmptyBytes()) return null;
            if (key.IsNullOrEmptyOrSpace()) return null;
            if (iv.IsNullOrEmptyOrSpace()) return null;

            // 合成密钥
            var deckey = StringMd5ShaToString(false, string.Format("<{0}/>{1}</{2}>[{3}]", iv, key, iv, EnDecryptConst),
                                              16, false, 1, System.Text.Encoding.UTF8);
            var deciv = StringMd5ShaToString(false, string.Format("[{0}/]{1}[/{2}]<{3}>", iv, key, iv, EnDecryptConst),
                                             16, false, 1, System.Text.Encoding.UTF8);
            // 转换参数
            var keybyte = System.Text.Encoding.UTF8.GetBytes(deckey);
            if (keybyte.Length <= 0)
                return null;
            var ivbyte = System.Text.Encoding.UTF8.GetBytes(deciv);
            if (ivbyte.Length <= 0)
                return null;
            // 存储解密结果
            string plaintext;
            // 创建一个解密对象
            using (var aesAlg = new System.Security.Cryptography.AesManaged())
            {
                aesAlg.Key = keybyte;
                aesAlg.IV = ivbyte;
                // 创建一个解密对象
                var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // 创建一个解密内存流
                try
                {
                    using (var msDecrypt = new System.IO.MemoryStream(cipherText))
                    {
                        using (
                            var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor,
                                                                                          System.Security.Cryptography
                                                                                                .CryptoStreamMode.Read))
                        {
                            using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
                            {
                                // 得到String
                                plaintext = srDecrypt.ReadToEnd();
                            }
                        }
                    }
                }
                catch
                {
                    return null;
                }
            }
            // 返回String
            return plaintext;

            #endregion
        }
Ejemplo n.º 10
0
 public static byte[] AesEcb128Decrypt(byte[] cipher, byte[] key)
 {
     System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged
     {
         Key  = key,
         Mode = System.Security.Cryptography.CipherMode.ECB
     };
     System.Security.Cryptography.ICryptoTransform decryptor = aes.CreateDecryptor();
     return(decryptor.TransformFinalBlock(cipher, 0, cipher.Length));
 }
Ejemplo n.º 11
0
        /// <summary>
        /// This method initializes the Aes used to encrypt or decrypt the dataset.
        /// </summary>
        /// <param name="username">Username to use for the encryption</param>
        /// <param name="password">Password to use for the encryption</param>
        /// <returns>New instance of Aes</returns>
        private static System.Security.Cryptography.Aes InitAes(string username, string password)
        {
            System.Security.Cryptography.Aes aes = new System.Security.Cryptography.AesManaged();
            System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(password, System.Text.Encoding.Unicode.GetBytes(username));

            aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            aes.KeySize = 128;
            aes.Key     = rfc2898.GetBytes(16);
            aes.IV      = rfc2898.GetBytes(16);

            return(aes);
        }
Ejemplo n.º 12
0
    /// <summary>
    /// AesManagedを取得
    /// </summary>
    /// <param name="keySize">暗号化鍵の長さ</param>
    /// <param name="blockSize">ブロックサイズ</param>
    /// <param name="iv">初期化ベクトル(半角X文字(8bit * X = [keySize]bit))</param>
    /// <param name="key">暗号化鍵 (半X文字(8bit * X文字 = [keySize]bit))</param>
    private System.Security.Cryptography.AesManaged GetAesManager(int keySize, int blockSize, string iv, string key)
    {
        var aes = new System.Security.Cryptography.AesManaged();

        aes.KeySize   = keySize;
        aes.BlockSize = blockSize;
        aes.Mode      = System.Security.Cryptography.CipherMode.CBC;
        aes.IV        = System.Text.Encoding.UTF8.GetBytes(iv);
        aes.Key       = System.Text.Encoding.UTF8.GetBytes(key);
        aes.Padding   = System.Security.Cryptography.PaddingMode.PKCS7;
        return(aes);
    }
Ejemplo n.º 13
0
Archivo: Utility.cs Proyecto: JuRogn/OA
        /// <summary>
        /// 根据给定的字符串对其进行加密
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string input)
        {
            // 盐值
            string saltValue = "saltValue";
            // 密码值
            string pwdValue = "pwdValue";

            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input);
            byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue);

            // AesManaged - 高级加密标准(AES) 对称算法的管理类
            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();

            // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数)
            // 通过 密码 和 salt 派生密钥
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);

            /**/
            /*
         * AesManaged.BlockSize - 加密操作的块大小(单位:bit)
         * AesManaged.LegalBlockSizes - 对称算法支持的块大小(单位:bit)
         * AesManaged.KeySize - 对称算法的密钥大小(单位:bit)
         * AesManaged.LegalKeySizes - 对称算法支持的密钥大小(单位:bit)
         * AesManaged.Key - 对称算法的密钥
         * AesManaged.IV - 对称算法的密钥大小
         * Rfc2898DeriveBytes.GetBytes(int 需要生成的伪随机密钥字节数) - 生成密钥
         */

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            aes.Key = rfc.GetBytes(aes.KeySize / 8);
            aes.IV = rfc.GetBytes(aes.BlockSize / 8);

            // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象
            System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor();

            // 加密后的输出流
            System.IO.MemoryStream encryptStream = new System.IO.MemoryStream();

            // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接
            System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream
                (encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);

            // 将一个字节序列写入当前 CryptoStream (完成加密的过程)
            encryptor.Write(data, 0, data.Length);
            encryptor.Close();

            // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串
            string encryptedString = Convert.ToBase64String(encryptStream.ToArray());

            return encryptedString;
        }
Ejemplo n.º 14
0
        static System.Security.Cryptography.AesManaged CreateAesManagedObject(byte[] key = null, byte[] IV = null)
        {
            var aesManaged = new System.Security.Cryptography.AesManaged
            {
                Mode      = System.Security.Cryptography.CipherMode.CBC,
                Padding   = System.Security.Cryptography.PaddingMode.PKCS7,
                BlockSize = 128,
                KeySize   = 256
            };

            if (IV != null)
            {
                aesManaged.IV = IV;
            }
            if (key != null)
            {
                aesManaged.Key = key;
            }
            return(aesManaged);
        }
Ejemplo n.º 15
0
        public String Encrypt(List <byte> payload)
        {
            if (_key.Count() == 0)
            {
                throw new Exception("Key hasn't been derived yet, encryption isn't available");
            }

            string encPayload = null;

            byte[] key = null;
            try
            {
                var result = new List <byte>();
                using (var aes = new System.Security.Cryptography.AesManaged())
                {
                    aes.Mode    = System.Security.Cryptography.CipherMode.CBC;
                    aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                    aes.GenerateIV();
                    result.AddRange(aes.IV);
                    key = _key.ToArray();
                    System.Security.Cryptography.ProtectedMemory.Unprotect(key, System.Security.Cryptography.MemoryProtectionScope.SameProcess);
                    aes.Key = key;
                    var enc = aes.CreateEncryptor();
                    result.AddRange(enc.TransformFinalBlock(payload.ToArray(), 0, payload.Count));
                    encPayload = System.Convert.ToBase64String(result.ToArray());
                    result.Clear();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Encryption failed " + ex.Message);
            }
            finally
            {
                if (key != null)
                {
                    Array.Clear(key, 0, key.Length);
                }
            }
            return(encPayload);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Encrypt(string input)
        {
            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input);
            byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue);

            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            aes.Key = rfc.GetBytes(aes.KeySize / 8);
            aes.IV = rfc.GetBytes(aes.BlockSize / 8);

            System.Security.Cryptography.ICryptoTransform encrypt = aes.CreateEncryptor();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream
            (stream, encrypt, System.Security.Cryptography.CryptoStreamMode.Write);

            encryptor.Write(data, 0, data.Length);
            encryptor.Close();
            return Convert.ToBase64String(stream.ToArray());
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Decrypt(string input)
        {
            byte[] encryptBytes = Convert.FromBase64String(input);
            byte[] salt = Encoding.UTF8.GetBytes(saltValue);

            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            aes.Key = rfc.GetBytes(aes.KeySize / 8);
            aes.IV = rfc.GetBytes(aes.BlockSize / 8);

            System.Security.Cryptography.ICryptoTransform transform = aes.CreateDecryptor();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream
            (stream, transform, System.Security.Cryptography.CryptoStreamMode.Write);
            decryptor.Write(encryptBytes, 0, encryptBytes.Length);
            decryptor.Close();
            byte[] decryptBytes = stream.ToArray();
            return UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
        }
Ejemplo n.º 18
0
        internal static string EncryptAesManaged(string raw, byte[] Key, byte[] IV)
        {
            string sRetval = raw;

            try
            {
                // Create Aes that generates a new key and initialization vector (IV).
                // Same key must be used in encryption and decryption
                using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged())
                {
                    // Encrypt string
                    byte[] encrypted = Encrypt(raw, Key, IV);
                    sRetval = System.Convert.ToBase64String(encrypted);
                }
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
            return(sRetval);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
            //写新解密文
            using (System.IO.FileStream writeFile = System.IO.File.Create(Server.MapPath("./temp可删除/") + System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) + ".Dencode")) {
                //读取加密码key
                using (System.IO.Stream sr = FileUpload2.PostedFile.InputStream) {
                    System.Security.Cryptography.AesManaged Aes = new System.Security.Cryptography.AesManaged();
                    byte[] ByteKey = new byte[32];
                    sr.Read(ByteKey, 0, ByteKey.Length);
                    //读取KEY
                    using (System.Security.Cryptography.ICryptoTransform dencode = Aes.CreateDecryptor(ByteKey, ByteKey.Take(16).ToArray())) {
                        //开始解密一次性
                        //byte[] result = dencode.TransformFinalBlock(reads, 0, len);
                        //使用DES流解密
                        using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(writeFile, dencode, System.Security.Cryptography.CryptoStreamMode.Write)) {
                            while (sr.CanRead)
                            {
                                byte[] reads = new byte[2048];
                                //读取的有效长度
                                int len = sr.Read(reads, 0, reads.Length);
                                if (len == 0)
                                {
                                    break;
                                }
                                cs.Write(reads, 0, len);
                            }
                            cs.Close();
                        }
                    }


                    sr.Close();
                }


                writeFile.Close();
            }
        }
        private static byte[] Encrypt(byte[] cipherKey, byte[] plaintext)
        {
            var cipher = new System.Security.Cryptography.AesManaged();
            cipher.Key = cipherKey;
            cipher.Mode = System.Security.Cryptography.CipherMode.CBC;
            cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

            using (var ms = new System.IO.MemoryStream())
            {
                using (var cs = new System.Security.Cryptography.CryptoStream(
                    ms, cipher.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cs.Write(plaintext, 0, plaintext.Length);
                }

                var ciphertext = ms.ToArray();

                var message = new byte[cipher.IV.Length + ciphertext.Length];
                cipher.IV.CopyTo(message, 0);
                ciphertext.CopyTo(message, cipher.IV.Length);
                return message;
            }
        }
Ejemplo n.º 21
0
        static string Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
        {
            string plaintext = null;

            // Create AesManaged
            using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged())
            {
                // Create a decryptor
                System.Security.Cryptography.ICryptoTransform decryptor = aes.CreateDecryptor(Key, IV);
                // Create the streams used for decryption.
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(cipherText))
                {
                    // Create crypto stream
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                    {
                        // Read crypto stream
                        using (System.IO.StreamReader reader = new System.IO.StreamReader(cs))
                            plaintext = reader.ReadToEnd();
                    }
                }
            }
            return(plaintext);
        }
Ejemplo n.º 22
0
        public static string Decrypt(string input)
        {
            try
            {
                if (input.Length <= 15)
                {
                    return(input);
                }

                byte[] encryptBytes = Convert.FromBase64String(input);
                byte[] salt         = Encoding.UTF8.GetBytes(saltValue);
                System.Security.Cryptography.AesManaged         aes = new System.Security.Cryptography.AesManaged();
                System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);
                aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
                aes.Key       = rfc.GetBytes(aes.KeySize / 8);
                aes.IV        = rfc.GetBytes(aes.BlockSize / 8);
                // 用当前的 Key 属性和初始化向量 IV 创建对称解密器对象
                System.Security.Cryptography.ICryptoTransform decryptTransform = aes.CreateDecryptor();
                // 解密后的输出流
                System.IO.MemoryStream decryptStream = new System.IO.MemoryStream();
                // 将解密后的目标流(decryptStream)与解密转换(decryptTransform)相连接
                System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream(decryptStream, decryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);
                // 将一个字节序列写入当前 CryptoStream (完成解密的过程)
                decryptor.Write(encryptBytes, 0, encryptBytes.Length);
                decryptor.Close();
                // 将解密后所得到的流转换为字符串
                byte[] decryptBytes    = decryptStream.ToArray();
                string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
                return(decryptedString);
            }
            catch
            {
            }
            return(input);
        }
Ejemplo n.º 23
0
        // Adapted from Kevin-Robertson powershell Get-KerberosAESKey: https://gist.github.com/Kevin-Robertson/9e0f8bfdbf4c1e694e6ff4197f0a4372
        // References:
        // * [MS-KILE] open spec' https://msdn.microsoft.com/library/cc233855.aspx?f=255&MSPPError=-2147217396
        // * RFC regarding AES in Kerberos https://www.rfc-editor.org/rfc/pdfrfc/rfc3962.txt.pdf
        public static byte[] ComputeAES256KerberosKey(byte[] password, byte[] salt)
        {
            byte[]    AES256_CONSTANT = { 0x6B, 0x65, 0x72, 0x62, 0x65, 0x72, 0x6F, 0x73, 0x7B, 0x9B, 0x5B, 0x2B, 0x93, 0x13, 0x2B, 0x93, 0x5C, 0x9B, 0xDC, 0xDA, 0xD9, 0x5C, 0x98, 0x99, 0xC4, 0xCA, 0xE4, 0xDE, 0xE6, 0xD6, 0xCA, 0xE4 };
            const int rounds          = 4096;
            var       pbkdf2          = new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, rounds);

            byte[] pbkdf2_aes256_key = pbkdf2.GetBytes(32);

            string pbkdf2_aes256_key_string = System.BitConverter.ToString(pbkdf2_aes256_key).Replace("-", "");

            var aes = new System.Security.Cryptography.AesManaged();

            aes.Mode    = System.Security.Cryptography.CipherMode.CBC;
            aes.Padding = System.Security.Cryptography.PaddingMode.None;
            aes.KeySize = 256;
            aes.Key     = pbkdf2_aes256_key;
            aes.IV      = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
            var encryptor = aes.CreateEncryptor();

            byte[] aes256_key_part_1 = encryptor.TransformFinalBlock(AES256_CONSTANT, 0, AES256_CONSTANT.Length);
            byte[] aes256_key_part_2 = encryptor.TransformFinalBlock(aes256_key_part_1, 0, aes256_key_part_1.Length);
            byte[] aes256_key        = aes256_key_part_1.Take(16).Concat(aes256_key_part_2.Take(16)).ToArray();
            return(aes256_key);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Decrypts and notifies MainActivity with the interpreted message contents.
        /// </summary>
        /// <param name="encrypted_message"></param>
        private void DecryptMessageAndNotify(string encrypted_message)
        {
            byte[] iv         = StringToByteArray(encrypted_message.Substring(0, 32));
            byte[] msg        = StringToByteArray(encrypted_message.Substring(32, 32));
            byte[] secret     = sharedKey.ToByteArrayUnsigned();
            string secret_str = ByteArrayToString(secret);

            byte[] iv1     = new byte[16];
            byte[] msg1    = new byte[16];
            byte[] secret1 = new byte[32];

            System.Buffer.BlockCopy(iv, 0, iv1, 0, iv.Length);
            System.Buffer.BlockCopy(msg, 0, msg1, 0, msg1.Length);
            System.Buffer.BlockCopy(secret, 0, secret1, 0, secret.Length);

            using (MemoryStream ms = new MemoryStream())
            {
                using (System.Security.Cryptography.AesManaged cryptor = new System.Security.Cryptography.AesManaged())
                {
                    cryptor.Mode      = System.Security.Cryptography.CipherMode.CBC;
                    cryptor.Padding   = System.Security.Cryptography.PaddingMode.None;
                    cryptor.KeySize   = 256;
                    cryptor.BlockSize = 128;

                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, cryptor.CreateDecryptor(secret1, iv1), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(msg1, 0, msg1.Length);
                    }

                    byte[] result = ms.ToArray();
                    Task.Run(() => InterperetGesture(result[0]));
                }
            }

            EncryptedMsg = "";
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 提交数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            //创建一个加密key
            string guid = Guid.NewGuid().ToString().Replace("-", "");

            byte[] ByteKey = System.Text.UTF8Encoding.UTF8.GetBytes(guid.ToCharArray());
            System.Security.Cryptography.AesManaged Aes = new System.Security.Cryptography.AesManaged();
            var encode = Aes.CreateEncryptor(ByteKey, ByteKey.Take(16).ToArray());


            byte[] byteArray = new byte[FileUpload1.PostedFile.InputStream.Length];
            FileUpload1.PostedFile.InputStream.Read(byteArray, 0, byteArray.Length);


            ///加密
            var list = encode.TransformFinalBlock(byteArray, 0, byteArray.Length).ToList();

            //写入加密KEY
            for (int i = 31; i >= 0; i--)
            {
                //加入到集合
                list.Insert(0, ByteKey[i]);
            }

            Response.Write(guid);

            //转换成Array
            byteArray = list.ToArray();



            System.IO.File.WriteAllBytes(Server.MapPath("./temp可删除/") + System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName) + ".Encode", byteArray);


            Response.Write("<br/>" + System.Text.UTF8Encoding.UTF8.GetString(byteArray.Take(32).ToArray()));
        }
Ejemplo n.º 26
0
        private static byte[] Encrypt(byte[] cipherKey, byte[] plaintext)
        {
            var cipher = new System.Security.Cryptography.AesManaged();

            cipher.Key     = cipherKey;
            cipher.Mode    = System.Security.Cryptography.CipherMode.CBC;
            cipher.Padding = System.Security.Cryptography.PaddingMode.ISO10126;

            using (var ms = new System.IO.MemoryStream())
            {
                using (var cs = new System.Security.Cryptography.CryptoStream(
                           ms, cipher.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cs.Write(plaintext, 0, plaintext.Length);
                }

                var ciphertext = ms.ToArray();

                var message = new byte[cipher.IV.Length + ciphertext.Length];
                cipher.IV.CopyTo(message, 0);
                ciphertext.CopyTo(message, cipher.IV.Length);
                return(message);
            }
        }
Ejemplo n.º 27
0
        /// 
        ///  <summary>
        ///  AES 加密 String -> Byte
        ///  </summary>
        ///  <param name="plainText"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static byte[] StringAesEncToByte(string plainText, string key, string iv)
        {
            #region AES 加密 String -> Byte

            // 检查参数
            if (string.IsNullOrEmpty(plainText))
                return null;
            if (string.IsNullOrEmpty(key))
                return null;
            if (string.IsNullOrEmpty(iv))
                return null;
            // 合成密钥
            var enckey = StringMd5ShaToString(false, string.Format("<{0}/>{1}</{2}>[{3}]", iv, key, iv, EnDecryptConst),
                                              16, false, 1, System.Text.Encoding.UTF8);
            var enciv = StringMd5ShaToString(false, string.Format("[{0}/]{1}[/{2}]<{3}>", iv, key, iv, EnDecryptConst),
                                             16, false, 1, System.Text.Encoding.UTF8);
            // 转换密钥
            var keybyte = System.Text.Encoding.UTF8.GetBytes(enckey);
            if (keybyte.Length <= 0)
                return null;
            var ivbyte = System.Text.Encoding.UTF8.GetBytes(enciv);
            if (ivbyte.Length <= 0)
                return null;
            byte[] encrypted;
            // 创建一个加密对象
            using (var aesAlg = new System.Security.Cryptography.AesManaged())
            {
                aesAlg.Key = keybyte;
                aesAlg.IV = ivbyte;
                // 创建一个加密来执行流的转换
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                // 为加密创建一个内存流
                try
                {
                    using (var msEncrypt = new System.IO.MemoryStream())
                    {
                        using (
                            var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor,
                                                                                          System.Security.Cryptography
                                                                                                .CryptoStreamMode.Write)
                            )
                        {
                            using (var swEncrypt = new System.IO.StreamWriter(csEncrypt))
                            {
                                // 把所有数据写进流
                                swEncrypt.Write(plainText);
                            }
                            // 把内存流转换为字节数组
                            encrypted = msEncrypt.ToArray();
                        }
                    }
                }
                catch
                {
                    return null;
                }
            }
            // 返回此加密字节
            return encrypted;

            #endregion
        }
        ///
        ///  <summary>
        ///  AES 加密 String -> Byte
        ///  </summary>
        ///  <param name="plainText"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static byte[] StringAesEncToByte(string plainText, string key, string iv)
        {
            #region AES 加密 String -> Byte

            // 检查参数
            if (string.IsNullOrEmpty(plainText))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(key))
            {
                return(null);
            }
            if (string.IsNullOrEmpty(iv))
            {
                return(null);
            }
            // 合成密钥
            var enckey = StringMd5ShaToString(false, string.Format("<{0}/>{1}</{2}>[{3}]", iv, key, iv, EnDecryptConst),
                                              16, false, 1, System.Text.Encoding.UTF8);
            var enciv = StringMd5ShaToString(false, string.Format("[{0}/]{1}[/{2}]<{3}>", iv, key, iv, EnDecryptConst),
                                             16, false, 1, System.Text.Encoding.UTF8);
            // 转换密钥
            var keybyte = System.Text.Encoding.UTF8.GetBytes(enckey);
            if (keybyte.Length <= 0)
            {
                return(null);
            }
            var ivbyte = System.Text.Encoding.UTF8.GetBytes(enciv);
            if (ivbyte.Length <= 0)
            {
                return(null);
            }
            byte[] encrypted;
            // 创建一个加密对象
            using (var aesAlg = new System.Security.Cryptography.AesManaged())
            {
                aesAlg.Key = keybyte;
                aesAlg.IV  = ivbyte;
                // 创建一个加密来执行流的转换
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                // 为加密创建一个内存流
                try
                {
                    using (var msEncrypt = new System.IO.MemoryStream())
                    {
                        using (
                            var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor,
                                                                                          System.Security.Cryptography
                                                                                          .CryptoStreamMode.Write)
                            )
                        {
                            using (var swEncrypt = new System.IO.StreamWriter(csEncrypt))
                            {
                                // 把所有数据写进流
                                swEncrypt.Write(plainText);
                            }
                            // 把内存流转换为字节数组
                            encrypted = msEncrypt.ToArray();
                        }
                    }
                }
                catch
                {
                    return(null);
                }
            }
            // 返回此加密字节
            return(encrypted);

            #endregion
        }
        /// <summary>
        /// AES 解密 Byte -> String
        /// </summary>
        /// <param name="cipherText"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static string ByteAesDecToString(byte[] cipherText, string key, string iv)
        {
            #region AES 解密 Byte -> String

            // 检查参数
            if (cipherText.IsEmptyBytes())
            {
                return(null);
            }
            if (key.IsNullOrEmptyOrSpace())
            {
                return(null);
            }
            if (iv.IsNullOrEmptyOrSpace())
            {
                return(null);
            }

            // 合成密钥
            var deckey = StringMd5ShaToString(false, string.Format("<{0}/>{1}</{2}>[{3}]", iv, key, iv, EnDecryptConst),
                                              16, false, 1, System.Text.Encoding.UTF8);
            var deciv = StringMd5ShaToString(false, string.Format("[{0}/]{1}[/{2}]<{3}>", iv, key, iv, EnDecryptConst),
                                             16, false, 1, System.Text.Encoding.UTF8);
            // 转换参数
            var keybyte = System.Text.Encoding.UTF8.GetBytes(deckey);
            if (keybyte.Length <= 0)
            {
                return(null);
            }
            var ivbyte = System.Text.Encoding.UTF8.GetBytes(deciv);
            if (ivbyte.Length <= 0)
            {
                return(null);
            }
            // 存储解密结果
            string plaintext;
            // 创建一个解密对象
            using (var aesAlg = new System.Security.Cryptography.AesManaged())
            {
                aesAlg.Key = keybyte;
                aesAlg.IV  = ivbyte;
                // 创建一个解密对象
                var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // 创建一个解密内存流
                try
                {
                    using (var msDecrypt = new System.IO.MemoryStream(cipherText))
                    {
                        using (
                            var csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor,
                                                                                          System.Security.Cryptography
                                                                                          .CryptoStreamMode.Read))
                        {
                            using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
                            {
                                // 得到String
                                plaintext = srDecrypt.ReadToEnd();
                            }
                        }
                    }
                }
                catch
                {
                    return(null);
                }
            }
            // 返回String
            return(plaintext);

            #endregion
        }
Ejemplo n.º 30
0
        public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)
        {
            //User Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new System.ArgumentException(string.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey");
            }

            if (authKey == null || authKey.Length != KeyBitSize / 8)
            {
                throw new System.ArgumentException(string.Format("Key needs to be {0} bit!", KeyBitSize), "authKey");
            }

            if (secretMessage == null || secretMessage.Length < 1)
            {
                throw new System.ArgumentException("Secret Message Required!", "secretMessage");
            }

            //non-secret payload optional
            nonSecretPayload = nonSecretPayload ?? new byte[] { };

            byte[] cipherText;
            byte[] iv;

            using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged
            {
                KeySize = KeyBitSize,
                BlockSize = BlockBitSize,
                Mode = System.Security.Cryptography.CipherMode.CBC,
                Padding = System.Security.Cryptography.PaddingMode.PKCS7
            })
            {
                //Use random IV
                aes.GenerateIV();
                iv = aes.IV;

                using (System.Security.Cryptography.ICryptoTransform encrypter = aes.CreateEncryptor(cryptKey, iv))

                    using (System.IO.MemoryStream cipherStream = new System.IO.MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(cipherStream, encrypter, System.Security.Cryptography.CryptoStreamMode.Write))

                            using (System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(cryptoStream))
                            {
                                //Encrypt Data
                                binaryWriter.Write(secretMessage);
                            }

                        cipherText = cipherStream.ToArray();
                    }
            }

            //Assemble encrypted message and add authentication
            using (System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(authKey))

                using (System.IO.MemoryStream encryptedStream = new System.IO.MemoryStream())
                {
                    using (System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(encryptedStream))
                    {
                        //Prepend non-secret payload if any
                        binaryWriter.Write(nonSecretPayload);

                        //Prepend IV
                        binaryWriter.Write(iv);

                        //Write Ciphertext
                        binaryWriter.Write(cipherText);

                        binaryWriter.Flush();

                        //Authenticate all data
                        byte[] tag = hmac.ComputeHash(encryptedStream.ToArray());

                        //Postpend tag
                        binaryWriter.Write(tag);
                    }

                    return(encryptedStream.ToArray());
                }
        }
Ejemplo n.º 31
0
        public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)
        {
            //Basic Usage Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new System.ArgumentException(string.Format("CryptKey needs to be {0} bit!", KeyBitSize), "cryptKey");
            }

            if (authKey == null || authKey.Length != KeyBitSize / 8)
            {
                throw new System.ArgumentException(string.Format("AuthKey needs to be {0} bit!", KeyBitSize), "authKey");
            }

            if (encryptedMessage == null || encryptedMessage.Length == 0)
            {
                throw new System.ArgumentException("Encrypted Message Required!", "encryptedMessage");
            }

            using (System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(authKey))
            {
                byte[] sentTag = new byte[hmac.HashSize / 8];

                //Calculate Tag
                byte[] calcTag = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);

                int ivLength = (BlockBitSize / 8);

                //if message length is to small just return null
                if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)
                {
                    return(null);
                }

                //Grab Sent Tag
                System.Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);

                //Compare Tag with constant time comparison
                int compare = 0;

                for (int i = 0; i < sentTag.Length; i++)
                {
                    compare |= sentTag[i] ^ calcTag[i];
                }

                //if message doesn't authenticate return null
                if (compare != 0)
                {
                    return(null);
                }

                using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged
                {
                    KeySize = KeyBitSize,
                    BlockSize = BlockBitSize,
                    Mode = System.Security.Cryptography.CipherMode.CBC,
                    Padding = System.Security.Cryptography.PaddingMode.PKCS7
                })
                {
                    //Grab IV from message
                    byte[] iv = new byte[ivLength];

                    System.Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);

                    using (System.Security.Cryptography.ICryptoTransform decrypter = aes.CreateDecryptor(cryptKey, iv))

                        using (System.IO.MemoryStream plainTextStream = new System.IO.MemoryStream())
                        {
                            using (System.Security.Cryptography.CryptoStream decrypterStream = new System.Security.Cryptography.CryptoStream(plainTextStream, decrypter, System.Security.Cryptography.CryptoStreamMode.Write))

                                using (System.IO.BinaryWriter binaryWriter = new System.IO.BinaryWriter(decrypterStream))
                                {
                                    //Decrypt Cipher Text from Message
                                    binaryWriter.Write(
                                        encryptedMessage,
                                        nonSecretPayloadLength + iv.Length,
                                        encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length
                                        );
                                }

                            //Return Plain Text
                            return(plainTextStream.ToArray());
                        }
                }
            }
        }
Ejemplo n.º 32
0
        public bool Connect(string host, int port, string module, bool requirewrite = false)
        {
            if (port == -1)
                port = VersionrDefaultPort;
            IEnumerator<SharedNetwork.Protocol> protocols = SharedNetwork.AllowedProtocols.Cast<SharedNetwork.Protocol>().GetEnumerator();
            Retry:
            if (!protocols.MoveNext())
            {
                Printer.PrintMessage("#e#No valid protocols available.##");
                return false;
            }
            Host = host;
            Port = port;
            Module = module;
            Connected = false;
            try
            {
                Connection = new System.Net.Sockets.TcpClient();
                var connectionTask = Connection.ConnectAsync(Host, Port);
                if (!connectionTask.Wait(5000))
                {
                    throw new Exception(string.Format("Couldn't connect to target: {0}", this.VersionrURL));
                }
            }
            catch (Exception e)
            {
                Printer.PrintError(e.Message);
                return false;
            }
            if (Connection.Connected)
            {
                try
                {
                    Printer.PrintDiagnostics("Connected to server at {0}:{1}", host, port);
                    Handshake hs = Handshake.Create(protocols.Current);
                    hs.RequestedModule = Module;
                    Printer.PrintDiagnostics("Sending handshake...");
                    Connection.NoDelay = true;
                    ProtoBuf.Serializer.SerializeWithLengthPrefix<Handshake>(Connection.GetStream(), hs, ProtoBuf.PrefixStyle.Fixed32);

                    var startTransaction = ProtoBuf.Serializer.DeserializeWithLengthPrefix<Network.StartTransaction>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                    if (startTransaction == null || !startTransaction.Accepted)
                    {
                        Printer.PrintError("#b#Server rejected connection.##");
                        if (startTransaction != null && hs.VersionrProtocol != startTransaction.ServerHandshake.VersionrProtocol)
                            Printer.PrintError("## Protocol mismatch - local: {0}, remote: {1}", hs.VersionrProtocol, startTransaction.ServerHandshake.VersionrProtocol);
                        else
                        {
                            if (startTransaction == null)
                                Printer.PrintError("## Connection terminated unexpectedly.");
                            else
                                Printer.PrintError("## Rejected request.");
                            return false;
                        }
                        Printer.PrintError("#b#Attempting to retry with a lower protocol.##");
                        goto Retry;
                    }
                    Printer.PrintDiagnostics("Server domain: {0}", startTransaction.Domain);
                    if (Workspace != null && !string.IsNullOrEmpty(startTransaction.Domain) && startTransaction.Domain != Workspace.Domain.ToString())
                    {
                        Printer.PrintError("Server domain doesn't match client domain. Disconnecting.");
                        return false;
                    }

                    RemoteDomain = startTransaction.Domain;

                    if (SharedNetwork.SupportsAuthentication(startTransaction.ServerHandshake.CheckProtocol().Value))
                    {
                        var command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                        if (command.Type == NetCommandType.Authenticate)
                        {
                            bool runauth = true;
                            var challenge = ProtoBuf.Serializer.DeserializeWithLengthPrefix<AuthenticationChallenge>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                            if ((!requirewrite && (command.Identifier & 1) != 0) ||
                                (requirewrite && (command.Identifier & 2) != 0)) // server supports unauthenticated access
                            {
                                AuthenticationResponse response = new AuthenticationResponse()
                                {
                                    IdentifierToken = string.Empty,
                                    Mode = AuthenticationMode.Guest
                                };
                                ProtoBuf.Serializer.SerializeWithLengthPrefix(Connection.GetStream(), response, ProtoBuf.PrefixStyle.Fixed32);
                                command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                                if (command.Type == NetCommandType.Acknowledge)
                                    runauth = false;
                            }
                            if (runauth)
                            {
                                bool q = Printer.Quiet;
                                Printer.Quiet = false;
                                Printer.PrintMessage("Server at #b#{0}## requires authentication.", VersionrURL);
                                while (true)
                                {
                                    if (challenge.AvailableModes.Contains(AuthenticationMode.Simple))
                                    {
                                        System.Console.CursorVisible = true;
                                        Printer.PrintMessageSingleLine("#b#Username:## ");
                                        string user = System.Console.ReadLine();
                                        Printer.PrintMessageSingleLine("#b#Password:## ");
                                        string pass = GetPassword();
                                        System.Console.CursorVisible = false;

                                        user = user.Trim(new char[] { '\r', '\n', ' ' });

                                        AuthenticationResponse response = new AuthenticationResponse()
                                        {
                                            IdentifierToken = user,
                                            Mode = AuthenticationMode.Simple,
                                            Payload = System.Text.ASCIIEncoding.ASCII.GetBytes(BCrypt.Net.BCrypt.HashPassword(pass, challenge.Salt))
                                        };
                                        Printer.PrintMessage("\n");
                                        ProtoBuf.Serializer.SerializeWithLengthPrefix(Connection.GetStream(), response, ProtoBuf.PrefixStyle.Fixed32);
                                        command = ProtoBuf.Serializer.DeserializeWithLengthPrefix<NetCommand>(Connection.GetStream(), ProtoBuf.PrefixStyle.Fixed32);
                                        if (command.Type == NetCommandType.AuthRetry)
                                            Printer.PrintError("#e#Authentication failed.## Retry.");
                                        if (command.Type == NetCommandType.AuthFail)
                                        {
                                            Printer.PrintError("#e#Authentication failed.##");
                                            return false;
                                        }
                                        if (command.Type == NetCommandType.Acknowledge)
                                            break;
                                    }
                                    else
                                    {
                                        Printer.PrintError("Unsupported authentication requirements!");
                                        return false;
                                    }
                                }
                                Printer.Quiet = q;
                            }
                        }
                    }
                    if (startTransaction.Encrypted)
                    {
                        var key = startTransaction.RSAKey;
                        Printer.PrintDiagnostics("Server RSA Key: {0}", key.Fingerprint());

                        var publicKey = new System.Security.Cryptography.RSACryptoServiceProvider();
                        publicKey.ImportParameters(key);

                        Printer.PrintDiagnostics("Generating secret key for data channel...");
                        System.Security.Cryptography.RSAOAEPKeyExchangeFormatter exch = new System.Security.Cryptography.RSAOAEPKeyExchangeFormatter(publicKey);

                        System.Security.Cryptography.AesManaged aesProvider = new System.Security.Cryptography.AesManaged();
                        aesProvider.KeySize = 256;
                        aesProvider.GenerateIV();
                        aesProvider.GenerateKey();

                        AESProvider = aesProvider;
                        AESKey = aesProvider.Key;
                        AESIV = aesProvider.IV;

                        Printer.PrintDiagnostics("Key: {0}", System.Convert.ToBase64String(aesProvider.Key));
                        var keyExchangeObject = new Network.StartClientTransaction() { Key = exch.CreateKeyExchange(aesProvider.Key), IV = exch.CreateKeyExchange(aesProvider.IV) };

                        ProtoBuf.Serializer.SerializeWithLengthPrefix<StartClientTransaction>(Connection.GetStream(), keyExchangeObject, ProtoBuf.PrefixStyle.Fixed32);
                        Connection.GetStream().Flush();
                        Connected = true;
                        SharedNetwork.SharedNetworkInfo sharedInfo = new SharedNetwork.SharedNetworkInfo()
                        {
                            DecryptorFunction = () => { return Decryptor; },
                            EncryptorFunction = () => { return Encryptor; },
                            Stream = Connection.GetStream(),
                            Workspace = Workspace,
                            Client = true,
                            CommunicationProtocol = protocols.Current
                        };

                        SharedInfo = sharedInfo;
                    }
                    else
                    {
                        Printer.PrintDiagnostics("Using cleartext communication");
                        var keyExchangeObject = new Network.StartClientTransaction();
                        ProtoBuf.Serializer.SerializeWithLengthPrefix<StartClientTransaction>(Connection.GetStream(), keyExchangeObject, ProtoBuf.PrefixStyle.Fixed32);
                        Connection.GetStream().Flush();
                        Connected = true;
                        SharedNetwork.SharedNetworkInfo sharedInfo = new SharedNetwork.SharedNetworkInfo()
                        {
                            DecryptorFunction = null,
                            EncryptorFunction = null,
                            Stream = Connection.GetStream(),
                            Workspace = Workspace,
                            Client = true,
                            CommunicationProtocol = protocols.Current
                        };
                        SharedInfo = sharedInfo;
                    }
                    return true;
                }
                catch (Exception e)
                {
                    Printer.PrintError("Error encountered: {0}", e);
                    return false;
                }
            }
            else
                return false;
        }
Ejemplo n.º 33
0
        /// <summary>
        /// AES数据解密
        /// SALT先用当天的日期尝试
        /// 如果失败的话,就用昨天的日期来尝试(考虑到0:00-0:30的时候可能会出现这种问题
        /// SALT默认为8位,如果为9位的话,说明是已经采用昨天的日期作为SALT(默认再最前添加一个‘Y’字符作为flag)
        /// 如果都解密失败的话,就返回null
        /// </summary>
        /// <param name="input">解密前的字符串</param>
        /// <param name="salt">随机值(SALT),默认为8位,如果为9位的话,说明是已经采用昨天的日期作为SALT</param>
        /// <param name="password">密码</param>
        /// <returns>解密后的字符串</returns>
        public static string Decrypt(string input, string salt, string password)
        {
            byte[] encryptBytes;
            try
            {
                //传参数时,会将加号替换成空格
                encryptBytes = Convert.FromBase64String(input.Replace(' ', '+'));
            }
            catch
            {
                return(null);
            }
            bool isLastDaySalt = (salt.Length > s_saltLength) ? true : false;

            if (isLastDaySalt)
            {
                salt = salt.Substring(salt.Length - s_saltLength);
            }
            byte[] saltBytes = Encoding.UTF8.GetBytes(salt);


            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged();

            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(password, saltBytes);

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
            aes.Key       = rfc.GetBytes(aes.KeySize / 8);
            aes.IV        = rfc.GetBytes(aes.BlockSize / 8);

            // 用当前的 Key 属性和初始化向量 IV 创建对称解密器对象
            System.Security.Cryptography.ICryptoTransform decryptTransform = aes.CreateDecryptor();

            // 解密后的输出流
            MemoryStream decryptStream = new MemoryStream();

            // 将解密后的目标流(decryptStream)与解密转换(decryptTransform)相连接
            System.Security.Cryptography.CryptoStream decryptor = new System.Security.Cryptography.CryptoStream(
                decryptStream, decryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);

            // 将一个字节序列写入当前 CryptoStream (完成解密的过程)

            decryptor.Write(encryptBytes, 0, encryptBytes.Length);

            try
            {
                decryptor.Close();
            }
            catch
            {
                if (isLastDaySalt)
                {
                    decryptor = null;
                    return(null);
                }
                DateTime parsedDate;
                DateTime.TryParseExact(salt, "yyyyMMdd", null,
                                       DateTimeStyles.None, out parsedDate);
                if (parsedDate.Year == 1)//Datetime format error, output 0001/1/1
                {
                    return(null);
                }
                string lastDaySalt = string.Format("Y{0}"
                                                   , parsedDate.AddDays(1).ToString("yyyyMMdd"));//stand for yesterday's salt, and add "Y" in the 1st character as flag
                var lastDaydecryptedString = Decrypt(input, lastDaySalt, password);

                return(lastDaydecryptedString);
            }

            // 将解密后所得到的流转换为字符串
            byte[] decryptBytes    = decryptStream.ToArray();
            string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);

            return(decryptedString);
        }
 public AESAlgorithmImplementation()
 {
     _algorithm = new System.Security.Cryptography.AesManaged();
 }