Ejemplo n.º 1
0
        public void DecryptStream(Stream sourcestream, Stream deststream, string key)
        {
            byte[] _key = new byte[32];
            byte[] _IV  = new byte[16];

            byte[] myKey = Encoding.ASCII.GetBytes(key);

            for (int i = 0; i < _key.Length; i++)
            {
                _key[i] = 0;
            }
            for (int i = 0; (i < _key.Length) && (i < myKey.Length); i++)
            {
                _key[i] = myKey[i];
            }
            for (int i = 0; (i < _key.Length) && (i < _IV.Length); i++)
            {
                _IV[i] = _key[i];
            }
            _IV.Reverse();

            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
            aes.IV  = _IV;
            aes.Key = _key;

            var decStream = new CryptoStream(sourcestream, aes.CreateDecryptor(), CryptoStreamMode.Read);

            deststream.SetLength(0);
            decStream.CopyTo(deststream);
        }
Ejemplo n.º 2
0
                /// <summary>
                /// Decrypt a message
                /// </summary>
                /// <param name="messageToDecrypt">The message to be decrypted</param>
                /// <param name="secretKey">The 32 characters long secret key to be used on the encryption</param>
                /// <param name="secretVector">The 16 characters long secret vector to be used on the encryption</param>
                /// <returns>The decrypted message</returns>
                public static String Decrypt(String messageToDecrypt, String secretKey, String secretVector)
                {
                    String messageDecrypted = null;

                    using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
                    {
                        aes.Key = System.Text.Encoding.UTF8.GetBytes(secretKey);
                        aes.IV  = System.Text.Encoding.UTF8.GetBytes(secretVector);

                        ICryptoTransform iCryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV);

                        using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(messageToDecrypt)))
                        {
                            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, iCryptoTransform, CryptoStreamMode.Read))
                            {
                                using (StreamReader streamReader = new StreamReader(cryptoStream))
                                {
                                    messageDecrypted = streamReader.ReadToEnd();
                                }
                            }
                        }
                    }

                    return(messageDecrypted);
                }
