예제 #1
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="input">密文字节数组</param>
        /// <param name="key">密钥(32位)</param>
        /// <returns>返回解密后的字符串</returns>
        public static string DecryptByAES(string input, string key)
        {
            byte[] inputBytes = HexStringToByteArray(input);
            byte[] keyBytes   = Encoding.UTF8.GetBytes(key.Substring(0, 32));
            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            {
                aesAlg.Key = keyBytes;
                aesAlg.IV  = Encoding.UTF8.GetBytes(AES_IV.Substring(0, 16));

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream(inputBytes))
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srEncrypt = new StreamReader(csEncrypt))
                        {
                            return(srEncrypt.ReadToEnd());
                        }
                    }
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Aes解密
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="key">aes密钥,长度必须32位</param>
        /// <param name="model">运算模式</param>
        /// <param name="padding">填充模式</param>
        /// <param name="encoding">编码类型</param>
        /// <returns>解密后的字符串</returns>
        public static string DecryptAes(string source, string key, CipherMode model = CipherMode.ECB,
                                        PaddingMode padding = PaddingMode.PKCS7, Encoding encoding = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }

            using (AesCryptoServiceProvider aesProvIder = new AesCryptoServiceProvider())
            {
                aesProvIder.Key     = GetAesKey(key, encoding);
                aesProvIder.Mode    = model;
                aesProvIder.Padding = padding;
                using (ICryptoTransform cryptoTransform = aesProvIder.CreateDecryptor())
                {
                    byte[] inputBuffers = Convert.FromBase64String(source);
                    byte[] results      = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                    aesProvIder.Clear();
                    return(encoding.GetString(results));
                }
            }
        }
예제 #3
0
        /// <summary>
        /// AES decryption
        /// </summary>
        static string Decrypt(string text)
        {
            // AesCryptoServiceProvider
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            aes.BlockSize = 128;
            aes.KeySize   = 128;
            aes.IV        = Encoding.UTF8.GetBytes(AesIV);
            aes.Key       = Encoding.UTF8.GetBytes(AesKey);
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;

            // Convert Base64 strings to byte array
            byte[] src = System.Convert.FromBase64String(text);

            // decryption
            using (ICryptoTransform decrypt = aes.CreateDecryptor())
            {
                byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
                return(Encoding.Unicode.GetString(dest));
            }
        }
예제 #4
0
        /// <summary>
        /// Encrypt a file with AES
        /// </summary>
        /// <param name="plainFilePath">Full path of the encrypted file</param>
        /// <param name="encryptedFilePath">Full path of the file to be decrypted</param>
        /// <param name="key">AES key</param>
        /// <param name="iv">AES IV</param>
        public static void DecryptFile(string plainFilePath, string encryptedFilePath, byte[] key, byte[] iv)
        {
            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.KeySize = 128;
                aes.Key     = key;
                aes.IV      = iv;
                aes.Padding = PaddingMode.PKCS7;
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                using (FileStream plain = File.Open(plainFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    using (FileStream encrypted = File.Open(encryptedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (CryptoStream cs = new CryptoStream(plain, decryptor, CryptoStreamMode.Write))
                        {
                            encrypted.CopyTo(cs);
                        }
                    }
                }
            }
        }
예제 #5
0
        public void Receive(byte[] encryptedMessage, byte[] iv)
        {
            using (Aes aes = new AesCryptoServiceProvider())
            {
                aes.Key = bobKey;
                aes.IV  = iv;
                // Decrypt the message
                using (MemoryStream plaintext = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(plaintext, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(encryptedMessage, 0, encryptedMessage.Length);
                        cs.Close();
                        string message         = Encoding.UTF8.GetString(plaintext.ToArray());
                        string StringEncrypted = BitConverter.ToString(encryptedMessage);

                        // Console.WriteLine(StringEncrypted);
                        // Console.WriteLine(message);
                    }
                }
            }
        }
예제 #6
0
        /* goodG2B() - use goodsource and badsink */
        private void GoodG2B()
        {
            string password;

            password = ""; /* init password */
            /* retrieve the password */
            try
            {
                password = Encoding.UTF8.GetString(File.ReadAllBytes("../../../common/strong_password_file.txt"));
            }
            catch (IOException exceptIO)
            {
                IO.Logger.Log(NLog.LogLevel.Warn, "Error with file reading", exceptIO);
            }
            /* FIX: password is decrypted before being passed on */
            {
                using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
                {
                    aesAlg.Key = Encoding.UTF8.GetBytes("ABCDEFGHABCDEFGH");
                    aesAlg.IV  = new byte[16];
                    // Create a decryptor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    // Create the streams used for decryption.
                    using (MemoryStream msDecrypt = new MemoryStream(File.ReadAllBytes("../../../common/strong_password_file.txt")))
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                            {
                                // Read the decrypted bytes from the decrypting stream
                                // and place them in a string.
                                password = srDecrypt.ReadToEnd();
                            }
                        }
                    }
                }
            }
            CWE256_Unprotected_Storage_of_Credentials__basic_52b.GoodG2BSink(password);
        }
