public static byte[] DecryptData(System.Security.Cryptography.RSACryptoServiceProvider full_rsa, byte[] data)
    {
        System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.MemoryStream(data));
        int encryptedkeylength    = br.ReadInt32();
        int aeskeylength          = br.ReadInt32();
        int aesivlength           = br.ReadInt32();

        byte[] encryptedaeskey = br.ReadBytes(encryptedkeylength);
        byte[] encrypteddata   = br.ReadBytes((int)(data.Length - br.BaseStream.Position));
        br.Close();
        byte[] decryptedkey = full_rsa.Decrypt(encryptedaeskey, false);
        br = new System.IO.BinaryReader(new System.IO.MemoryStream(decryptedkey));
        using (System.Security.Cryptography.Aes myAes = System.Security.Cryptography.Aes.Create())
        {
            byte[] aeskey = br.ReadBytes(aeskeylength);
            byte[] aesiv  = br.ReadBytes(aesivlength);
            System.Security.Cryptography.ICryptoTransform decryptor = myAes.CreateDecryptor(aeskey, aesiv);
            using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream())
            {
                using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(csEncrypt))
                    {
                        bw.Write(encrypteddata);
                    }
                    return(msDecrypt.ToArray());
                }
            }
        }
    }
Esempio n. 2
0
        //암호화
        public static byte[] Encrypt(byte[] plainText, byte[] Key, byte[] IV)
        {
            byte[] cipherText;
            //byte[] plain = { 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08 };


            // Create an Aes object
            // with the specified key and IV.
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.BlockSize = 128;
                aesAlg.Key       = Key;
                aesAlg.IV        = IV;
                aesAlg.Mode      = System.Security.Cryptography.CipherMode.CBC;
                aesAlg.Padding   = System.Security.Cryptography.PaddingMode.PKCS7;

                // Create an encryptor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                cipherText = encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
            }

            return(cipherText);

            //byte[] result = new byte[newPlain.Length];
            //System.Buffer.BlockCopy(cipherText, 0, result, 0, newPlain.Length);

            //// Return the encrypted bytes from the memory stream.
            //return result;
        }
Esempio n. 3
0
        }   // End Constructor

        public string GenerateKey()
        {
            string retValue = null;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.GenerateKey();
                aes.GenerateIV();

                byte[] bIV  = aes.IV;
                byte[] bKey = aes.Key;
                aes.Clear();

                retValue = "IV: " + ByteArrayToHexString(bIV)
                           + System.Environment.NewLine
                           + "Key: " + ByteArrayToHexString(bKey);

                System.Array.Clear(bIV, 0, bIV.Length);
                System.Array.Clear(bKey, 0, bKey.Length);
                bIV  = null;
                bKey = null;
            } // End Using aes

            return(retValue);
        } // End Function GenerateKey
Esempio n. 4
0
        public static string Encrypt(string plainText, string encryptionKey)
        {
            //string EncryptionKey = "tahaahat";

            if (plainText == null)
            {
                return(string.Empty);
            }

            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(plainText);

            using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
            {
                System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.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 (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    plainText = HttpServerUtility.UrlTokenEncode(ms.ToArray());
                }
            }
            return(plainText);
        }
Esempio n. 5
0
        /// <summary>
        /// Saves the dataset encrypted in specified file
        /// </summary>
        /// <param name="dataset">Dataset to save</param>
        /// <param name="username">Username for encryption</param>
        /// <param name="password">Password for encryption</param>
        /// <param name="fileName">File name where to save</param>
        /// <param name="compress">Should the file be compressed</param>
        internal static void EncryptDataSet(System.Data.DataSet dataset, string username, string password, string fileName, bool compress)
        {
            // Check the parameters
            if (dataset == null ||
                string.IsNullOrEmpty(username) ||
                string.IsNullOrEmpty(password) ||
                string.IsNullOrEmpty(fileName))
            {
                throw new System.ArgumentNullException("All arguments must be supplied.");
            }

            // Save the dataset as encrypted
            using (System.Security.Cryptography.Aes aes = Cryptography.InitAes(username, password)) {
                using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None)) {
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(fileStream, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) {
                        if (compress)
                        {
                            // when compression is requested, use GZip
                            using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(cryptoStream, System.IO.Compression.CompressionMode.Compress)) {
                                dataset.WriteXml(zipStream, System.Data.XmlWriteMode.WriteSchema);
                                zipStream.Flush();
                            }
                        }
                        else
                        {
                            dataset.WriteXml(cryptoStream, System.Data.XmlWriteMode.WriteSchema);
                            cryptoStream.FlushFinalBlock();
                        }
                    }
                }
            }
        }