Ejemplo n.º 3
0
        private static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an Aes object
            // with the specified key and IV.
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create a decrytor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(cipherText))
                {
                    using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(
                               msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                    {
                        using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
                        {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return(plaintext);
        }
Ejemplo n.º 4
0
        private static string DecryptStringFromBytesAes(byte[] cipherText, byte[] key, byte[] iv)
        {
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }

            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }

            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Padding = PaddingMode.None;
                aes.Mode    = CipherMode.CBC;
                aes.Key     = key;
                aes.IV      = iv;

                using (var output = new MemoryStream())
                    using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
                        using (var ms = new MemoryStream(cipherText))
                            using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                            {
                                cs.CopyTo(output);

                                return(output.ToArray().ToHexString());
                            }
            }
        }
        protected virtual ICryptoTransform CreateTransform(System.Security.Cryptography.Aes aes, byte[] key, byte[] iv, AesMode mode)
        {
            if (aes == null)
            {
                throw new ArgumentNullException(nameof(aes));
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (iv == null)
            {
                throw new ArgumentNullException(nameof(iv));
            }

            switch (mode)
            {
            case AesMode.Decrypt:
                return(aes.CreateDecryptor(key, iv));

            case AesMode.Encrypt:
                return(aes.CreateEncryptor(key, iv));

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 6
0
        public override void init(int mode, byte[] key, byte[] iv)
        {
            if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE) throw new ArgumentOutOfRangeException();
            ms = new PipedMemoryStream();
            aesm = AesManaged.Create();
            aesm.BlockSize = blockSize * 8;
            aesm.Padding = PaddingMode.None;
            ICryptoTransform ict;
            if (key.Length > blockSize)
            {
                byte[] tmp = new byte[blockSize];
                Array.Copy(key, 0, tmp, 0, tmp.Length);
                key = tmp;
            }
            if (iv.Length > ivSize)
            {
                byte[] tmp = new byte[ivSize];
                Array.Copy(iv, 0, tmp, 0, tmp.Length);
                iv = tmp;
            }
            if (mode == ENCRYPT_MODE)
            {
                ict = aesm.CreateEncryptor(key, iv);
            }
            else
            {
                ict = aesm.CreateDecryptor(key, iv);
            }

            cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
        }
Ejemplo n.º 7
0
        public byte[] Decrypt(byte[] buffer)
        {
#if WINDOWS_STORE
            SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey aes    = provider.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(this.key));
            IBuffer          result = CryptographicEngine.Decrypt(aes, CryptographicBuffer.CreateFromByteArray(buffer), CryptographicBuffer.CreateFromByteArray(this.iv));

            byte[] decrypted;
            CryptographicBuffer.CopyToByteArray(result, out decrypted);

            return(decrypted);
#else
            using (System.Security.Cryptography.Aes aes = AesManaged.Create())
            {
                aes.KeySize = 256;
                aes.Mode    = CipherMode.CBC;

                aes.IV  = iv;
                aes.Key = key;
                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                {
                    return(decryptor.TransformFinalBlock(buffer, 0, buffer.Length));
                }
            }
#endif
        }
Ejemplo n.º 8
0
        internal int ProcessDecryption(crypto.Aes cipher, CommandLine commandLine)
        {
            Stream inputStream  = CreateInputStream(commandLine);
            Stream outputStream = CreateOutputStream(commandLine);

            if (commandLine.SkipBytes > 0)
            {
                if (commandLine.SkipBytes >= inputStream.Length)
                {
                    return(0);
                }

                if (inputStream.CanSeek)
                {
                    inputStream.Position = commandLine.SkipBytes;
                }
                else
                {
                    for (int i = 0; i < commandLine.SkipBytes; i++)
                    {
                        inputStream.ReadByte();
                    }
                }
            }

            var versionBytes = new byte[2];

            inputStream.Read(versionBytes, 0, versionBytes.Length);
            ushort version = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(versionBytes, 0));

            if (version != Constants.FormatVersion)
            {
                Console.WriteLine($"Unsupported version, expected {Constants.FormatVersion}, found {version}.");
                return(1);
            }

            // reads 16 bytes of IV
            var iv = new byte[cipher.BlockSize / 8]; // cipher.BlockSize / 8 = 16 since block size is always 128 for AES algorithm

            inputStream.Read(iv, 0, iv.Length);

            // reads 2 bytes of salt size (in host order)
            byte[] saltLengthBytes = new byte[sizeof(ushort)];
            inputStream.Read(saltLengthBytes, 0, saltLengthBytes.Length);
            int saltLength = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(saltLengthBytes, 0));

            // reads n bytes of salt
            byte[] salt = new byte[saltLength];
            inputStream.Read(salt, 0, salt.Length);

            var key = new Rfc2898DeriveBytes(commandLine.Password, salt, commandLine.KeyIterations);

            cipher.IV  = iv;
            cipher.Key = key.GetBytes(cipher.KeySize / 8);

            using (Stream cryptoStream = new CryptoStream(inputStream, cipher.CreateDecryptor(), CryptoStreamMode.Read))
                cryptoStream.CopyTo(outputStream);

            return(0);
        }
Ejemplo n.º 9
0
 public AES(byte[] key)
 {
     rsa = new AesManaged();
     rsa.GenerateKey();
     rsa.GenerateIV();
     _decoder = rsa.CreateDecryptor();
     _encoder = rsa.CreateEncryptor();
 }
Ejemplo n.º 10
0
        private static string Decrypt(byte[] cipherText, byte[] key, byte[] iv)
        {
            var decryptor = Aes.CreateDecryptor(key, iv);

            using (var ms = new MemoryStream(cipherText))
                using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    using (var sr = new StreamReader(cs))
                        return(sr.ReadToEnd());
        }
Ejemplo n.º 11
0
        /**********************************************************************************************************
        *	UserData LoadUserData(string MasterPassword)
        *       Purpose:	Loads data, if it exists, from the disk. The data is encrypted using AES using the
        *					master password's hash as the secret key.
        **********************************************************************************************************/
        private UserData LoadUserData(string MasterPassword)
        {
            // Need 128 bits password for the encryption key.
            ApplicationEntry self     = new ApplicationEntry("MasterPass", 128 / sizeof(char) / 8, 0, true, true, true, false);
            HashedPassword   fileName = self.GeneratePassword(MasterPassword);
            HashedPassword   aesKey   = self.GeneratePassword(MasterPassword);
            HashedPassword   aesIV    = self.GeneratePassword(MasterPassword);

            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();

            // Even if aes is broken the master password is unrecoverable.
            aes.Key = Encoding.Unicode.GetBytes(aesKey.Password);
            aes.IV  = Encoding.Unicode.GetBytes(aesIV.Password);

            aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            ICryptoTransform decryptor = aes.CreateDecryptor();

            UserData loadedData = null;

            // If there is no data don't load it.
            if (File.Exists(fileName.Password + ".pass") == false)
            {
                return(loadedData);
            }

            // Open the file
            using (FileStream outputStream = new FileStream(fileName.Password + ".pass", FileMode.Open))
            {
                // Use a safe to file encryption method
                using (CryptoStream csDecrypt = new CryptoStream(outputStream, decryptor, CryptoStreamMode.Read))
                {
                    // Convert the object to a byte array
                    using (MemoryStream objectStream = new MemoryStream())
                    {
                        byte[] buffer    = new byte[1024];
                        int    bytesRead = csDecrypt.Read(buffer, 0, buffer.Length);

                        while (bytesRead > 0)
                        {
                            objectStream.Write(buffer, 0, bytesRead);
                            bytesRead = csDecrypt.Read(buffer, 0, buffer.Length);
                        }

                        csDecrypt.Flush();

                        objectStream.Position = 0;

                        IFormatter formatter = new BinaryFormatter();
                        loadedData = formatter.Deserialize(objectStream) as UserData;
                    }
                }
            }

            return(loadedData);
        }