예제 #7
0
        private static byte[] AesDecrypt(byte[] secureBytes, uint offset, uint count, byte[] saltedPassword, byte[] saltedIV)
        {
            byte[] decryptedBytes = null;

            using (var provider = new AesCryptoServiceProvider())
            {
                using (var memory = new MemoryStream())
                {
                    using (var decryptor = provider.CreateDecryptor(saltedPassword, saltedIV))
                    {
                        using (var writer = new CryptoStream(memory, decryptor, CryptoStreamMode.Write))
                        {
                            writer.Write(secureBytes, (int)offset, (int)count);
                            writer.FlushFinalBlock();
                        }
                        decryptedBytes = memory.ToArray();
                    }
                }
            }

            return(decryptedBytes);
        }
예제 #8
0
        public static void decryptFile(string filePath, AesCryptoServiceProvider aes)
        {
            //create new file name
            string origname = filePath.Remove(filePath.Length - 4);
            var    buffer   = new byte[65536];

            using (var streamIn = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                using (var streamOut = new FileStream(origname, FileMode.Create))
                    using (var decrypt = new CryptoStream(streamOut, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        int bytesRead;
                        do
                        {
                            bytesRead = streamIn.Read(buffer, 0, buffer.Length);
                            if (bytesRead != 0)
                            {
                                decrypt.Write(buffer, 0, bytesRead);
                            }
                        }while (bytesRead != 0);
                    }
            File.Delete(filePath);
        }
예제 #9
0
        static byte[] Decrypt(byte[] encryptedString)
        {
            using (var provider = new AesCryptoServiceProvider())
            {
                provider.Key = CryptoKey;
                using (var ms = new MemoryStream(encryptedString))
                {
                    // Read the first 16 bytes which is the IV.
                    byte[] iv = new byte[16];
                    ms.Read(iv, 0, 16);
                    provider.IV = iv;

                    using (var decryptor = provider.CreateDecryptor())
                    {
                        using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                        {
                            return(cs.ReadAllBytes());
                        }
                    }
                }
            }
        }
예제 #10
0
        private byte[] Decrypt(byte[] data,
            byte[] key,
            byte[] iv)
        {
#if DISABLE_ENCRYPTION
     			return data;
#else
            using (var aes = new AesCryptoServiceProvider()) // new AesCryptoServiceProvider() faster than Aes.Create()
            {
                byte[] decryptedData; // decrypted data
                try
                {
                    using (var memory = new MemoryStream(data))
                    {
                        using (var decryptor = new CryptoStream(memory, aes.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                        {
                            using (var tempMemory = new MemoryStream())
                            {
                                var buffer = new byte[1024];
                                int readBytes;
                                while ((readBytes = decryptor.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    tempMemory.Write(buffer, 0, readBytes);
                                }

                                decryptedData = tempMemory.ToArray();
                            }
                        }
                    }
                }
                catch
                {
                    decryptedData = null;
                }

                return decryptedData;
            }
#endif
        }
예제 #11
0
        public static void Decrypt(string path)
        {
            string archPath = TargetDirectory + "\\archive" + path.Substring(path.LastIndexOf('\\'));
            string dePath   = TargetDirectory + path.Substring(path.LastIndexOf('\\'));

            byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
            byte[] iv  = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

            using (FileStream fsFileIn = File.OpenRead(dePath))
                using (FileStream fsFileOut = new FileStream(archPath, FileMode.Create))
                    using (AesCryptoServiceProvider cryptAlgorithm = new AesCryptoServiceProvider())
                    {
                        cryptAlgorithm.Key = key;
                        cryptAlgorithm.IV  = iv;
                        using (CryptoStream csEncrypt = new CryptoStream(fsFileIn, cryptAlgorithm.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            csEncrypt.CopyTo(fsFileOut);
                        }
                    }

            delete(dePath);
        }
예제 #12
0
    //<Snippet3>
    public void Receive(byte[] iv, byte[] encryptedSessionKey, byte[] encryptedMessage)
    {
        using (Aes aes = new AesCryptoServiceProvider())
        {
            aes.IV = iv;

            // Decrypt the session key
            RSAOAEPKeyExchangeDeformatter keyDeformatter = new RSAOAEPKeyExchangeDeformatter(rsaKey);
            aes.Key = keyDeformatter.DecryptKeyExchange(encryptedSessionKey);

            // Decrypt the message
            using (MemoryStream plaintext = new MemoryStream())
                using (CryptoStream cs = new CryptoStream(plaintext, aes.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(encryptedMessage, 0, encryptedMessage.Length);
                    cs.Close();

                    string message = Encoding.UTF8.GetString(plaintext.ToArray());
                    Console.WriteLine(message);
                }
        }
    }
예제 #13
0
        public async Task JackRecvDataAsync(byte[] encryptedData)
        {
            Console.WriteLine("Bob recevies encrypted data");
            byte[] rawData = null;

            var aes = new AesCryptoServiceProvider();

            int nBytes = aes.BlockSize >> 3;

            byte[] iv = new byte[nBytes];

            for (int i = 0; i < iv.Length; i++)
            {
                iv[i] = encryptedData[i];
            }

            using (var bobAlgorithm = new ECDiffieHellmanCng(jackKey))
                using (CngKey rosePubKey = CngKey.Import(rosePubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
                {
                    byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(rosePubKey);
                    Console.WriteLine($"The Symmetric key is {Convert.ToBase64String(symmKey)}");

                    aes.Key = symmKey;
                    aes.IV  = iv;

                    using (ICryptoTransform decryptor = aes.CreateDecryptor())
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                            {
                                await cs.WriteAsync(encryptedData, nBytes, encryptedData.Length - nBytes);
                            }
                            rawData = ms.ToArray();

                            Console.WriteLine($"Decrypts message is :{Encoding.UTF8.GetString(rawData)}");
                        }
                    aes.Clear();
                }
        }
예제 #14
0
        public override byte[] Decryption(byte[] dataToDecrypt, byte[] key, byte[] iv)
        {
            using (var aes = new AesCryptoServiceProvider())
            {
                aes.Mode    = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                aes.Key = key;
                aes.IV  = iv;

                using (var memoryStream = new MemoryStream())
                {
                    var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(),
                                                        CryptoStreamMode.Write);

                    cryptoStream.Write(dataToDecrypt, 0, dataToDecrypt.Length);
                    cryptoStream.FlushFinalBlock();

                    return(memoryStream.ToArray());
                }
            }
        }
예제 #15
0
        /// <summary>
        /// Decrypt xml using encryption key and pack content with encryption key id, oid and iv
        /// </summary>
        /// <param name="element">Source xml to be decrypted</param>
        /// <param name="key">Encryption key</param>
        public static void DecryptXml(this XmlElement element, byte[] key)
        {
            using (var aescp = new AesCryptoServiceProvider {
                Mode = CipherMode.CBC, KeySize = 256
            })
            {
                var sData = element.InnerXml;
                var eData = Convert.FromBase64String(sData);

                var sDaed = new SdaEncryptedData(eData);

                var iv = sDaed.IV;

                var decryptor = aescp.CreateDecryptor(key, iv);

                eData = sDaed.EncryptedContent;

                var data = decryptor.TransformFinalBlock(eData, 0, eData.Length);

                element.InnerXml = Encoding.UTF8.GetString(data);
            }
        }
예제 #16
0
파일: Program.cs 프로젝트: zilo312/aa
        private static void BobReceivesData(byte[] encryptedData)
        {
            Console.WriteLine("Bob receives encrpyted data");
            byte[] rawData = null;

            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            int nBytes = aes.BlockSize >> 3;

            byte[] iv = new byte[nBytes];
            for (int i = 0; i < iv.Length; i++)
            {
                iv[i] = encryptedData[i];
            }

            ECDiffieHellmanCng bobAlgorithm = new ECDiffieHellmanCng(bobKey);

            using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
            {
                byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey);
                Console.WriteLine("Bob creates this key with Alices public key information: {0}", Convert.ToBase64String(symmKey));

                aes.Key = symmKey;
                aes.IV  = iv;

                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                    using (MemoryStream ms = new MemoryStream())
                    {
                        CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write);
                        cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes);
                        cs.Close();

                        rawData = ms.ToArray();

                        Console.WriteLine("Bob decrypts message to: {0}", Encoding.UTF8.GetString(rawData));
                    }
                aes.Clear();
            }
        }
예제 #17
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="src">解密数据</param>
        /// <param name="aesKey">密钥字符串(需要和加密时相同)</param>
        /// <returns></returns>
        public static byte[] AesDecrypt(byte[] src, byte[] aesKey)
        {
            try
            {
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
                aes.BlockSize = 128;
                aes.KeySize   = 128;
                aes.Key       = aesKey;
                aes.Mode      = CipherMode.ECB;
                aes.Padding   = PaddingMode.PKCS7;

                using (ICryptoTransform decrypt = aes.CreateDecryptor())
                {
                    byte[] dest = decrypt.TransformFinalBlock(src, 0, src.Length);
                    return(dest);
                }
            }
            catch
            {
                throw;
            }
        }
예제 #18
0
        public byte[] Decrypt(byte[] cipher, byte[] key, byte[] iv, string cipherType)
        {
            try
            {
                switch (cipherType)
                {
                case "aes-128-cbc":
                {
                    using var aes = new AesCryptoServiceProvider
                          {
                              BlockSize = _config.SymmetricEncrypterBlockSize,
                              KeySize   = _config.SymmetricEncrypterKeySize,
                              Padding   = PaddingMode.PKCS7,
                              Key       = key,
                              IV        = iv
                          };
                    var decryptor = aes.CreateDecryptor(key, aes.IV);
                    return(Execute(decryptor, cipher));
                }

                case "aes-128-ctr":
                {
                    using var outputEncryptedStream = new MemoryStream(cipher);
                    using var outputDecryptedStream = new MemoryStream();
                    AesCtr(key, iv, outputEncryptedStream, outputDecryptedStream);
                    outputDecryptedStream.Position = 0;
                    return(outputDecryptedStream.ToArray());
                }

                default:
                    throw new Exception($"Unsupported cipherType: {cipherType}");
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error during encryption", ex);
                return(null);
            }
        }
        /// <summary>
        /// Decrypt a string using the AES algorithm.
        /// </summary>
        /// <param name="dataToDecrypt"></param>
        /// <returns></returns>
        public string Decrypt(string dataToDecrypt)
        {
            byte[] input = Convert.FromBase64String(dataToDecrypt);

            string decrypted = string.Empty;

            using (var memoryStream = new MemoryStream(input))
            {
                var initializationVector = new byte[InitializationVectorSize];

                memoryStream.Read(initializationVector, 0, initializationVector.Length);

                using AesCryptoServiceProvider cryptoServiceProvider = CreateCryptographyProvider();
                using ICryptoTransform cryptoTransform = cryptoServiceProvider.CreateDecryptor(_key, initializationVector);
                using var crypto = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read);
                using var reader = new StreamReader(crypto);

                decrypted = reader.ReadToEnd().Trim('\0');
            }

            return(decrypted);
        }
예제 #20
0
        public byte[] Decrypt(byte[] cipherText, byte[] iv)
        {
            // TODO do checks on args

            byte[] plainText;

            _provider.IV = iv;
            ICryptoTransform decryptor = _provider.CreateDecryptor();

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (BinaryReader brDecrypt = new BinaryReader(csDecrypt))
                    {
                        plainText = brDecrypt.ReadBytes(cipherText.Length);
                    }
                }
            }

            return(plainText);
        }
예제 #21
0
        /// <summary>
        ///     Decrypts a cipher-text that has been encrypted with AES256 Encryption
        /// </summary>
        /// <param name="encryptedText"></param>
        /// <returns></returns>
        public static string DeCryptString(string encryptedText)
        {
            string       plainText;
            const string key = ("abcdefghijklmnopqrstuvwxyz123456");
            const string IV  = ("1234567890123456");

            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
            var    aes            = new AesCryptoServiceProvider
            {
                BlockSize = 128,
                KeySize   = 256,
                Key       = Encoding.ASCII.GetBytes(key),
                IV        = Encoding.ASCII.GetBytes(IV),
                Padding   = PaddingMode.PKCS7,
                Mode      = CipherMode.CBC
            };
            ICryptoTransform crypto = aes.CreateDecryptor(aes.Key, aes.IV);

            byte[] plainTextBytes = crypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
            plainText = Encoding.ASCII.GetString(plainTextBytes);
            return(plainText);
        }
        /* goodB2G() - use badsource and goodsink */
        public static void GoodB2GSink(string[] passwordArray)
        {
            string password = passwordArray[2];

            /* FIX: password is decrypted before being used as a database password */
            {
                using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
                {
                    aesAlg.Key = Encoding.UTF8.GetBytes("ABCDEFGHABCDEFGH");
                    aesAlg.IV  = new byte[16];
                    // Create a decryptor to perform the stream transform.
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    // Create the streams used for decryption.
                    using (MemoryStream msDecrypt = new MemoryStream(File.ReadAllBytes("../../../common/strong_password_file.txt")))
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                            {
                                // Read the decrypted bytes from the decrypting stream
                                // and place them in a string.
                                password = srDecrypt.ReadToEnd();
                            }
                        }
                    }
                }
            }
            using (SqlConnection dBConnection = new SqlConnection(@"Data Source=(local);Initial Catalog=CWE256;User ID=sa;Password="******"Error with database connection", exceptSql);
                }
            }
        }