Esempio n. 6
0
        public string EncryptPassword(string clearText)
        {
            string encryptedText = "";


            string EncryptionKey = "Xavier";

            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
            {
                System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.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 (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    encryptedText = Convert.ToBase64String(ms.ToArray());
                }
            }


            return(encryptedText);
        }
    public static byte[] EncryptData(byte[] publickey, byte[] data)
    {
        using (System.Security.Cryptography.Aes myAes = System.Security.Cryptography.Aes.Create())
        {
            System.Security.Cryptography.ICryptoTransform encryptor = myAes.CreateEncryptor(myAes.Key, myAes.IV);
            using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
            {
                using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    System.IO.MemoryStream headerms = new System.IO.MemoryStream();
                    System.IO.BinaryWriter headerbw = new System.IO.BinaryWriter(headerms);
                    using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(csEncrypt))
                    {
                        System.Security.Cryptography.RSACryptoServiceProvider public_key = new System.Security.Cryptography.RSACryptoServiceProvider(1024);
                        public_key.ImportCspBlob(publickey);
                        byte[] encryptedkey = public_key.Encrypt(Combine(myAes.Key, myAes.IV), false);
                        headerbw.Write(encryptedkey.Length);
                        headerbw.Write(myAes.Key.Length);
                        headerbw.Write(myAes.IV.Length);
                        headerbw.Write(encryptedkey);
                        headerbw.Flush();
                        bw.Write(data);
                    }

                    byte[] result = Combine(headerms.ToArray(), msEncrypt.ToArray());
                    headerbw.Close();
                    return(result);
                }
            }
        }
    }
Esempio n. 8
0
        /// <summary>
        /// Reads and decrypts the dataset from the given file
        /// </summary>
        /// <param name="dataset">Dataset to read</param>
        /// <param name="username">Username for decryption</param>
        /// <param name="password">Password for decryption</param>
        /// <param name="fileName">File name to read</param>
        /// <param name="compressed">Is the file compressed</param>
        /// <returns>XmlReadMode used for reading</returns>
        internal static System.Data.XmlReadMode DecryptDataSet(System.Data.DataSet dataset, string username, string password, string fileName, bool compressed)
        {
            System.Data.XmlReadMode xmlReadMode;

            // Check the parameters
            if (dataset == null ||
                string.IsNullOrEmpty(username) ||
                string.IsNullOrEmpty(password) ||
                string.IsNullOrEmpty(fileName))
            {
                throw new System.ArgumentNullException("All arguments must be supplied.");
            }

            // Read the dataset and encrypt it
            using (System.Security.Cryptography.Aes aes = Cryptography.InitAes(username, password)) {
                using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open)) {
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(fileStream, aes.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Read)) {
                        if (compressed)
                        {
                            // when decompression is requested, use GZip
                            using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(cryptoStream, System.IO.Compression.CompressionMode.Decompress)) {
                                xmlReadMode = dataset.ReadXml(zipStream, System.Data.XmlReadMode.ReadSchema);
                            }
                        }
                        else
                        {
                            xmlReadMode = dataset.ReadXml(cryptoStream, System.Data.XmlReadMode.ReadSchema);
                        }
                    }
                }
            }

            return(xmlReadMode);
        }
Esempio n. 9
0
        public UniversalHashFunction(byte[] keyOf16Or24Or32Bytes, int randomKeyVectorLengthInBytes = 256)
        {
            int numberOfRandomBytesToGenerate = SetVectorLengthAndGetNumberOfRandomBytesNeeded(randomKeyVectorLengthInBytes);

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Key  = keyOf16Or24Or32Bytes;
                aes.IV   = new byte[16];
                aes.Mode = System.Security.Cryptography.CipherMode.CBC;

                byte[] pseudoRandomBytes;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ciphertext, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        if (numberOfRandomBytesToGenerate % 16 != 0)
                        {
                            numberOfRandomBytesToGenerate += 16 - (numberOfRandomBytesToGenerate % 16);
                        }
                        cs.Write(new byte[numberOfRandomBytesToGenerate], 0, numberOfRandomBytesToGenerate);
                    }
                    pseudoRandomBytes = ciphertext.ToArray();
                }

                _randomKeyVector = new ulong[randomKeyVectorLengthInBytes / 8];
                for (int i = 0; i < _randomKeyVector.Length; i++)
                {
                    _randomKeyVector[i] = BitConverter.ToUInt64(pseudoRandomBytes, i * 8);
                }
                _initialRandomKey = BitConverter.ToUInt64(pseudoRandomBytes, randomKeyVectorLengthInBytes);
            }
        }