Ejemplo n.º 12
0
        public SimpleAes(byte[] key)
        {
            aes = Aes.Create();
            aes.GenerateIV();

            aes.Key = key;

            encryptor = aes.CreateEncryptor(key, aes.IV);
            decryptor = aes.CreateDecryptor(key, aes.IV);
        }
Ejemplo n.º 13
0
        static DBCrypto()
        {
            aesAlg = Aes.Create();
            aesAlg.Key = AES_CBC_KEY;
            aesAlg.IV = AES_CBC_IV;
            aesAlg.Padding = PaddingMode.PKCS7;

            decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// AES加解密
        /// </summary>
        /// <param name="aes"></param>
        /// <param name="forEncryption">是否加密(false为解密)</param>
        /// <param name="data">待加解密的数据</param>
        /// <param name="key">加解密密钥,为空则使用实体属性Key</param>
        /// <param name="mode">加解密模式,为空则使用实体属性Mode</param>
        /// <param name="padding">填充算法,为空则使用实体属性Padding</param>
        /// <returns>加解密后数据</returns>
        public static byte[] Crypto(this System.Security.Cryptography.Aes aes,
                                    bool forEncryption, byte[] data, byte[] key = null, CipherMode?mode = null, PaddingMode?padding = null)
        {
            aes.Key     = key ?? aes.Key;
            aes.Mode    = mode ?? aes.Mode;
            aes.Padding = padding ?? aes.Padding;
            var cryptor = forEncryption ? aes.CreateEncryptor() : aes.CreateDecryptor();

            return(cryptor.TransformFinalBlock(data, 0, data.Length));
        }
 internal static byte[] AES256Decrypt(byte[] block, byte[] key)
 {
     using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
     {
         aes.Key     = key;
         aes.Mode    = System.Security.Cryptography.CipherMode.ECB;
         aes.Padding = System.Security.Cryptography.PaddingMode.None;
         using (System.Security.Cryptography.ICryptoTransform decryptor = aes.CreateDecryptor())
         {
             return(decryptor.TransformFinalBlock(block, 0, block.Length));
         }
     }
 }
Ejemplo n.º 16
0
        private string CryptoTransform(string input, bool base64in, bool base64out, Aes cipher, CMode mode)
        {
            byte[] bytes;
            if (base64in)
                bytes = decode64(input);
            else
                bytes = Encoding.UTF8.GetBytes(input);


            using (var c = mode == CMode.ENCRYPT ? cipher.CreateEncryptor() : cipher.CreateDecryptor()) {
            var buf = c.TransformFinalBlock(bytes, 0, bytes.Length);
            return base64out ? encode64(buf) : Encoding.UTF8.GetString(buf);
            }
        }
        /// <summary>
        /// Decrypts data.
        /// </summary>
        /// <param name="aes">Aes object.</param>
        /// <param name="encrypted">Encrypted data to be decrypted.</param>
        /// <param name="key">Encryption key.</param>
        /// <param name="iv">Initial vector.</param>
        /// <returns>Decrypted data.</returns>
        public static byte[] Decrypt(Aes aes, byte[] encrypted, byte[] key, byte[] iv)
        {
            byte[] buffer = new byte[encrypted.Length];

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

            using (MemoryStream ms = new MemoryStream(encrypted))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    int length = cs.Read(buffer, 0, encrypted.Length);
                    return buffer.Take(length).ToArray();
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Decrypt the giving <see cref="Byte"> <see cref="Array"/>.
        /// </summary>
        /// <param name="cipherText">The <see cref="Byte"> <see cref="Array"/> that contains data to decrypt.</param>
        /// <param name="Key">The <see cref="Byte"> <see cref="Array"/> that contains the key.</param>
        /// <param name="IV">The <see cref="Byte"> <see cref="Array"/> that contains the initialize vector.</param>
        /// <returns>The decrypted data.</returns>
        public static byte[] Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(cipherText, null) || cipherText.Length <= 0)
            {
                throw (new ArgumentNullException("cipherText"));
            }

            if (ReferenceEquals(Key, null) || Key.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            if (ReferenceEquals(IV, null) || IV.Length <= 0)
            {
                throw (new ArgumentNullException("IV"));
            }

            // Declare the string used to hold the decrypted text
            byte[] clearBytes = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = AesManaged.Create())
            {
                aesAlg.Key     = Key;
                aesAlg.IV      = IV;
                aesAlg.Padding = PaddingMode.Zeros;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
                    {
                        csDecrypt.Write(cipherText, 0, cipherText.Length);
                        csDecrypt.Flush();
                        csDecrypt.Close();
                    }

                    clearBytes = msDecrypt.ToArray();
                }
            }

            return(clearBytes);
        }