예제 #23
0
    static void Main(string[] args)
    {
        // Get bytes of AES Key, read contents
        var aesKeyBytes   = Convert.FromBase64String(AES_Key);
        var contentsBytes = File.ReadAllBytes("profile.sii");

        // Create IV & Cipher test byte arrays
        var iv         = new byte[0x10];
        var cipherText = new byte[contentsBytes.Length - 0x38];

        // Copy contents bytes to cipherText & IV arrays
        Array.Copy(contentsBytes, 56, cipherText, 0, cipherText.Length);
        Array.Copy(contentsBytes, 36, iv, 0, iv.Length);
        // Create AES Crypto Service Provider with our Key & Vector.
        var cryptoServiceProvider = new AesCryptoServiceProvider
        {
            Mode      = CipherMode.CBC,
            Padding   = PaddingMode.None,
            KeySize   = 0x80,
            BlockSize = 0x80,
            Key       = aesKeyBytes,
            IV        = iv
        };
        // Create decryptor and get plain text of encrypted contents.
        var decryptor = cryptoServiceProvider.CreateDecryptor();
        var plainText = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);

        string decompressedContents;

        // Load into Memory Stream and skip the first 2 bytes.
        // Use a Deflate stream to decompress the contents
        // Read the deflated contents via our StreamReader
        using (var memStream = new MemoryStream(plainText, 2, plainText.Length - 2))
            using (var iis = new DeflateStream(memStream, CompressionMode.Decompress))
                using (var streamReader = new StreamReader(iis))
                {
                    decompressedContents = streamReader.ReadToEnd();
                }
    }