Esempio n. 10
0
 public EncryptionHelper(byte[] key)
 {
     aes         = System.Security.Cryptography.Aes.Create();
     aes.Key     = key;
     aes.IV      = System.Text.UTF8Encoding.UTF8.GetBytes(System.Reflection.Assembly.GetExecutingAssembly().FullName).Take(aes.BlockSize / 8).ToArray();
     aes.Mode    = System.Security.Cryptography.CipherMode.CBC;
     aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
 }
Esempio n. 11
0
        } // End Function Encrypt

        public string DeCrypt(string encryptedInput)
        {
            string returnValue = null;

            if (string.IsNullOrEmpty(encryptedInput))
            {
                throw new System.ArgumentNullException("encryptedInput", "encryptedInput may not be string.Empty or NULL, because these are invid values.");
            }

            using (System.Security.Cryptography.Aes objRijndael = System.Security.Cryptography.Aes.Create())
            {
                byte[] baCipherTextBuffer     = HexStringToByteArray(encryptedInput);
                byte[] baDecryptionKey        = HexStringToByteArray(this.m_key);
                byte[] baInitializationVector = HexStringToByteArray(this.m_iv);

                // This is where the message would be transmitted to a recipient
                // who already knows your secret key. Optionally, you can
                // also encrypt your secret key using a public key algorithm
                // and pass it to the mesage recipient along with the RijnDael
                // encrypted message.
                //Get a decryptor that uses the same key and IV as the encryptor.
                using (System.Security.Cryptography.ICryptoTransform transform = objRijndael.CreateDecryptor(baDecryptionKey, baInitializationVector))
                {
                    //Now decrypt the previously encrypted message using the decryptor
                    // obtained in the above step.
                    using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(baCipherTextBuffer))
                    {
                        using (System.Security.Cryptography.CryptoStream csDecrypt =
                                   new System.Security.Cryptography.CryptoStream(
                                       msDecrypt
                                       , transform
                                       , System.Security.Cryptography.CryptoStreamMode.Read)
                               )
                        {
                            byte[] baPlainTextBuffer = new byte[baCipherTextBuffer.Length];

                            //Read the data out of the crypto stream.
                            csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length);

                            //Convert the byte array back into a string.
                            returnValue = this.m_encoding.GetString(baPlainTextBuffer);
                            System.Array.Clear(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
                            baPlainTextBuffer = null;

                            if (!string.IsNullOrEmpty(returnValue))
                            {
                                returnValue = returnValue.Trim('\0');
                            }

                            csDecrypt.Clear();
                        } // End Using csDecrypt
                    }     // End Using msDecrypt
                }         // End Using transform
            }             // End Using aes

            return(returnValue);
        } // End Function DeCrypt
Esempio n. 12
0
        /// <summary>
        /// 加密(二进制)
        /// </summary>
        /// <param name="data">需要加密的数据。</param>
        /// <param name="password">密钥</param>
        /// <returns>返回加密后的数据。</returns>
        public static byte[] Encrypt(byte[] data, byte[] password)
        {
#if netcore
            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
#else
            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create("AES");
#endif
            aes.Mode = System.Security.Cryptography.CipherMode.ECB;
            aes.Key  = password;
            System.Security.Cryptography.ICryptoTransform encryptor = aes.CreateEncryptor();
            return(encryptor.TransformFinalBlock(data, 0, data.Length));
        }