Ejemplo n.º 19
0
        public static string DecryptStringFromBytes_AES(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments
            if (ReferenceEquals(cipherText, null) || cipherText.Length <= 0)
            {
                throw (new ArgumentNullException("cipherText"));
            }

            if (ReferenceEquals(Key, null) || Key.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            if (ReferenceEquals(IV, null) || IV.Length <= 0)
            {
                throw (new ArgumentNullException("Key"));
            }

            // Declare the string used to hold the decrypted text
            string plaintext = null;

            // Create an Aes object with the specified key and IV
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    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
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return(plaintext);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Encrypt a byte array by using the AES algorightm.
        /// <para>The input is: [Magic Number (4 bytes)] [AES IV (16 bytes)] [AES(data) (xx bytes)] [HMAC(IV || AES(data)) (32 bytes)]</para>
        /// <para>The output is: [data]</para>
        /// </summary>
        public static byte[] Decrypt(byte[] content, Aes aes)
        {
            byte[] headerBytes = new byte[4];
            byte[] ivBytes = new byte[16];
            byte[] dataBytes = new byte[content.Length - 4 - 16 - 32];
            byte[] cypherBytes = new byte[ivBytes.Length + dataBytes.Length];
            byte[] hmacBytes = new byte[32];

            Array.Copy (content, 0, headerBytes, 0, headerBytes.Length);
            Array.Copy (content, 4, ivBytes, 0, ivBytes.Length);
            Array.Copy (content, 4 + 16, dataBytes, 0, dataBytes.Length);
            Array.Copy (content, 4, cypherBytes, 0, cypherBytes.Length);
            Array.Copy (content, content.Length - 32, hmacBytes, 0, hmacBytes.Length);

            // Compute the HMAC of the cypher
            using (HMACSHA256 hmac = new HMACSHA256 (DeriveKey (aes.Key))) {
                byte[] newHmacBytes = hmac.ComputeHash (cypherBytes);

                // Check for HMAC equality
                for (int i = 0; i < newHmacBytes.Length; i++) {
                    if (newHmacBytes [i] != hmacBytes [i]) {
                        throw new CryptographicException ("Content has been tampered. HMAC don't match.");
                    }
                }
            }

            using (MemoryStream outputStream = new MemoryStream()) {
                // Report the IV
                aes.IV = ivBytes;

                // Write the AES decrypted content
                using (ICryptoTransform transform = aes.CreateDecryptor ()) {
                    using (CryptoStream cryptoStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write)) {
                        cryptoStream.Write (dataBytes, 0, dataBytes.Length);
                    }
                }

                // Collect cypher result
                outputStream.Flush ();
                outputStream.Close ();
                byte[] outputBytes = outputStream.ToArray ();

                return outputBytes;
            }
        }
Ejemplo n.º 21
0
        private bool TestRequestVerifier(Request r, Aes aes, string key)
        {
            var success = false;
            var crypted = decode64(r.Verifier);

            aes.Key = decode64(key);
            aes.IV = decode64(r.Nonce);

            using (var dec = aes.CreateDecryptor())
            {
                try {
                    var buf = dec.TransformFinalBlock(crypted, 0, crypted.Length);
                    var value = Encoding.UTF8.GetString(buf);
                    success = value == r.Nonce;
                } catch (CryptographicException) { } // implicit failure
            }
            return success;
        }
Ejemplo n.º 22
0
    static Boolean Test(Aes aes, CipherMode md)
    {

        Byte[]  PlainText = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        Byte[]  Key = {1, 1, 1, 1, 1, 1, 1, 1,2,2,2,2,2,2,2,2};
        Byte[]  IV = {100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115};
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(PlainText);
        
        aes.Mode = md;

        Console.WriteLine("AES default key size = " + aes.KeySize);
        ICryptoTransform sse = aes.CreateEncryptor(Key, IV);
        Console.WriteLine("SSE mode = " + aes.Mode);
        MemoryStream ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(PlainText,0,PlainText.Length);
        cs.FlushFinalBlock();
        byte[] CipherText = ms.ToArray();
        cs.Close();

        Console.WriteLine("Cyphertext:");
        PrintByteArray(CipherText);
        

        Console.WriteLine("Decrypting...");

        ICryptoTransform ssd = aes.CreateDecryptor(Key, IV);
        Console.WriteLine("SSD mode = " + aes.Mode);
        cs = new CryptoStream(new MemoryStream(CipherText), ssd, CryptoStreamMode.Read);

        byte[] NewPlainText = new byte[PlainText.Length];
        cs.Read(NewPlainText,0,PlainText.Length);

        PrintByteArray(NewPlainText);
        
        if (!Compare(PlainText, NewPlainText)) {
        	Console.WriteLine("ERROR: roundtrip failed");
        	return false;
        }
        
        return true;
    }
Ejemplo n.º 23
0
    static Boolean TestKnownEnc(Aes aes, Byte[] Key, Byte[] IV, Byte[] Cipher, Byte[] Plain)
    {

        Byte[]  CipherCalculated;
        
        Console.WriteLine("Encrypting the following bytes:");
        PrintByteArray(Plain);
        Console.WriteLine("With the following Key:");
        PrintByteArray(Key);
        Console.WriteLine("and IV:");
        PrintByteArray(IV);
 		Console.WriteLine("Expecting this ciphertext:");
		PrintByteArray(Cipher);        
        
        ICryptoTransform sse = aes.CreateDecryptor(Key, IV);
        MemoryStream 	ms = new MemoryStream();
        CryptoStream    cs = new CryptoStream(ms, sse, CryptoStreamMode.Write);
        cs.Write(Plain,0,Plain.Length);
        
		try
		{
			cs.FlushFinalBlock();
		} 
		catch (CryptographicException e)
		{
			Console.WriteLine(e.ToString());
		}

        CipherCalculated = ms.ToArray();
        cs.Close();

        Console.WriteLine("Computed this cyphertext:");
        PrintByteArray(CipherCalculated);
        

        if (!Compare(Cipher, CipherCalculated)) {
        	Console.WriteLine("ERROR: result is different from the expected");
        	return false;
        }
        
        Console.WriteLine("OK");
        return true;
    }
Ejemplo n.º 24
0
 public override string Decrypt(string cipherText, string key, string iv)
 {
     try
     {
         System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
         byte[] inputBytes = Convert.FromBase64String(cipherText);
         aes.Key = Convert.FromBase64String(key);
         aes.IV  = Convert.FromBase64String(iv);
         MemoryStream ms = new MemoryStream();
         CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
         cs.Write(inputBytes, 0, inputBytes.Length);
         cs.FlushFinalBlock();
         return(Encoding.UTF8.GetString(ms.ToArray()));
     }
     catch (Exception e)
     {
         return("\nERROR: " + e.Message);
     }
 }
Ejemplo n.º 25
0
 public string Decrypt(string str)
 {
     str = str.Replace(" ", "+");
     byte[] bytes = Convert.FromBase64String(str);
     using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
     {
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, 8);
         encryptor.Key = pdb.GetBytes(32);
         encryptor.IV  = pdb.GetBytes(16);
         using (MemoryStream ms = new MemoryStream())
         {
             using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(bytes, 0, bytes.Length);
                 cs.Close();
             }
             return(Encoding.Unicode.GetString(ms.ToArray()));
         }
     }
 }
 public static string Decrypt(string DecryptText)
 {
     DecryptText = DecryptText.Replace(" ", "+");
     byte[] cipherBytes = Convert.FromBase64String(DecryptText);
     using (Aes encryptor = Aes.Create())
     {
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
         encryptor.Key = pdb.GetBytes(32);
         encryptor.IV  = pdb.GetBytes(16);
         using (MemoryStream ms = new MemoryStream())
         {
             using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(cipherBytes, 0, cipherBytes.Length);
                 cs.Close();
             }
             DecryptText = Encoding.Unicode.GetString(ms.ToArray());
         }
     }
     return(DecryptText);
 }