예제 #24
0
        private static ICryptoTransform GetTransform(string password, bool encrypt)
        {
            // Create an instance of the AES class.
            var provider = new AesCryptoServiceProvider();
            // Calculate salt to make it harder to guess key by using a dictionary attack.
            var salt = SaltFromPassword(password);
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            // Rfc2898DeriveBytes generator based on HMACSHA1 by default.
            // Ability to specify HMAC algorithm is available since .NET 4.7.2
            var secretKey = new Rfc2898DeriveBytes(password, salt, 10);
            // Create a cryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            var key     = secretKey.GetBytes(provider.KeySize / 8);
            var iv      = secretKey.GetBytes(provider.BlockSize / 8);
            var cryptor = encrypt
                                ? provider.CreateEncryptor(key, iv)
                                : provider.CreateDecryptor(key, iv);

            return(cryptor);
        }
예제 #25
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="content">待加密内容</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string DecryptByAES(string content, string key)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

            byte[] inputByteArray = Convert.FromBase64String(content);
            aes.Key = Encoding.GetEncoding("UTF-8").GetBytes(key);                  //在AES的情况下,密钥是32位
            aes.IV  = Encoding.GetEncoding("UTF-8").GetBytes(key.Substring(0, 16)); //在AES的情况下,该大小为16字节
            MemoryStream ms = new MemoryStream();

            try
            {
                CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                //当提供的密钥与加密时的密钥不一致会导致报错
                cs.FlushFinalBlock();
            }
            catch (Exception ex)
            {
                throw new Exception("密钥错误!");
            }
            return(Encoding.GetEncoding("UTF-8").GetString(ms.ToArray()));
        }