Esempio n. 13
0
 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));
         }
     }
 }
 public static void GenerateKeyAndInitializationVectorIfNeeded()
 {
     if (!File.Exists(AES_PROPERTIES_PATH_IV) || !File.Exists(AES_PROPERTIES_PATH_KEY))
     {
         using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
         {
             AESProperties aesProperties = new AESProperties {
                 InitializationVector = aesAlg.IV, Key = aesAlg.Key
             };
             WriteToBinaryFile(AES_PROPERTIES_PATH_IV, aesProperties.InitializationVector);
             WriteToBinaryFile(AES_PROPERTIES_PATH_KEY, aesProperties.Key);
         }
     }
 }
Esempio n. 15
0
        } // End Function Encrypt

        public static string DeCrypt(string strEncryptedInput)
        {
            string strReturnValue = null;

            if (string.IsNullOrEmpty(strEncryptedInput))
            {
                throw new System.ArgumentNullException("strEncryptedInput", "strEncryptedInput may not be string.Empty or NULL, because these are invid values.");
            }

            // System.Text.Encoding enc = System.Text.Encoding.ASCII;
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                byte[] baCipherTextBuffer = HexStringToByteArray(strEncryptedInput);


                byte[] baDecryptionKey        = HexStringToByteArray(strKey);
                byte[] baInitializationVector = HexStringToByteArray(strIV);

                // This is where the message would be transmitted to a recipient
                // who already knows your secret key. Optionally, you can
                // also encrypt your secret key using a public key algorithm
                // and pass it to the mesage recipient along with the RijnDael
                // encrypted message.
                // Get a decryptor that uses the same key and IV as the encryptor.
                System.Security.Cryptography.ICryptoTransform ifaceAESdecryptor = aes.CreateDecryptor(baDecryptionKey, baInitializationVector);

                // Now decrypt the previously encrypted message using the decryptor
                // obtained in the above step.
                System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(baCipherTextBuffer);
                System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, ifaceAESdecryptor, System.Security.Cryptography.CryptoStreamMode.Read);

                // byte[] baPlainTextBuffer
                // byte[] baPlainTextBuffer = new byte[baCipherTextBuffer.Length;
                byte[] baPlainTextBuffer = new byte[baCipherTextBuffer.Length + 1];

                //Read the data out of the crypto stream.
                csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length);

                //Convert the byte array back into a string.
                strReturnValue = enc.GetString(baPlainTextBuffer);
                if (!string.IsNullOrEmpty(strReturnValue))
                {
                    strReturnValue = strReturnValue.Trim('\0');
                }
            }
            return(strReturnValue);
        } // End Function DeCrypt
Esempio n. 16
0
        } // End Function GenerateKey

        public static string Encrypt(string strPlainText)
        {
            byte[] baCipherTextBuffer = null;

            // System.Text.Encoding enc = System.Text.Encoding.ASCII;
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                byte[] baPlainTextBuffer      = null;
                byte[] baEncryptionKey        = null;
                byte[] baInitializationVector = null;

                // Create a new key and initialization vector.
                // aes.GenerateKey()
                // aes.GenerateIV()
                aes.Key = HexStringToByteArray(strKey);
                aes.IV  = HexStringToByteArray(strIV);


                // Get the key and initialization vector.
                baEncryptionKey        = aes.Key;
                baInitializationVector = aes.IV;
                // strKey = ByteArrayToHexString(baEncryptionKey)
                // strIV = ByteArrayToHexString(baInitializationVector)

                // Get an encryptor.
                System.Security.Cryptography.ICryptoTransform ifaceAESencryptor = aes.CreateEncryptor(baEncryptionKey, baInitializationVector);

                // Encrypt the data.
                using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, ifaceAESencryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        //Convert the data to a byte array.
                        baPlainTextBuffer = enc.GetBytes(strPlainText);

                        //Write all data to the crypto stream and flush it.
                        csEncrypt.Write(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
                        csEncrypt.FlushFinalBlock();

                        //Get encrypted array of bytes.
                        baCipherTextBuffer = msEncrypt.ToArray();
                    }
                }
            }
            return(ByteArrayToHexString(baCipherTextBuffer));
        } // End Function Encrypt
        public static string Decrypt(string cipherString)
        {
            byte[] cipherText = Convert.FromBase64String(cipherString);
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (aesProperties.Key == null || aesProperties.Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (aesProperties.InitializationVector == null || aesProperties.InitializationVector.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 = aesProperties.Key;
                aesAlg.IV  = aesProperties.InitializationVector;

                // 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 (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, decryptor, System.Security.Cryptography.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);
        }
Esempio n. 18
0
        } // End Sub SetIV

        public static string GenerateKey()
        {
            byte[] bIV;
            byte[] bKey;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.GenerateKey();
                aes.GenerateIV();

                bIV  = aes.IV;
                bKey = aes.Key;
                // aes.Clear();
            } // End Using aes

            return("IV: " + ByteArrayToHexString(bIV) + System.Environment.NewLine + "Key: " + ByteArrayToHexString(bKey));
        } // End Function GenerateKey
        public static string Encrypt(string plainText)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (aesProperties.Key == null || aesProperties.Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (aesProperties.InitializationVector == null || aesProperties.InitializationVector.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            // Create an Aes object
            // with the specified key and IV.
            byte[] encrypted = null;

            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = aesProperties.Key;
                aesAlg.IV  = aesProperties.InitializationVector;

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

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return(Convert.ToBase64String(encrypted));
        }
Esempio n. 20
0
        //복호화
        public static byte[] Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
        {
            byte[] plainText;
            // Create an Aes object
            // with the specified key and IV.
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.BlockSize = 128;
                aesAlg.Key       = Key;
                aesAlg.IV        = IV;
                aesAlg.Mode      = System.Security.Cryptography.CipherMode.CBC;
                aesAlg.Padding   = System.Security.Cryptography.PaddingMode.PKCS7;

                System.Security.Cryptography.ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                plainText = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
            }

            return(plainText);
        }