Ejemplo n.º 27
0
        public static string DecryptString(string key, string cipherText)
        {
            byte[] iv     = new byte[16];
            byte[] buffer = Convert.FromBase64String(cipherText);

            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV  = iv;
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
                        {
                            return(streamReader.ReadToEnd());
                        }
                    }
                }
            }
        }
Ejemplo n.º 28
0
        public byte[] DecoderBytes(byte[] inputBytes)
        {
            Byte[] outputBytes = inputBytes;

            byte[] decode = new byte[] { };

            using (MemoryStream memoryStream = new MemoryStream(outputBytes))
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, AES.CreateDecryptor(AES.Key, AES.IV), CryptoStreamMode.Read))
                {
                    int    len = 1024, count = len;
                    byte[] buffer = new byte[len];

                    while (count != 0)
                    {
                        count  = cryptoStream.Read(buffer, 0, len);
                        decode = Program.ConcatByte(decode, buffer, count);
                    }
                }
            }

            return(decode);
        }
Ejemplo n.º 29
0
        public void Initialize(ReadOnlySpan <byte> key, ReadOnlySpan <byte> iv, CipherMode mode, bool isDecrypting)
        {
            Debug.Assert(key.Length == Aes.KeySize128);
            Debug.Assert(iv.IsEmpty || iv.Length == Aes.BlockSize);

            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();

            if (aes == null)
            {
                throw new CryptographicException("Unable to create AES object");
            }
            aes.Key     = key.ToArray();
            aes.Mode    = mode;
            aes.Padding = PaddingMode.None;

            if (!iv.IsEmpty)
            {
                aes.IV = iv.ToArray();
            }

            _transform    = isDecrypting ? aes.CreateDecryptor() : aes.CreateEncryptor();
            _isDecrypting = isDecrypting;
        }
        /// <summary>
        /// Decrypts a string
        /// </summary>
        /// <param name="encryptedString"></param>
        /// <returns></returns>
        public string DecryptBytes(byte[] value)
        {
            ICryptoTransform et     = _cryptor.CreateDecryptor(_cryptor.Key, _cryptor.IV);
            string           output = string.Empty;

            if (value != null)
            {
                using (MemoryStream ms = new MemoryStream(value))
                {
                    using (CryptoStream cs = new CryptoStream(ms, et, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs, this._encoding, true, this._padding))
                        {
                            output = sr.ReadToEnd();
                            sr.Dispose();
                        }
                        cs.Dispose();
                    }
                    ms.Dispose();
                }
            }

            return(output);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="data">待解密的密文</param>
        /// <param name="password">加密公钥</param>
        /// <returns>返回一个由AesEncrypt加密而得到的明文</returns>
        public static string AesDecrypt(this string data, string password)
        {
            if (string.IsNullOrEmpty(data) || string.IsNullOrEmpty(password))
            {
                return(data);
            }

            byte[] keyBytes       = password.ToBytes();
            byte[] toEncryptArray = Convert.FromBase64String(data);
            Aes    aesProvider    = Aes.Create();

            if (keyBytes.Length < aesProvider.KeySize)
            {
                throw new KeySizeException();
            }

            aesProvider.Key     = keyBytes;
            aesProvider.Mode    = CipherMode.ECB;
            aesProvider.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = aesProvider.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return(Encoding.UTF8.GetString(resultArray));
        }