예제 #26
0
        /// <summary>
        /// 以指定的秘钥和编码方式对字符串进行AES解密。
        /// </summary>
        /// <param name="key">解密使用的字符串秘钥。</param>
        /// <param name="value">需要解密的字符串。</param>
        /// <param name="encoding">字符串使用的编码方式。</param>
        /// <returns>解密后的字符串。</returns>
        /// <exception cref="ArgumentException">参数key为空时将抛出该异常。</exception>
        /// <exception cref="ArgumentNullException">参数encoding为null时将抛出该异常。</exception>
        public static string AesDecrypt(string key, string value, Encoding encoding)
        {
            if (string.IsNullOrEmpty(key))
            {
                return(string.Empty);
            }
            byte[] keyBuffer = Encryption.ComputeKey(key, 16, encoding);
            string result;

            using (Aes provider = new AesCryptoServiceProvider()) {
                using (MemoryStream memory = new MemoryStream()) {
                    using (ICryptoTransform transform = provider.CreateDecryptor(keyBuffer, keyBuffer)) {
                        using (CryptoStream crypto = new CryptoStream(memory, transform, CryptoStreamMode.Write)) {
                            byte[] buffer = Convert.FromBase64String(value);
                            crypto.Write(buffer, 0, buffer.Length);
                        }
                    }
                    result = encoding.GetString(memory.ToArray());
                }
            }
            return(result);
        }
