Ejemplo n.º 1
0
        /// <summary>
        /// Decrypts plain text data using AES in CBC mode
        /// </summary>
        private byte[] DecryptData(byte[] iv, byte[] cipherText, int offset, int count)
        {
            Debug.Assert((iv != null) && (cipherText != null));
            Debug.Assert(offset > -1 && count > -1);
            Debug.Assert((count + offset) <= cipherText.Length);

            byte[] plainText;
            AesCryptoServiceProvider aesAlg;

            // Try to get a provider from the pool.
            // If no provider is available, create a new one.
            if (!this.cryptoProviderPool.TryDequeue(out aesAlg))
            {
                aesAlg = new AesCryptoServiceProvider();

                try
                {
                    // Set various algorithm properties
                    aesAlg.Key     = this.dataEncryptionKey.EncryptionKey;
                    aesAlg.Mode    = cipherMode;
                    aesAlg.Padding = paddingMode;
                }
                catch (Exception)
                {
                    aesAlg?.Dispose();

                    throw;
                }
            }

            try
            {
                // Always set the IV since it changes from cell to cell.
                aesAlg.IV = iv;

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream())
                {
                    // Create an encryptor to perform the stream transform.
                    using (ICryptoTransform decryptor = aesAlg.CreateDecryptor())
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
                        {
                            // Decrypt the secret message and get the plain text data
                            csDecrypt.Write(cipherText, offset, count);
                            csDecrypt.FlushFinalBlock();
                            plainText = msDecrypt.ToArray();
                        }
                    }
                }
            }
            finally
            {
                // Return the provider to the pool.
                this.cryptoProviderPool.Enqueue(aesAlg);
            }

            return(plainText);
        }
Ejemplo n.º 2
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects).
                    _aes?.Dispose();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
 /// <summary>
 /// Close output stream and AesCryptoServiceProvider
 /// </summary>
 public void Dispose()
 {
     aes?.Dispose();
 }
Ejemplo n.º 4
0
 public void Dispose()
 {
     aesAlg.Dispose();
 }