Ejemplo n.º 32
0
        private static void Decrypt(byte[] cipherText, byte[] plaintext, byte[] key, byte[] iv)
        {
            var decryptor = Aes.CreateDecryptor(key, iv);

            decryptor.TransformBlock(cipherText, 0, cipherText.Length, plaintext, 0);
        }
Ejemplo n.º 33
0
        public SegmentReader(Stream _bsstr, Aes rdale, int _fragsize)
        {
            
            _rdale = rdale as AesManaged;
            
            basestream = _bsstr;
            fragsize = _fragsize;
            reader = rdale.CreateDecryptor();
            writer = rdale.CreateEncryptor();
#if !SINGLE_THREADED
            mthread = new System.Threading.Thread(thetar);
            mthread.Start();
#endif
        }
Ejemplo n.º 34
0
	public static bool TestTransform(Aes aes)
	{
		ICryptoTransform encryptor;
		ICryptoTransform decryptor;

		encryptor = aes.CreateEncryptor();
		decryptor = aes.CreateDecryptor();

		if (encryptor.CanReuseTransform != true)
		{
			Console.WriteLine("Error - encryptor CanReuseTransform not true");
			return false;
		}

		if (decryptor.CanReuseTransform != true)
		{
			Console.WriteLine("Error - decryptor CanReuseTransform not true");
			return false;
		}

		if (encryptor.CanTransformMultipleBlocks != true)
		{
			Console.WriteLine("Error - encryptor CanTransformMultipleBlocks not true");
			return false;
		}

		if (decryptor.CanTransformMultipleBlocks != true)
		{
			Console.WriteLine("Error - decryptor CanTransformMultipleBlocks not true");
			return false;
		}

		if (encryptor.InputBlockSize != 16)
		{
			Console.WriteLine("Error - encryptor InputBlockSize not 16");
			return false;
		}

		if (decryptor.InputBlockSize != 16)
		{
			Console.WriteLine("Error - decryptor InputBlockSize not 16");
			return false;
		}

		if (encryptor.OutputBlockSize != 16)
		{
			Console.WriteLine("Error - encryptor OutputBlockSize not 16");
			return false;
		}

		if (decryptor.OutputBlockSize != 16)
		{
			Console.WriteLine("Error - decryptor OutputBlockSize not 16");
			return false;
		}

		return true;
	}