예제 #27
0
        // Reference:
        // https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.aescryptoserviceprovider?view=netstandard-2.0
        /// <summary>
        /// Decrypt data encrypted with AES.
        /// </summary>
        /// <param name="encryptedData"> data encrypted with AES </param>
        /// <param name="key"> key used for AES encryption </param>
        /// <param name="IV"> IV used for AES encryption </param>
        /// <returns> the string of decrypted data </returns>
        public static string DecryptAES(byte[] encryptedData, byte[] key, byte[] IV)
        {
            string decryptedData;

            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                // Create AES decryptor using the given key and IV.
                ICryptoTransform decryptor = aes.CreateDecryptor(key, IV);

                // Pass the encrypted data to the memory stream.
                MemoryStream ms = new MemoryStream(encryptedData);
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader sr = new StreamReader(cs))
                    {
                        // Read the decrypted data as string from the stream reader.
                        decryptedData = sr.ReadToEnd();
                    }
                }
            }
            return(decryptedData);
        }
예제 #28
0
        public byte[] Descriptografar(byte[] dadosParaDescriptografar, byte[] chave, byte[] iv)
        {
            using (var aes = new AesCryptoServiceProvider())
            {
                aes.Mode    = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.Key     = chave;
                aes.IV      = iv;

                using (var memoryStream = new MemoryStream())
                {
                    var cryptoStream = new CryptoStream(memoryStream,
                                                        aes.CreateDecryptor(),
                                                        CryptoStreamMode.Write);

                    cryptoStream.Write(dadosParaDescriptografar, 0, dadosParaDescriptografar.Length);
                    cryptoStream.FlushFinalBlock();

                    return(memoryStream.ToArray());
                }
            }
        }