Esempio n. 21
0
 public static string Decrypt2(string cipherText, string encryptionKey)
 {
     byte[] cipherBytes = Convert.FromBase64String(cipherText);
     using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
     {
         System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.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 (System.IO.MemoryStream ms = new System.IO.MemoryStream())
         {
             using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
             {
                 cs.Write(cipherBytes, 0, cipherBytes.Length);
                 cs.Close();
             }
             cipherText = System.Text.Encoding.Unicode.GetString(ms.ToArray());
         }
     }
     return(cipherText);
 }
Esempio n. 22
0
        public AESEncryptionProvider(string password)
        {
            mAES = System.Security.Cryptography.Aes.Create();
            mAES.Mode = System.Security.Cryptography.CipherMode.CBC;
            mAES.Padding = System.Security.Cryptography.PaddingMode.None;

            // NOTE: Following settings match the hardcoded 7z922 settings, which make some questionable choices:
            //
            // - The password salt is not used in the 7z encoder. Should not be a problem unless you create a huge
            //   amount of 7z archives all using the same password.
            //
            // - The RNG for the seed (aka IV) has some questionable choices for seeding itself, but it does
            //   include timing variations over a loop of 1k iterations, so it is not completely predictable.
            //
            // - The seed (aka IV) uses only 8 of 16 bytes, meaning 50% are zeroes. This does not make cracking
            //   the password any easier but may cause problems in AES security, but I'm no expert here.
            //
            // - Setting the NumCyclesPower to a fixed value is ok, raising it just makes brute forcing the
            //   password a bit more expensive, but doing half a million SHA1 iterations is reasonably slow.
            //
            // So while some choices are questionable they still don't allow any obvious attack. If you are going
            // to store highly sensitive material you probably shouldn't rely on 7z encryption alone anyways.
            // (Not to mention you shouldn't be using this library because its totally not finished ;-)
            //

            mNumCyclesPower = 19; // 7z922 has this parameter fixed
            mSalt = new byte[0]; // 7z922 does not use a salt (?)
            mSeed = new byte[8]; // 7z922 uses only 8 byte seeds (?)

            // 7z922 uses a questionable RNG hack, we will just use the standard .NET cryptography RNG
            using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create())
            {
                rng.GetBytes(mSalt);
                rng.GetBytes(mSeed);
            }

            mSeed16 = new byte[16];
            Buffer.BlockCopy(mSeed, 0, mSeed16, 0, mSeed.Length);

            mKey = master._7zip.Legacy.AesDecoderStream.InitKey(mNumCyclesPower, mSalt, Encoding.Unicode.GetBytes(password));
        }