Ejemplo n.º 35
0
 private ICryptoTransform GetMessageDecryptor(
     Aes aes,
     TaskAgentMessage message)
 {
     if (Session.EncryptionKey.Encrypted)
     {
         // The agent session encryption key uses the AES symmetric algorithm
         var keyManager = HostContext.GetService<IRSAKeyManager>();
         using (var rsa = keyManager.GetKey())
         {
             return aes.CreateDecryptor(rsa.Decrypt(Session.EncryptionKey.Value, RSAEncryptionPadding.OaepSHA1), message.IV);
         }
     }
     else
     {
         return aes.CreateDecryptor(Session.EncryptionKey.Value, message.IV);
     }
 }
Ejemplo n.º 36
0
 public SegmentReader(Stream _bsstr, Aes rdale, int _fragsize)
 {
     
     _rdale = rdale as AesManaged;
     
     basestream = _bsstr;
     fragsize = _fragsize;
     reader = rdale.CreateDecryptor();
   
 }
Ejemplo n.º 37
0
        public static Message ToMessage(this MemoryStream inStream, Aes aes = null)
        {
            if (inStream.Length == 0)
                throw new Exceptions.CommunicationException("read stream blank!");

            MemoryStream plainStream;

            inStream.Seek(0, SeekOrigin.Begin);

            //TODO: clean this up
            string beforeGreaterThan = StreamUtilities.ReadUntilChar(inStream, '<', 5, true);
            string beforeExclaimation = StreamUtilities.ReadUntilChar(inStream, '!', 5, true);

            bool streamEncrypted;
            if (beforeGreaterThan != null && beforeExclaimation == null)
                streamEncrypted = false;
            else if (beforeGreaterThan == null && beforeExclaimation != null)
                streamEncrypted = true;
            else if (beforeGreaterThan.Length < beforeExclaimation.Length)
                streamEncrypted = false;
            else
                streamEncrypted = true;

            if (streamEncrypted)
            {

                if (aes == null)
                    throw new Exceptions.CommunicationException("oops!  Got an encrypted response, but don't know the key.");

                string numBytesForIvString = StreamUtilities.ReadUntilChar(inStream, '!', 10, false);

                //int bleh = StreamUtilities.PeekByte(inStream);
                //string test2 = StreamUtilities.MemoryStreamToString(inStream);

                int numBytesForIv;
                try
                {
                    numBytesForIv = Convert.ToInt32(numBytesForIvString);
                }
                catch
                {
                    throw new Exceptions.CommunicationException("Error parsing the number of bytes for the Initialization Vector");
                }

                byte[] iv = new byte[numBytesForIv];
                int numRead = inStream.Read(iv, 0, numBytesForIv);

                if (numRead != numBytesForIv)
                    throw new Exceptions.CommunicationException("Error reading the initialization vector.");

                aes.IV = iv;

                try
                {
                    plainStream = StreamUtilities.RunCryptoTransform(inStream, aes.CreateDecryptor(), false);

                    plainStream.Seek(0, SeekOrigin.Begin);
                    //string beforeGreaterThan2 = StreamUtilities.ReadUntilChar(inStream, 'x', 50, true);
                    //string test3 = StreamUtilities.MemoryStreamToString(plainStream);
                    //inStream.Seek(0, SeekOrigin.Begin);
                }
                catch (CryptographicException exception)
                {
                    throw new Exceptions.CommunicationException("Error decrypting response.", exception);
                }
            }
            else
            {
                plainStream = inStream;
            }

            Message result = new Message(plainStream);

            if (result.controlValues.Count == 0 && result.Values.Count == 0 && result.Payload.Count == 0)
                throw new Exceptions.CommunicationException("Blank response.");

            if (!String.IsNullOrEmpty(result.CommunicationErrorMessage))
                throw new Exceptions.CommunicationException(result.CommunicationErrorMessage);

            return result;
        }