예제 #29
0
        ////////////////////////////////////////////////////////////////////////////////
        // Added compatibility for newer versions of windows
        // https://github.com/rapid7/metasploit-framework/blob/master/modules/post/windows/gather/hashdump.rb
        ////////////////////////////////////////////////////////////////////////////////
        private static Byte[] DecryptSingleHashAES(Byte[] encryptedHash, Int32 rid, Byte[] hBootKey, Byte[] hashType, Byte[] blankHash)
        {
            if (encryptedHash.Length < 40)
            {
                return(blankHash);
            }

            Int32[][] desKeys = ConvertRidToDesKey(rid);
            Byte[]    aesDecryptedHash;
            using (Aes aes = new AesCryptoServiceProvider())
            {
                aes.Key     = hBootKey.Take(16).ToArray();
                aes.Padding = PaddingMode.Zeros;
                aes.IV      = encryptedHash.Skip(8).Take(16).ToArray();
                aes.Mode    = CipherMode.CBC;
                ICryptoTransform decryptor = aes.CreateDecryptor();
                aesDecryptedHash = decryptor.TransformFinalBlock(encryptedHash, 24, 16);
            }
            Byte[] desDecryptedHash1 = DecryptDes(aesDecryptedHash.Take(8).ToArray(), desKeys[0]);
            Byte[] desDecryptedHash2 = DecryptDes(aesDecryptedHash.Skip(8).Take(8).ToArray(), desKeys[1]);
            return(Combine.combine(desDecryptedHash1, desDecryptedHash2));
        }
예제 #30
0
        public byte[] Decrypt(byte[] encrypted,
                              int workFactor,
                              byte[] salt)
        {
            if (encrypted == null)
            {
                throw new ArgumentNullException("encrypted", "Cannot be null");
            }

            if (workFactor < MIN_VALID_WORK_FACTOR || MAX_VALID_WORK_FACTOR < workFactor)
            {
                throw new ArgumentOutOfRangeException("workFactor",
                                                      workFactor,
                                                      string.Format("workFactor value must be between {0} and {1} inclusive.",
                                                                    MIN_VALID_WORK_FACTOR,
                                                                    MAX_VALID_WORK_FACTOR));
            }

            if (salt == null)
            {
                throw new ArgumentNullException("salt", "Cannot be null");
            }

            using (var encryptedMemoryStream = new MemoryStream(encrypted))
                using (var aes = new AesCryptoServiceProvider())
                {
                    InitAesKeyAndIv(aes, workFactor, salt);
                    ICryptoTransform decryptor = aes.CreateDecryptor();

                    using (var cs = new CryptoStream(encryptedMemoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        var unencryptedMemoryStream = new MemoryStream();

                        cs.CopyTo(unencryptedMemoryStream);

                        return(unencryptedMemoryStream.ToArray());
                    }
                }
        }
예제 #31
0
		/// <summary>
		/// Decrypt incoming message
		/// </summary>
		public bool Decrypt(NetIncomingMessage msg)
		{
#if !IOS && !__ANDROID__
			try
			{
				// nested usings are fun!
				using (AesCryptoServiceProvider aesCryptoServiceProvider = new AesCryptoServiceProvider { KeySize = m_bitSize, Mode = CipherMode.CBC })
				{
					using (ICryptoTransform cryptoTransform = aesCryptoServiceProvider.CreateDecryptor(m_key, m_iv))
					{
						using (MemoryStream memoryStream = new MemoryStream())
						{
							using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform,
																			 CryptoStreamMode.Write))
							{
								cryptoStream.Write(msg.m_data, 0, msg.m_data.Length);
							}
							msg.m_data = memoryStream.ToArray();
						}
					}
				}

			}
			catch
			{
				return false;
			}
			return true;
#else
			return false;
#endif
		}