Esempio n. 23
0
        public bool Encrypt(byte[] src, out byte[] dst)
        {
            dst = new byte[src.Length];

            if (key == null)
            {
                key = GetAssemblyHash();
            }

            System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create();
            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
            aes.Key = key;

            System.Security.Cryptography.ICryptoTransform ict = aes.CreateEncryptor();

            for (int l = 0; l < src.Length;)
            {
                l += ict.TransformBlock(src, l, l + bufferSize < src.Length? bufferSize: src.Length - l, dst, l);
            }

            return(true);
        }
Esempio n. 24
0
        /// <summary>
        /// Construct a keyed universal hash function.
        ///
        /// An instance of a universal hash function needs to store on the order of RandomKeyVectorLengthInBytes values upon construction,
        /// so it is best not to initialize this function for large strings (e.g., those over 32k).
        ///
        /// </summary>
        /// <param name="keyOf16Or24Or32Bytes">A key that should not be known to those who might try to create collisions, provided as an array of 16, 24, or 32 bytes.</param>
        /// <param name="randomKeyVectorLengthInBytes">The length of the random key vector used for hashing.  Should be twice the length of the longest value you expect to hash,
        /// unless you hash values bigger than you would want to keep in memory.  If hashing a value longer than this, the universal hash properties may not hold.</param>
        public UniversalHashFunction(byte[] keyOf16Or24Or32Bytes, int randomKeyVectorLengthInBytes = 256)
        {
            int numberOfRandomBytesToGenerate = SetVectorLengthAndGetNumberOfRandomBytesNeeded(randomKeyVectorLengthInBytes);

            // Generate enough random bytes to fill the RandomKeyVector and 4 extra for the InitialRandomKey
            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Key  = keyOf16Or24Or32Bytes;
                aes.IV   = new byte[16];
                aes.Mode = System.Security.Cryptography.CipherMode.CBC;

                // Encrypt a null message with the key using CBC and InitializationVector=0
                byte[] pseudoRandomBytes;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ciphertext, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        if (numberOfRandomBytesToGenerate % 16 != 0)
                        {
                            // Round to next 128-bit boundary since we're using AES 128-bit blocks to generate randomness
                            numberOfRandomBytesToGenerate += 16 - (numberOfRandomBytesToGenerate % 16);
                        }
                        cs.Write(new byte[numberOfRandomBytesToGenerate], 0, numberOfRandomBytesToGenerate);
                        // Ensure all bytes are flushed.
                    }
                    pseudoRandomBytes = ciphertext.ToArray();
                }

                // Create the random key vector and fill it with random bytes
                _randomKeyVector = new ulong[randomKeyVectorLengthInBytes / 8];
                for (int i = 0; i < _randomKeyVector.Length; i++)
                {
                    _randomKeyVector[i] = BitConverter.ToUInt64(pseudoRandomBytes, i * 8);
                }
                // Fill the initial random key with the last remaining 8 bytes
                _initialRandomKey = BitConverter.ToUInt64(pseudoRandomBytes, randomKeyVectorLengthInBytes);
            }
        }
Esempio n. 25
0
        public static void StoreCredentials( string _Name, string _P )
        {
            using (System.Security.Cryptography.Aes myAes = System.Security.Cryptography.Aes.Create())
            {
                byte[] key = myAes.Key;
                byte[] iv = myAes.IV;

                byte[] encryptedName = AesHelper.EncryptStringToBytes_Aes(_Name, key, iv);
                byte[] encryptedP = AesHelper.EncryptStringToBytes_Aes(_P, key, iv);

                // Format: 
                // [4 bytes: key size in bytes]
                // [4 bytes: iv size in bytes]
                // [4 bytes: name size]
                // [4 bytes: p size]
                // [n bytes: key (n==keysize)]
                // [n bytes: iv (n==ivsize)]
                // [n bytes: name (n==namesize)]
                // [n bytes: p (n==psize)]

                byte[] finalData = new byte[16 + key.Length + iv.Length + encryptedName.Length + encryptedP.Length];

                BitConverter.GetBytes(key.Length).CopyTo(finalData, 0);
                BitConverter.GetBytes(iv.Length).CopyTo(finalData, 4);
                BitConverter.GetBytes(encryptedName.Length).CopyTo(finalData, 8);
                BitConverter.GetBytes(encryptedP.Length).CopyTo(finalData, 12);
                key.CopyTo(finalData, 16);
                iv.CopyTo(finalData, 16 + key.Length);
                encryptedName.CopyTo(finalData, 16 + key.Length + iv.Length);
                encryptedP.CopyTo(finalData, 16 + key.Length + iv.Length + encryptedName.Length);

                string dataString = Convert.ToBase64String(finalData);
                Properties.Settings.Default.accountInfo = dataString;
                Properties.Settings.Default.Save();
            }
        }