Ejemplo n.º 38
0
 public byte[] DecodeBytes(string s)
 {
     return(Transform(rsa.CreateDecryptor(), Encoding.UTF8.GetBytes(s)));
 }
Ejemplo n.º 39
0
 public static byte[] Decrypt(this byte[] encrypted, FAesKey key)
 {
     return(Provider.CreateDecryptor(key.Key, null).TransformFinalBlock(encrypted, 0, encrypted.Length));
 }
Ejemplo n.º 40
0
 public static ICryptoTransform getDecryptor(Aes aes)
 {
     return aes.CreateDecryptor(aes.Key, aes.IV);
 }
            internal AesCbcHmacSha2Decryptor( string name, byte[] key, byte[] iv, byte[] associatedData )
            {
                // Split the key to get the AES key, the HMAC key and the HMAC object
                byte[] aesKey;

                GetAlgorithmParameters( name, key, out aesKey, out _hmac_key, out _hmac );

                // Create the AES provider
                _aes = Aes.Create();

                _aes.Mode    = CipherMode.CBC;
                _aes.Padding = PaddingMode.PKCS7;
                _aes.KeySize = aesKey.Length * 8;
                _aes.Key     = aesKey;
                _aes.IV      = iv;

                _inner = _aes.CreateDecryptor();

                _associated_data_length = ConvertToBigEndian( associatedData.Length * 8 );

                // Prime the hash.
                _hmac.TransformBlock( associatedData, 0, associatedData.Length, associatedData, 0 );
                _hmac.TransformBlock( iv, 0, iv.Length, iv, 0 );
            }
Ejemplo n.º 42
0
	public static byte[] GetPaddingBytes(Aes aes, PaddingMode mode, int offset)
	{
		byte[] originalData = new byte[BlockSizeBytes + offset];
		new Random().NextBytes(originalData);

		aes.Padding = mode;
		byte[] encryptedData = aes.CreateEncryptor().TransformFinalBlock(originalData, 0, originalData.Length);

		aes.Padding = PaddingMode.None;
		byte[] decryptedData = aes.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);

		byte[] paddingBytes = new byte[decryptedData.Length - BlockSizeBytes - offset];
		Array.Copy(decryptedData, BlockSizeBytes + offset, paddingBytes, 0, decryptedData.Length - BlockSizeBytes - offset);
		
		return paddingBytes;
	}
Ejemplo n.º 43
0
 public override ICryptoTransform CreateDecryptor() => _impl.CreateDecryptor();
Ejemplo n.º 44
0
	public static bool TestTransform(Aes aes)
	{
		CipherMode[] modes;

		// AES allows CBC, ECB, and CFB modes.  Due to bug in RijndaelManaged, AesManaged does not
		// allow CFB.
		//
		if (aes is AesManaged)
			modes = new CipherMode[] {CipherMode.CBC, CipherMode.ECB};
		else
			modes = new CipherMode[] {CipherMode.CBC, CipherMode.ECB, CipherMode.CFB};

		ICryptoTransform encryptor;
		ICryptoTransform decryptor;

		foreach (CipherMode mode in modes)
		{
			aes.Mode = mode;

			encryptor = aes.CreateEncryptor();
			decryptor = aes.CreateDecryptor();

			if (encryptor.CanReuseTransform != true)
			{
				Console.WriteLine("Error - encryptor CanReuseTransform not true");
				return false;
			}

			if (decryptor.CanReuseTransform != true)
			{
				Console.WriteLine("Error - decryptor CanReuseTransform not true");
				return false;
			}

			if (encryptor.CanTransformMultipleBlocks != true)
			{
				Console.WriteLine("Error - encryptor CanTransformMultipleBlocks not true");
				return false;
			}

			if (decryptor.CanTransformMultipleBlocks != true)
			{
				Console.WriteLine("Error - decryptor CanTransformMultipleBlocks not true");
				return false;
			}

			if (encryptor.InputBlockSize != 16)
			{
				Console.WriteLine("Error - encryptor InputBlockSize not 16");
				return false;
			}

			if (decryptor.InputBlockSize != 16)
			{
				Console.WriteLine("Error - decryptor InputBlockSize not 16");
				return false;
			}

			if (encryptor.OutputBlockSize != 16)
			{
				Console.WriteLine("Error - encryptor OutputBlockSize not 16");
				return false;
			}

			if (decryptor.OutputBlockSize != 16)
			{
				Console.WriteLine("Error - decryptor OutputBlockSize not 16");
				return false;
			}
		}

		return true;
	}