Ejemplo n.º 5
0
        private void encriptFileContent(string contents, string fullPath, Boolean flag)
        {
            AesCryptoServiceProvider aes = null;
            FileStream   fsOutput        = null;
            CryptoStream cs      = null;
            FileStream   fsInput = null;
            StreamWriter sw      = null;
            StreamWriter swl     = null;

            string directoryName = Path.GetDirectoryName(fullPath) + "\\" + Path.GetFileNameWithoutExtension(fullPath);

            try
            {
                aes      = new AesCryptoServiceProvider();
                this.key = aes.Key;
                this.iv  = aes.IV;

                string newFileName = directoryName + ".dat";
                if (Path.GetExtension(fullPath).Equals(".dat"))
                {
                    newFileName = directoryName + "_copy.dat";
                }
                using (fsOutput = new FileStream(newFileName, FileMode.Create))
                {
                    using (cs = new CryptoStream(fsOutput, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        using (fsInput = new FileStream(fullPath, FileMode.Open))
                        {
                            int data;
                            while ((data = fsInput.ReadByte()) != -1)
                            {
                                cs.WriteByte((byte)data);
                            }
                        }
                    }
                }

                if (flag)
                {
                    using (sw = File.AppendText(keyPath + filesWithFilenameAndKeys))
                    {
                        sw.WriteLine(System.Convert.ToBase64String(aes.Key));
                        sw.WriteLine(System.Convert.ToBase64String(aes.IV));
                        sw.WriteLine(Path.GetFullPath(fullPath));
                        using (swl = File.AppendText(keyPath + listFilesEncripted))
                        {
                            swl.WriteLine(Path.GetFullPath(fullPath));
                        }
                    }
                }
                else
                {
                    using (sw = File.AppendText(keyPath + encriptedKey)) //chave resulta do ficheiro files.txt
                    {
                        sw.WriteLine(System.Convert.ToBase64String(aes.Key));
                        sw.WriteLine(System.Convert.ToBase64String(aes.IV));
                    }
                }

                File.Delete(fullPath);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (aes != null)
                {
                    aes.Dispose();
                }
                if (fsOutput != null)
                {
                    fsOutput.Dispose();
                }
                if (cs != null)
                {
                    cs.Dispose();
                }
                if (fsInput != null)
                {
                    fsInput.Dispose();
                }
                if (sw != null)
                {
                    sw.Dispose();
                }
                if (swl != null)
                {
                    swl.Dispose();
                }
            }
        }
Ejemplo n.º 6
0
        private void decriptFileContent(string fileKey, string fileIv, string fullPath, Boolean flag)
        {
            AesCryptoServiceProvider aes = null;
            FileStream   fsInput         = null;
            CryptoStream cs       = null;
            FileStream   fsOutput = null;


            try
            {
                //Configuração (ler a chave)
                aes = new AesCryptoServiceProvider();

                aes.Key = System.Convert.FromBase64String(fileKey);
                aes.IV  = System.Convert.FromBase64String(fileIv);

                string encriptedFile = Path.GetDirectoryName(fullPath) + "\\" + Path.GetFileNameWithoutExtension(fullPath) + ".dat";

                if (Path.GetExtension(fullPath).Equals(".dat"))
                {
                    encriptedFile = Path.GetDirectoryName(fullPath) + "\\" + Path.GetFileNameWithoutExtension(fullPath) + "_copy.dat";
                }

                using (fsInput = new FileStream(encriptedFile, FileMode.Open))
                {
                    using (cs = new CryptoStream(fsInput, aes.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        using (fsOutput = new FileStream(Path.GetDirectoryName(fullPath) + "\\" + Path.GetFileNameWithoutExtension(fullPath) + Path.GetExtension(fullPath), FileMode.Create))
                        {
                            int data;
                            while ((data = cs.ReadByte()) != -1)
                            {
                                fsOutput.WriteByte((byte)data);
                            }
                        }
                    }
                }

                File.Delete(encriptedFile);
                if (flag)
                {
                    foreach (string file in Directory.EnumerateFiles(keyPath, "*.*", SearchOption.AllDirectories))   // O.o TEMOS QUE VERIFICAR SÓ PARA ACEITAR AS EXTENÇOES QUE PRETENDEMOS
                    {
                        File.Delete(file);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (aes != null)
                {
                    aes.Dispose();
                }
                if (fsInput != null)
                {
                    fsInput.Dispose();
                }
                if (cs != null)
                {
                    cs.Dispose();
                }
                if (fsOutput != null)
                {
                    fsOutput.Dispose();
                }
            }
        }
Ejemplo n.º 7
0
 public void Dispose()
 {
     _aes.Dispose();
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Encryption Algorithm
        /// cell_iv = HMAC_SHA-2-256(iv_key, cell_data) truncated to 128 bits
        /// cell_ciphertext = AES-CBC-256(enc_key, cell_iv, cell_data) with PKCS7 padding.
        /// (optional) cell_tag = HMAC_SHA-2-256(mac_key, versionbyte + cell_iv + cell_ciphertext + versionbyte_length)
        /// cell_blob = versionbyte + [cell_tag] + cell_iv + cell_ciphertext
        /// </summary>
        /// <param name="plainText">Plaintext data to be encrypted</param>
        /// <param name="hasAuthenticationTag">Does the algorithm require authentication tag.</param>
        /// <returns>Returns the ciphertext corresponding to the plaintext.</returns>
        protected byte[] EncryptData(byte[] plainText, bool hasAuthenticationTag)
        {
            // Empty values get encrypted and decrypted properly for both Deterministic and Randomized encryptions.
            Debug.Assert(plainText != null);

            byte[] iv = new byte[BlockSizeInBytes];

            // Prepare IV
            // Should be 1 single block (16 bytes)
            if (this.isDeterministic)
            {
                SecurityUtility.GetHMACWithSHA256(plainText, this.dataEncryptionKey.IVKey, iv);
            }
            else
            {
                SecurityUtility.GenerateRandomBytes(iv);
            }

            int numBlocks = (plainText.Length / BlockSizeInBytes) + 1;

            // Final blob we return = version + HMAC + iv + cipherText
            const int hmacStartIndex       = 1;
            int       authenticationTagLen = hasAuthenticationTag ? KeySizeInBytes : 0;
            int       ivStartIndex         = hmacStartIndex + authenticationTagLen;
            int       cipherStartIndex     = ivStartIndex + BlockSizeInBytes; // this is where hmac starts.

            // Output buffer size = size of VersionByte + Authentication Tag + IV + cipher Text blocks.
            int outputBufSize = sizeof(byte) + authenticationTagLen + iv.Length + (numBlocks * BlockSizeInBytes);

            byte[] outBuffer = new byte[outputBufSize];

            // Store the version and IV rightaway
            outBuffer[0] = this.algorithmVersion;
            Buffer.BlockCopy(iv, 0, outBuffer, ivStartIndex, iv.Length);

            AesCryptoServiceProvider aesAlg;

            // Try to get a provider from the pool.
            // If no provider is available, create a new one.
            if (!this.cryptoProviderPool.TryDequeue(out aesAlg))
            {
                aesAlg = new AesCryptoServiceProvider();

                try
                {
                    // Set various algorithm properties
                    aesAlg.Key     = this.dataEncryptionKey.EncryptionKey;
                    aesAlg.Mode    = cipherMode;
                    aesAlg.Padding = paddingMode;
                }
                catch (Exception)
                {
                    aesAlg?.Dispose();

                    throw;
                }
            }

            try
            {
                // Always set the IV since it changes from cell to cell.
                aesAlg.IV = iv;

                // Compute CipherText and authentication tag in a single pass
                using (ICryptoTransform encryptor = aesAlg.CreateEncryptor())
                {
                    Debug.Assert(encryptor.CanTransformMultipleBlocks, "AES Encryptor can transform multiple blocks");
                    int count       = 0;
                    int cipherIndex = cipherStartIndex; // this is where cipherText starts
                    if (numBlocks > 1)
                    {
                        count        = (numBlocks - 1) * BlockSizeInBytes;
                        cipherIndex += encryptor.TransformBlock(plainText, 0, count, outBuffer, cipherIndex);
                    }

                    byte[] buffTmp = encryptor.TransformFinalBlock(plainText, count, plainText.Length - count); // done encrypting
                    Buffer.BlockCopy(buffTmp, 0, outBuffer, cipherIndex, buffTmp.Length);
                    cipherIndex += buffTmp.Length;
                }

                if (hasAuthenticationTag)
                {
                    using (HMACSHA256 hmac = new HMACSHA256(this.dataEncryptionKey.MACKey))
                    {
                        Debug.Assert(hmac.CanTransformMultipleBlocks, "HMAC can't transform multiple blocks");
                        hmac.TransformBlock(version, 0, version.Length, version, 0);
                        hmac.TransformBlock(iv, 0, iv.Length, iv, 0);

                        // Compute HMAC on final block
                        hmac.TransformBlock(outBuffer, cipherStartIndex, numBlocks * BlockSizeInBytes, outBuffer, cipherStartIndex);
                        hmac.TransformFinalBlock(versionSize, 0, versionSize.Length);
                        byte[] hash = hmac.Hash;
                        Debug.Assert(hash.Length >= authenticationTagLen, "Unexpected hash size");
                        Buffer.BlockCopy(hash, 0, outBuffer, hmacStartIndex, authenticationTagLen);
                    }
                }
            }
            finally
            {
                // Return the provider to the pool.
                this.cryptoProviderPool.Enqueue(aesAlg);
            }

            return(outBuffer);
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            const int n      = 100 * 1000;
            var       sw     = new Stopwatch();
            Random    r      = new Random();
            var       data   = new byte[1024];
            var       key8B  = new byte[8];
            var       key16B = new byte[16];
            var       key24B = new byte[24];
            var       key32B = new byte[32];

            r.NextBytes(data);
            r.NextBytes(key8B);
            r.NextBytes(key16B);
            r.NextBytes(key24B);
            r.NextBytes(key32B);
            Action <string> outputToConsole = (s) =>
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(s);
            };

            // AES
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("AES");
            var aes = new AesCryptoServiceProvider();

            aes.Padding = PaddingMode.PKCS7;
            aes.Key     = key16B;
            Action doAes = () => EncryptDecryptAndDispose(aes.CreateEncryptor(), aes.CreateDecryptor(), data);

            doAes.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            aes.Dispose();

            // RSA
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("DES");
            var des = new DESCryptoServiceProvider();

            des.IV  = key8B;
            des.Key = key8B;
            Action doDes = () => EncryptDecryptAndDispose(des.CreateEncryptor(), des.CreateDecryptor(), data);

            doDes.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            des.Dispose();

            // RC2
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("RC2");
            var rc2 = new RC2CryptoServiceProvider();

            rc2.IV  = key8B;
            rc2.Key = key8B;
            Action doRc2 = () => EncryptDecryptAndDispose(rc2.CreateEncryptor(), rc2.CreateDecryptor(), data);

            doRc2.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            rc2.Dispose();

            // Rijndael
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("Rijndael");
            var rijndael = new RijndaelManaged();

            rijndael.IV  = key16B;
            rijndael.Key = key16B;
            Action doRijndael = () => EncryptDecryptAndDispose(rijndael.CreateEncryptor(), rijndael.CreateDecryptor(), data);

            doRijndael.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            rijndael.Dispose();

            // 3DES
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("3DES");
            var tripleDes = new TripleDESCryptoServiceProvider();

            tripleDes.IV  = key8B;
            tripleDes.Key = key24B;
            Action do3des = () => EncryptDecryptAndDispose(tripleDes.CreateEncryptor(), tripleDes.CreateDecryptor(), data);

            do3des.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            tripleDes.Dispose();

            // RSA
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("RSA");
            RSAParameters param = new RSAParameters();

            param.Exponent = new byte[] { 0, 1, 0 };
            var store = new X509Store(StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly);
            X509Certificate cert = null;

            foreach (X509Certificate cer in store.Certificates)
            {
                if (cer != null)
                {
                    cert = cer;
                    break;
                }
            }
            param.Modulus = cert.GetPublicKey();

            var rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(param);


            Action doRsa = () =>
            {
                var encryptedData = rsa.Encrypt(key32B, true);
                //var decryptedData = rsa.Decrypt(encryptedData, true);
            };

            doRsa.Repeat(n)
            .OutputPerformance(sw, outputToConsole)();
            rsa.Dispose();

            Console.Read();
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            con("MachineKey Generator v0.1 for ASP.NET / xsiteman WebForms Application");
            con("");

            string _decKeyMode = "AES";
            string _hashMode   = "HMACSHA512";

            if (args.Length != 0)
            {
                if ((args.Length != 2) || (args[0] == "-h") || (args[0] == "--help"))
                {
                    error(-1);
                }

                if ((args[0] != "AES") && (args[0] != "DES") && (args[0] != "3DES"))
                {
                    error(1);
                }
                if ((args[1] != "MD5") && (args[1] != "SHA1") && (args[1] != "HMACSHA256") && (args[1] != "HMACSHA384") && (args[1] != "HMACSHA512"))
                {
                    error(2);
                }

                _decKeyMode = args[0];
                _hashMode   = args[1];

                con("FOUND OPTIONS: " + args[0] + ", " + args[1]);
            }
            else
            {
                con("USING DEFAULTS: AES + HMACSHA512");
            }

            con("");

            string _decKey;
            string _hashKey;

            switch (_decKeyMode)
            {
            case "3DES":
                TripleDESCryptoServiceProvider _3DES = new TripleDESCryptoServiceProvider();
                _3DES.GenerateKey();
                _decKey = BinToHexStr(_3DES.Key);
                _3DES.Dispose();
                break;

            case "DES":
                DESCryptoServiceProvider _DES = new DESCryptoServiceProvider();
                _DES.GenerateKey();
                _decKey = BinToHexStr(_DES.Key);
                _DES.Dispose();
                break;

            default:
                AesCryptoServiceProvider _AES = new AesCryptoServiceProvider();
                _AES.GenerateKey();
                _decKey = BinToHexStr(_AES.Key);
                _AES.Dispose();
                break;
            }

            switch (_hashMode)
            {
            case "MD5":
                HMACMD5 _MD5 = new HMACMD5();
                _hashKey = BinToHexStr(_MD5.Key);
                _MD5.Dispose();
                break;

            case "SHA1":
                HMACSHA1 _SHA1 = new HMACSHA1();
                _hashKey = BinToHexStr(_SHA1.Key);
                _SHA1.Dispose();
                break;

            case "SHA256":
                HMACSHA256 _SHA256 = new HMACSHA256();
                _hashKey = BinToHexStr(_SHA256.Key);
                _SHA256.Dispose();
                break;

            case "SHA384":
                HMACSHA384 _SHA384 = new HMACSHA384();
                _hashKey = BinToHexStr(_SHA384.Key);
                _SHA384.Dispose();
                break;

            default:
                HMACSHA512 _SHA512 = new HMACSHA512();
                _hashKey = BinToHexStr(_SHA512.Key);
                _SHA512.Dispose();
                break;
            }


            string _mkstring = string.Concat("<machineKey decryption=\"", _decKeyMode, "\" decryptionKey=\"", _decKey, "\" validation=\"", _hashMode, "\" validationKey=\"", _hashKey, "\" />");

            con(_mkstring);
        }
Ejemplo n.º 11
0
        private string Encrypt(string text, string strMeterID)
        {
            string strAESKey = string.Empty;

            //Need to check does the key exist

            using (var db = new uwkeydataEntities1())
            {
                foreach (MeterKey mk in db.MeterKeys)
                {
                    if (mk.MeterID == strMeterID)
                    {
                        strAESKey = mk.AesKey;
                    }
                }
            }

            //if key does not already exist
            if (strAESKey == string.Empty)
            {
                //make key on the fly
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {
                    myRijndael.KeySize = 128;
                    myRijndael.GenerateKey();
                    // we dont need iv just key value
                    //myRijndael.GenerateIV();

                    byte[] xkey = myRijndael.Key;
                    //var xIV = myRijndael.IV;

                    AesCryptoServiceProvider aes;
                    // AesCryptoServiceProvider
                    using (aes = new AesCryptoServiceProvider())
                    {
                        aes.BlockSize = 128;
                        aes.KeySize   = 128;
                        aes.IV        = Encoding.UTF8.GetBytes(AesIV);
                        aes.Key       = xkey;
                        aes.Mode      = CipherMode.CBC;
                        aes.Padding   = PaddingMode.PKCS7;

                        //store meterID AES Key AES IV in Database

                        using (var db = new uwkeydataEntities1())
                        {
                            MeterKey mk = new MeterKey();
                            mk.MeterID = strMeterID;
                            mk.AesKey  = Convert.ToBase64String(aes.Key);
                            db.MeterKeys.Add(mk);
                            db.SaveChanges();
                        }

                        //byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
                        // Convert string to byte array
                        byte[] src = Encoding.Unicode.GetBytes(text);

                        // encryption
                        using (ICryptoTransform encrypt = aes.CreateEncryptor())
                        {
                            byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
                            aes.Clear();
                            aes.Dispose();
                            encrypt.Dispose();
                            // Convert byte array to Base64 strings
                            return(Convert.ToBase64String(dest));
                        }
                    }
                }
            }
            else
            {
                //we have the key
                AesCryptoServiceProvider aes;
                // AesCryptoServiceProvider
                using (aes = new AesCryptoServiceProvider())
                {
                    aes.BlockSize = 128;
                    aes.KeySize   = 128;
                    aes.IV        = Encoding.UTF8.GetBytes(AesIV);
                    //aes.Key = Encoding.UTF8.GetBytes(strAESKey);
                    aes.Key     = System.Convert.FromBase64String(strAESKey);
                    aes.Mode    = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;

                    //byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
                    // Convert string to byte array
                    byte[] src = Encoding.Unicode.GetBytes(text);

                    // encryption
                    using (ICryptoTransform encrypt = aes.CreateEncryptor())
                    {
                        byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);
                        aes.Clear();
                        aes.Dispose();
                        encrypt.Dispose();
                        // Convert byte array to Base64 strings
                        return(Convert.ToBase64String(dest));
                    }
                }
            }
        }