Esempio n. 26
0
        static void KeyGenConsole()
        {
            Console.WriteLine("Which?");
            // Console.WriteLine("1. RSA");
            Console.WriteLine("2. AES");
            Console.Write("> ");
            string input = Console.ReadLine();

            switch (input)
            {
            case "1":
                // TODO
                break;

            case "2":
                System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create();
                aesAlg.GenerateKey();
                byte[] key = aesAlg.Key;
                Util.SaveFile.WriteFile("./AES.-2.key", key);
                aesAlg.GenerateKey();
                Util.SaveFile.WriteFile("./AES.-1.key", aesAlg.Key);
                break;
            }
        }
Esempio n. 27
0
        public static string Decrypt(string cipherText, string encryptionKey)
        {
            try
            {
                if (cipherText == null)
                {
                    return(string.Empty);
                }

                byte[] cipherBytes = HttpServerUtility.UrlTokenDecode(cipherText.ToString());

                using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
                {
                    System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.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 (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        cipherText = System.Text.Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
            }
            catch
            {
                cipherText = string.Empty;
            }
            return(cipherText.ToString());
        }
Esempio n. 28
0
        } // End Function GenerateKey

        public string Encrypt(string plainText)
        {
            string retValue = null;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                byte[] baCipherTextBuffer     = null;
                byte[] baPlainTextBuffer      = null;
                byte[] baEncryptionKey        = HexStringToByteArray(this.m_key);
                byte[] baInitializationVector = HexStringToByteArray(this.m_iv);


                aes.Key = baEncryptionKey;
                aes.IV  = baInitializationVector;


                //Get an encryptor.
                using (System.Security.Cryptography.ICryptoTransform transform =
                           aes.CreateEncryptor(baEncryptionKey, baInitializationVector))
                {
                    //Encrypt the data.
                    using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream csEncrypt =
                                   new System.Security.Cryptography.CryptoStream(
                                       msEncrypt
                                       , transform
                                       , System.Security.Cryptography.CryptoStreamMode.Write
                                       )
                               )
                        {
                            //Convert the data to a byte array.
                            baPlainTextBuffer = this.m_encoding.GetBytes(plainText);

                            //Write all data to the crypto stream and flush it.
                            csEncrypt.Write(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
                            csEncrypt.FlushFinalBlock();

                            //Get encrypted array of bytes.
                            baCipherTextBuffer = msEncrypt.ToArray();
                            csEncrypt.Clear();
                        } // End Using csEncrypt
                    }     // End Using msEncrypt
                }         // End Using transform


                retValue = ByteArrayToHexString(baCipherTextBuffer);

                System.Array.Clear(baCipherTextBuffer, 0, baCipherTextBuffer.Length);
                System.Array.Clear(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
                System.Array.Clear(baEncryptionKey, 0, baEncryptionKey.Length);
                System.Array.Clear(baInitializationVector, 0, baInitializationVector.Length);

                baCipherTextBuffer     = null;
                baPlainTextBuffer      = null;
                baEncryptionKey        = null;
                baInitializationVector = null;
            } // End Using aes

            return(retValue);
        } // End Function Encrypt
Esempio n. 29
0
 public Aes Create()
 {
     return(Aes.Create());
 }
