Ejemplo n.º 1
0
 public NetworkProtocol(Socket client, ECCBaseClass ecc)
 {
     this.ecc              = ecc;
     this.socket           = client;
     this.aes.KeySize      = 256;
     this.aes.BlockSize    = 128;
     this.aes.FeedbackSize = 128;
     this.aes.Mode         = System.Security.Cryptography.CipherMode.CBC;
     this.aes.Padding      = System.Security.Cryptography.PaddingMode.ISO10126;
     this.aes.Key          = new byte[256 / 8];
     this.aes.IV           = new byte[128 / 8];
     this.encryptor        = aes.CreateEncryptor();
     this.decryptor        = aes.CreateDecryptor();
 }
Ejemplo n.º 2
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.º 3
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);
        }
        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.º 5
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);
            }
        }
        /// <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.º 7
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.º 8
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.º 9
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();
            }
        }
Ejemplo n.º 10
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.º 11
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);
        }
        /// <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.º 13
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);
        }
Ejemplo n.º 14
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.º 15
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());
                        }
                }
            }
        }