Esempio n. 30
0
        } // End Function Encrypt

        public static string Decrypt(string encryptedInput)
        {
            string returnValue = null;

            if (string.IsNullOrEmpty(encryptedInput))
            {
                return(encryptedInput);
            }

            // System.Text.Encoding enc = System.Text.Encoding.ASCII;
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            byte[] cipherTextBuffer     = HexStringToByteArray(encryptedInput);
            byte[] decryptionKey        = HexStringToByteArray(s_key);
            byte[] initializationVector = HexStringToByteArray(s_IV);

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                // This is where the message would be transmitted to a recipient
                // who already knows your secret key. Optionally, you can
                // also encrypt your secret key using a public key algorithm
                // and pass it to the mesage recipient along with the RijnDael
                // encrypted message.
                //Get a decryptor that uses the same key and IV as the encryptor.
                using (System.Security.Cryptography.ICryptoTransform aesDecryptor = aes.CreateDecryptor(decryptionKey, initializationVector))
                {
                    //Now decrypt the previously encrypted message using the decryptor
                    // obtained in the above step.
                    using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(cipherTextBuffer))
                    {
                        using (System.Security.Cryptography.CryptoStream csDecrypt = new System.Security.Cryptography.CryptoStream(msDecrypt, aesDecryptor, System.Security.Cryptography.CryptoStreamMode.Read))
                        {
                            //Dim baPlainTextBuffer() As Byte
                            //baPlainTextBuffer = New Byte(baCipherTextBuffer.Length) {}
                            byte[] baPlainTextBuffer = new byte[cipherTextBuffer.Length + 1];

                            //Read the data out of the crypto stream.
                            csDecrypt.Read(baPlainTextBuffer, 0, baPlainTextBuffer.Length);

                            //Convert the byte array back into a string.
                            returnValue = enc.GetString(baPlainTextBuffer);
                            if (!string.IsNullOrEmpty(returnValue))
                            {
                                returnValue = returnValue.Trim('\0');
                            }
                        } // End Using csDecrypt
                    }     // End Using msDecrypt
                }         // End Using aesDecryptor
            }             // End Using aes

            System.Array.Clear(cipherTextBuffer, 0, cipherTextBuffer.Length);
            cipherTextBuffer = null;

            System.Array.Clear(decryptionKey, 0, decryptionKey.Length);
            decryptionKey = null;

            System.Array.Clear(initializationVector, 0, initializationVector.Length);
            initializationVector = null;

            return(returnValue);
        } // End Function DeCrypt
Esempio n. 31
0
        } // End Function GenerateKey

        public static string Encrypt(string plainText)
        {
            string retValue = null;

            if (plainText == null)
            {
                return(null);
            }

            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                // Create a new key and initialization vector.
                // aes.GenerateKey();
                // aes.GenerateIV();
                aes.Key = HexStringToByteArray(s_key);
                aes.IV  = HexStringToByteArray(s_IV);


                // Get the key and initialization vector.
                byte[] encryptionKey        = aes.Key;
                byte[] initializationVector = aes.IV;
                // strKey = ByteArrayToHexString(encryptionKey)
                // strIV = ByteArrayToHexString(initializationVector)

                // Get an encryptor.
                using (System.Security.Cryptography.ICryptoTransform aesEncryptor = aes.CreateEncryptor(encryptionKey, initializationVector))
                {
                    //Encrypt the data.
                    using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, aesEncryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                        {
                            //Convert the data to a byte array.
                            byte[] plainTextBuffer = enc.GetBytes(plainText);

                            //Write all data to the crypto stream and flush it.
                            csEncrypt.Write(plainTextBuffer, 0, plainTextBuffer.Length);
                            csEncrypt.FlushFinalBlock();

                            //Get encrypted array of bytes.
                            byte[] cipherTextBuffer = msEncrypt.ToArray();
                            retValue = ByteArrayToHexString(cipherTextBuffer);
                            System.Array.Clear(cipherTextBuffer, 0, cipherTextBuffer.Length);
                            cipherTextBuffer = null;

                            System.Array.Clear(plainTextBuffer, 0, plainTextBuffer.Length);
                            plainTextBuffer = null;
                        } // End Using csEncrypt
                    }     // End Using msEncrypt
                }         // End Using aesEncryptor

                System.Array.Clear(encryptionKey, 0, encryptionKey.Length);
                encryptionKey = null;

                System.Array.Clear(initializationVector, 0, initializationVector.Length);
                initializationVector = null;
            } // End Using aes

            return(retValue);
        } // End Function Encrypt
Esempio n. 32
0
 public EncryptionHelper(byte[] key)
 {
     aes = System.Security.Cryptography.Aes.Create();
     aes.Key = key;
     aes.IV = System.Text.UTF8Encoding.UTF8.GetBytes(System.Reflection.Assembly.GetExecutingAssembly().FullName).Take(aes.BlockSize/8).ToArray();
     aes.Mode = System.Security.Cryptography.CipherMode.CBC;
     aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
 }