CreateEncryptor() 공개 메소드

public CreateEncryptor ( ) : ICryptoTransform
리턴 ICryptoTransform
예제 #1
0
파일: Program.cs 프로젝트: sgopisetty/AES
        private static string GetEncryptedString(byte[] OriginalKeyInByteArr, byte[] IVBytes, string PlainText)
        {
            byte[] encrypted;
            AesCryptoServiceProvider myAes = new AesCryptoServiceProvider();
            myAes.Key = OriginalKeyInByteArr;
            myAes.IV = IVBytes;

            AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider();
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(myAes.Key, myAes.IV);
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(PlainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }

            var encryptedInBase64 = Convert.ToBase64String(encrypted);
            var encryptedInHex = GetHexStringFromBytes(encrypted);
            return encryptedInHex;
        }
예제 #2
0
        void Button1Click(object sender, EventArgs e)
        {
            //if (save_encrypt.ShowDialog() == DialogResult.OK)
            //{
                FileStream encrypt_file = File.Create(openfile.FileName+"_encrypt");
                AesCryptoServiceProvider AES_ALGORITHM = new AesCryptoServiceProvider();
                CryptoStream csEncrypt = new CryptoStream(encrypt_file, AES_ALGORITHM.CreateEncryptor(),CryptoStreamMode.Write);
                StreamWriter swEncStream = new StreamWriter(csEncrypt);
                StreamReader srFile = new StreamReader(textBox1.Text);
                string currLine = srFile.ReadLine();
                while(currLine != null)
                {
                    swEncStream.WriteLine(currLine);
                    currLine = srFile.ReadLine();
                }

                srFile.Close();
                swEncStream.Flush();
                swEncStream.Close();

                FileStream keyfile = File.Create(openfile.FileName+".key");
                BinaryWriter binFile = new BinaryWriter(keyfile);
                key = AES_ALGORITHM.Key;
                iv = AES_ALGORITHM.IV;
                binFile.Write(AES_ALGORITHM.Key);
                binFile.Write(AES_ALGORITHM.IV);
                binFile.Flush();
                binFile.Close();

            //}
        }
예제 #3
0
        private static byte[] AliceSendData(string msg)
        {
            Console.WriteLine(string.Format("Alice Send Msg: {0}", msg));
            byte[] rawdata = Encoding.UTF8.GetBytes(msg);
            byte[] encryptedData = null;
            using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey))
            using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob))
            {
                byte[] symmkey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);

                Console.WriteLine(string.Format("Alice Create this symmtric key with {0}", Convert.ToBase64String(symmkey)));

                var aes = new AesCryptoServiceProvider();
                aes.Key = symmkey;
                aes.GenerateIV();
                using (ICryptoTransform encryptor = aes.CreateEncryptor())
                using (MemoryStream ms = new MemoryStream())
                {
                    var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
                    ms.Write(aes.IV, 0, aes.IV.Length);
                    cs.Write(rawdata, 0, rawdata.Length);
                    cs.Close();
                    encryptedData = ms.ToArray();
                }
                aes.Clear();
            }

            Console.WriteLine(Convert.ToBase64String(encryptedData));
            return encryptedData;
        }
예제 #4
0
        public static byte[] Encrypt(byte[] data, string privateKey)
        {
            //  We hash the private key string to ensure we have a key with the correct
            //  number of bytes.
            var privateKeyHash = HashKey(privateKey);

            using (var provider = new AesCryptoServiceProvider())
            {
                provider.Key = privateKeyHash;
                provider.Mode = CipherMode.CBC;
                provider.Padding = PaddingMode.PKCS7;

                using (var ms = new MemoryStream())
                {
                    ms.Write(provider.IV, 0, 16);
                    using (var encryptor = provider.CreateEncryptor())
                    {
                        using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                        {
                            cs.Write(data, 0, data.Length);
                            cs.FlushFinalBlock();
                        }
                        return ms.ToArray();
                    }
                }
            }
        }
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="data">待加密数据</param>
        /// <param name="key">密钥</param>
        /// <returns>密文字节数组</returns>
        public static byte[] AesEncrypt(string data, byte[] key)
        {
            byte[] result;

            using (SymmetricAlgorithm algorithm = new AesCryptoServiceProvider())
            {
                algorithm.Mode = CipherMode.ECB;
                algorithm.Padding = PaddingMode.PKCS7;
                using (ICryptoTransform transform = algorithm.CreateEncryptor(key, key))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (Stream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                        {
                            using (StreamWriter writer = new StreamWriter(cs))
                            {
                                writer.Write(data);
                            }
                            result = ms.ToArray();
                        }
                    }
                }
            }

            return result;
        }
        string CreateEncryptedSensitiveVariablesFile(string fileName, string encryptionPassword, Dictionary<string, string> variables)
        {
            using (var algorithm = new AesCryptoServiceProvider
            {
                Key = Calamari.Deployment.SensitiveVariables.GetEncryptionKey(encryptionPassword)
            })
            using (var encryptor = algorithm.CreateEncryptor())
            using (var encryptedTextStream = new MemoryStream())
            using (var jsonStream = new MemoryStream())
            using (var streamWriter = new StreamWriter(jsonStream, Encoding.UTF8))
            using (var jsonWriter = new JsonTextWriter(streamWriter))
            {
                using (var cryptoStream = new CryptoStream(encryptedTextStream, encryptor, CryptoStreamMode.Write))
                {
                    var serializer = new JsonSerializer();
                    serializer.Serialize(jsonWriter, variables);
                    jsonWriter.Flush();
                    streamWriter.Flush();

                    var jsonBytes = jsonStream.ToArray();
                    cryptoStream.Write(jsonBytes, 0, jsonBytes.Length);
                }

                var encryptedBytes = encryptedTextStream.ToArray();
                fileSystem.OverwriteFile(fileName, Convert.ToBase64String(encryptedBytes));

                return Convert.ToBase64String(algorithm.IV);
            }
        }
예제 #7
0
        /// <summary>
        /// AES Encryption
        /// </summary>
        public static string Encrypt(string clearText)
        {
            if (clearText == null) return null;
            // AesCryptoServiceProvider
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize = 128;

            aes.GenerateIV();
            aes.Key = Encoding.UTF8.GetBytes(AesKey);
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            // Convert string to byte array
            byte[] src = Encoding.Unicode.GetBytes(clearText);

            // encryption
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // Convert byte array to Base64 strings
                return Convert.ToBase64String(aes.IV) + Convert.ToBase64String(dest);
            }
        }
예제 #8
0
        public static string Encrypt(long id)
        {
            byte[] encrypted;

            using (var aesAlg = new AesCryptoServiceProvider())
            {
                aesAlg.Key = AesCryptoServiceProvider.Key;
                aesAlg.IV = AesCryptoServiceProvider.IV;

                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(id);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            return Convert.ToBase64String(encrypted);
        }
예제 #9
0
 protected override string EncryptByBlocks(byte[] key,
     List<byte> plainText)
 {
     var cipherText = new StringBuilder();
     if (plainText.Count % BlockSize == 0)
     {
         AddDummyBlock(plainText);
     }
     using (var aes = new AesCryptoServiceProvider())
     {
         aes.BlockSize = BlockSize * 8;
         aes.KeySize = KeySize * 8;
         aes.Padding = PaddingMode.None;
         aes.Key = key;
         aes.GenerateIV();
         cipherText.Append(BytesToHexString(aes.IV));
         using (var encr = aes.CreateEncryptor())
         {
             while (plainText.Count != 0)
             {
                 var block = DetachBlock(plainText);
                 if (block.Length < BlockSize)
                 {
                     block = CompleteBlock(block);
                 }
                 var encrypted = new byte[BlockSize];
                 encr.TransformBlock(block, 0, BlockSize, encrypted, 0);
                 cipherText.Append(BytesToHexString(encrypted));
                 aes.IV = encrypted;
             }
         }
     }
     return cipherText.ToString();
 }
        public byte[] Encription(string message, byte[] bobPubKeyBlob)
        {
            byte[] rawData = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;

            using (var aliceAlgorithm = new ECDiffieHellmanCng(privKey))
            using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob,
                  CngKeyBlobFormat.EccPublicBlob))
            {
                byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
                using (var aes = new AesCryptoServiceProvider())
                {
                    aes.Key = symmKey;
                    aes.GenerateIV();
                    using (ICryptoTransform encryptor = aes.CreateEncryptor())
                    using (MemoryStream ms = new MemoryStream())
                    {
                        // create CryptoStream and encrypt data to send
                        var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);

                        // write initialization vector not encrypted
                        ms.Write(aes.IV, 0, aes.IV.Length);
                        cs.Write(rawData, 0, rawData.Length);
                        cs.Close();
                        encryptedData = ms.ToArray();
                    }
                    aes.Clear();
                }
            }
            return encryptedData;
        }
예제 #11
0
        /// <summary>
        /// Encryptes a string using 3DES
        /// </summary>
        /// <param name="data">The data to encrypt</param>
        /// <param name="key">The key to use</param>
        /// <param name="IV">Initialization Vector</param>
        /// <returns>An encrypted, base64 encoded string</returns>
        public static byte[] EncryptAES(string data, byte[] key, byte[] IV)
        {
            string retVal = string.Empty;

            var tsp = new System.Security.Cryptography.AesCryptoServiceProvider();

            // default padding and mode
            tsp.Mode = CipherMode.CBC;
            tsp.Padding = PaddingMode.PKCS7;

            // get a crypt transform interface
            ICryptoTransform ct = tsp.CreateEncryptor(key, IV);

            // setup a memory stream
            MemoryStream ms = new MemoryStream();
            using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write))
            {
                // write the string through the crypto stream
                byte[] db = System.Text.Encoding.ASCII.GetBytes(data);
                cs.Write(db, 0, db.Length);

                // flush
                cs.FlushFinalBlock();

                // convert the data in the memory stream to base64 text
                ms.Seek(0, SeekOrigin.Begin);

                var edata = ms.ToArray();
                return edata;
            }
        }
 /// <summary>
 /// Encrypts a plainText string using the system key retrieved from the Web Service
 /// </summary>
 /// <param name="plainText">String to encrypt</param>
 /// <returns>EncryptedData with encrypted string and IV used</returns>
 public EncryptedData Encrypt(string plainText)
 {
     lock (_locker)
     {
         using (var crypto = new AesCryptoServiceProvider())
         {
             try
             {
                 UnprotectKey();
                 // Create the streams used for encryption. 
                 using (MemoryStream msEncrypt = new MemoryStream())
                 using (var encryptor = crypto.CreateEncryptor(_key, crypto.IV))
                 using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                 {
                     using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                     {
                         //Write all data to the stream.
                         swEncrypt.Write(plainText);
                     }
                     return new EncryptedData(msEncrypt.ToArray(), crypto.IV);
                 }
             }
             finally
             {
                 ProtectKey();
             }
         }
     }
 }
예제 #13
0
        /// <summary>
        /// uses the AES FIPS-140 compliant algorithm to encrypt a string
        /// </summary>
        /// <param name="plainText">the text to encrypt</param>
        /// <param name="passPhrase">the pass phase to do the encryption</param>
        /// <param name="salt">a salt value to ensure ciphertext using the same text/password is different</param>
        /// <param name="iterations">number of iterations to derive the key (higher is slower but more secure) - optional parameter with a default of 1000</param>
        /// <returns></returns>
        public static String EncryptAES(String plainText, String passPhrase, String salt, int iterations = 1000)
        {
            VerifyAesSettings(passPhrase, salt);

            byte[] saltBytes = Encoding.ASCII.GetBytes(salt);
            var aesProvider = new AesCryptoServiceProvider();
            var derivedBytes = new Rfc2898DeriveBytes(passPhrase, saltBytes, iterations);
            Byte[] derivedKey = derivedBytes.GetBytes(32); // 256 bits
            Byte[] derivedInitVector = derivedBytes.GetBytes(16); // 128 bits
            Byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            aesProvider.KeySize = 256;
            aesProvider.Padding = PaddingMode.ISO10126;
            aesProvider.Mode = CipherMode.CBC;

            ICryptoTransform encryptor = aesProvider.CreateEncryptor(derivedKey, derivedInitVector);
            var memStream = new MemoryStream();
            var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write);

            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            Byte[] cipherTextBytes = memStream.ToArray();

            memStream.Close();
            cryptoStream.Close();

            return Convert.ToBase64String(cipherTextBytes);
        }
예제 #14
0
 public void SetUp()
 {
     using ( AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider() ) {
         m_Encryptor = aesAlg.CreateEncryptor();
         m_Decryptor = aesAlg.CreateDecryptor();
     }
 }
예제 #15
0
        public void Encrypt(string filename)
        {
            FileStream fsInput = new FileStream(filename, FileMode.Open, FileAccess.Read);
            FileStream fsOutput = new FileStream(filename + ".crypt", FileMode.Create, FileAccess.Write);
            AesCryptoServiceProvider Aes = new AesCryptoServiceProvider();

            Aes.KeySize = 128;
            Aes.GenerateIV();
            Aes.GenerateKey();

            byte[] output = _algorithm_asym.Encrypt(Aes.Key, false);
            fsOutput.Write(output, 0, 256);
            output = _algorithm_asym.Encrypt(Aes.IV, false);
            fsOutput.Write(output, 0, 256);

            ICryptoTransform encrypt = Aes.CreateEncryptor();
            CryptoStream cryptostream = new CryptoStream(fsOutput, encrypt, CryptoStreamMode.Write);

            byte[] bytearrayinput = new byte[fsInput.Length - 1];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

            fsInput.Close();
            fsOutput.Close();
        }
        /// <summary>
        /// AES encryption
        /// </summary>
        public string Encrypt(string text)
        {
            // AES cryptographic service provider
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize = 128;
           
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            aes.IV = Encoding.UTF8.GetBytes(AesIV);
            aes.Key = Encoding.UTF8.GetBytes(AesKey);

            // String → byte
            byte[] src = Encoding.Unicode.GetBytes(text);

            //encryption
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // byte→Base64
                return Convert.ToBase64String(dest);
            }
        }
예제 #17
0
파일: AES.cs 프로젝트: yashodhank/QuasarRAT
        public static byte[] Encrypt(byte[] input, byte[] key)
        {
            if (key == null || key.Length == 0) throw new Exception("Key can not be empty.");

            using (var md5 = new MD5CryptoServiceProvider())
            {
                key = md5.ComputeHash(key);
            }

            byte[] data = input, encdata = new byte[0];

            try
            {
                using (var ms = new MemoryStream())
                {
                    using (var aesProvider = new AesCryptoServiceProvider() { Key = key })
                    {
                        aesProvider.GenerateIV();

                        using (var cs = new CryptoStream(ms, aesProvider.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            ms.Write(aesProvider.IV, 0, aesProvider.IV.Length); // write first 16 bytes IV, followed by encrypted message
                            cs.Write(data, 0, data.Length);
                        }
                    }

                    encdata = ms.ToArray();
                }
            }
            catch
            {
            }
            return encdata;
        }
예제 #18
0
 public static byte[] EncryptString(byte[] toEncrypt, byte[] encryptionKey)
 {
     if (encryptionKey == null || encryptionKey.Length == 0) throw new ArgumentException("encryptionKey");
     using (var provider = new AesCryptoServiceProvider())
     {
         provider.Key = encryptionKey;
         provider.Mode = CipherMode.CBC;
         provider.Padding = PaddingMode.PKCS7;
         using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV))
         {
             using (var ms = new MemoryStream())
             {
                 using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                 {
                     cs.Write(toEncrypt, 0, toEncrypt.Length);
                     cs.FlushFinalBlock();
                     var retVal = new byte[16 + ms.Length];
                     provider.IV.CopyTo(retVal, 0);
                     ms.ToArray().CopyTo(retVal, 16);
                     return retVal;
                 }
             }
         }
     }
 }
예제 #19
0
        public static void EncryptAndUpload(string file, string awsPath, string key)
        {
            if (bool.Parse(ConfigurationManager.AppSettings["ManagedEncryption"]))
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, appKey);
                using (var aes = new AesCryptoServiceProvider())
                {
                    aes.Key = deriveBytes.GetBytes(aes.KeySize / 8);
                    aes.IV = deriveBytes.GetBytes(aes.BlockSize / 8);
                    using (var temp = new FileStream(file + "_encrypted", FileMode.Create))
                    {
                        using (var stream = new CryptoStream(new FileStream(file, FileMode.Open), aes.CreateEncryptor(), CryptoStreamMode.Read))
                        {
                            stream.CopyTo(temp);
                        }
                    }

                    UploadFile(file + "_encrypted", awsPath);

                    File.Delete(file + "_encrypted");
                }
            }
            else
                UploadFile(file, awsPath);
        }
예제 #20
0
        public static byte[] Protect(byte[] encryptionKey, byte[] validationKey, byte[] initializationVector, byte[] plainText)
        {
            using (var provider = new AesCryptoServiceProvider())
            {
                using (ICryptoTransform transform = provider.CreateEncryptor(encryptionKey, initializationVector))
                {
                    using (var ms = new MemoryStream())
                    {
                        ms.Write(initializationVector, 0, initializationVector.Length);
                        using (var cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                        {
                            // Encrypted payload
                            cryptoStream.Write(plainText, 0, plainText.Length);
                            cryptoStream.FlushFinalBlock();

                            // Compute signature
                            using (var sha = new HMACSHA256(validationKey))
                            {
                                checked
                                {
                                    byte[] signature = sha.ComputeHash(ms.GetBuffer(), 0, (int)ms.Length);

                                    // Write the signature to the paylod
                                    ms.Write(signature, 0, signature.Length);

                                    // Final bytes
                                    return ms.ToArray();
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #21
0
 public static string AESEncryptor(string plainText, byte[] Key, byte[] IV)
 {
     byte[] data = ASCIIEncoding.ASCII.GetBytes(plainText);
     AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
     string encryptedString = Convert.ToBase64String(aes.CreateEncryptor(Key, IV).TransformFinalBlock(data, 0, data.Length));
     return encryptedString;
 }
 public ICryptoTransform CreateEncryptor(byte[] key, byte[] iv)
 {
     using (var provider = new AesCryptoServiceProvider {Padding = _paddingMode})
     {
         return provider.CreateEncryptor(key, iv);
     }
 }
 public static byte[] EncryptString(string toEncrypt, byte[] encryptionKey)
 {
     if (string.IsNullOrEmpty(toEncrypt)) throw new ArgumentException("toEncrypt");
     if (encryptionKey == null || encryptionKey.Length == 0) throw new ArgumentException("encryptionKey");
     var toEncryptBytes = Encoding.UTF8.GetBytes(toEncrypt);
     using (var provider = new AesCryptoServiceProvider())
     {
         provider.Key = encryptionKey;
         provider.Mode = CipherMode.CBC;
         provider.Padding = PaddingMode.PKCS7;
         using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV))
         {
             using (var ms = new MemoryStream())
             {
                 ms.Write(provider.IV, 0, 16);
                 using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                 {
                     cs.Write(toEncryptBytes, 0, toEncryptBytes.Length);
                     cs.FlushFinalBlock();
                 }
                 return ms.ToArray();
             }
         }
     }
 }
        public static string Request(string requestParams, string devKey, string devIV, string devID) {
            // Create an unencrypted request as an array of bytes
            byte[] request = UTF8Encoding.UTF8.GetBytes(requestParams);
            byte[] key = UTF8Encoding.UTF8.GetBytes(devKey);
            byte[] iv = UTF8Encoding.UTF8.GetBytes(devIV);

            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.Key = key;
            aes.IV = iv;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;

            // Get the transformer from the AES Encryptor
            ICryptoTransform cTransform = aes.CreateEncryptor();

            // Use the transformer to encrypt our request
            byte[] result = cTransform.TransformFinalBlock(request, 0, request.Length);
            aes.Clear();

            // Encode to base64
            string encryptedRequest = Convert.ToBase64String(result, 0, result.Length);

            // Send request to API
            string requestUri = "http://api.blackoutrugby.com/?d=" + devID + "&er=" + encryptedRequest;
            string xmlResponse = getWebResponse(requestUri);
            return XmlToJson(xmlResponse);
        }
예제 #25
0
        public static string encriptar(string texto, string key)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            MD5 md5Hash = MD5.Create();
            string chave = GetMd5Hash(md5Hash, key);
            aes.Key = System.Text.Encoding.UTF8.GetBytes(chave);
            aes.BlockSize = 128;
            aes.IV = System.Text.Encoding.UTF8.GetBytes("6abraswa+hep&#Ac");
            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            byte[] encrypted;

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(texto);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }

            return Convert.ToBase64String(encrypted);
        }
예제 #26
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] AesEncrypt(string data, byte[] key)
        {
            if (key.Length != 16)
            {
                var ex = new Exception("the length of AES ecrypted key must be 16bit.");
                throw ex;
            }
            byte[] result;

            using (SymmetricAlgorithm algorithm = new AesCryptoServiceProvider())
            {
                algorithm.Mode = CipherMode.ECB;
                algorithm.Padding = PaddingMode.PKCS7;
                using (ICryptoTransform transform = algorithm.CreateEncryptor(key, key))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (Stream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                        {
                            using (StreamWriter writer = new StreamWriter(cs))
                            {
                                writer.Write(data);
                            }
                            result = ms.ToArray();
                        }
                    }
                }
            }

            return result;
        }
예제 #27
0
        public static string EncryptString(string message, string passphrase = null)
        {
            if (string.IsNullOrEmpty(message))
            {
                throw new ArgumentException("message is empty!", message);
            }

            if (string.IsNullOrEmpty(passphrase))
            {
                passphrase = ConfigurationManager.AppSettings.Get("Common.Cryptography.DefaultPassPhrase");
            }

            // First hash the passphrase to get a 256bit key
            var sha = new SHA256CryptoServiceProvider();
            var passphraseHash = sha.ComputeHash(Encoding.UTF8.GetBytes(passphrase));

            var aes = new AesCryptoServiceProvider { KeySize = 256, Key = passphraseHash };

            var memoryStream = new MemoryStream();

            var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);

            using (var writer = new StreamWriter(cryptoStream, Encoding.UTF8))
            {
                writer.Write(message);
            }

            var results = memoryStream.ToArray();

            var finalArray = new byte[aes.IV.Length + results.Length];
            Array.Copy(aes.IV, 0, finalArray, 0, aes.IV.Length);
            Array.Copy(results, 0, finalArray, aes.IV.Length, results.Length);

            return HttpServerUtility.UrlTokenEncode(finalArray);
        }
예제 #28
0
        /// <summary>
        /// Encrypt a message using AES in CBC (cipher-block chaining) mode.
        /// </summary>
        /// <param name="plaintext">The message (plaintext) to encrypt</param>
        /// <param name="key">An AES key</param>
        /// <param name="iv">The IV to use or null to use a 0 IV</param>
        /// <param name="addHmac">When set, a SHA256-based HMAC (HMAC256) of 32 bytes using the same key is added to the plaintext
        /// before it is encrypted.</param>
        /// <returns>The ciphertext derived by encrypting the orignal message using AES in CBC mode</returns>
        public static byte[] EncryptAesCbc(byte[] plaintext, byte[] key, byte[] iv = null, bool addHmac = false)
        {
            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.Key = key;
                if (iv == null)
                    iv = NullIv;
                aes.Mode = CipherMode.CBC;
                aes.IV = iv;

                // Encrypt the message with the key using CBC and InitializationVector=0
                byte[] cipherText;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintext, 0, plaintext.Length);
                        if (addHmac)
                        {
                            byte[] hmac = new HMACSHA256(key).ComputeHash(plaintext);
                            cs.Write(hmac, 0, hmac.Length);
                        }
                        cs.Flush();
                    }
                    cipherText = ciphertext.ToArray();
                }

                return cipherText;
            }
        }
예제 #29
0
        private async static Task<byte[]> AliceSendsData(string message)
        {
            Console.WriteLine("Alice send message {0}", message);
            byte[] rawData = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;

            using(var aliceAlgo = new ECDiffieHellmanCng(aliceKey))
            {
                using(CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.GenericPublicBlob))
                {
                    byte[] symmKey = aliceAlgo.DeriveKeyMaterial(bobPubKey);
                    Console.WriteLine("Alice create this symm key with Bobs public key information : {0}", Convert.ToBase64String(symmKey));
                    using(var aes = new AesCryptoServiceProvider())
                    {
                        aes.Key = symmKey;
                        aes.GenerateIV();
                        using(ICryptoTransform encryptor = aes.CreateEncryptor())
                        {
                            using(MemoryStream ms = new MemoryStream())
                            {
                                var cs = new CryptoStream(ms, encryptor,CryptoStreamMode.Write);
                                await ms.WriteAsync(aes.IV, 0, aes.IV.Length);
                                cs.Write(rawData, 0, rawData.Length);
                                cs.Close();
                                encryptedData = ms.ToArray();
                            }
                        }
                        aes.Clear();
                    }
                }
            }
            Console.WriteLine("Alice message is encrypted : {0}", Convert.ToBase64String(encryptedData));
            return encryptedData;
        }
예제 #30
0
 /// <summary>
 /// AES加密
 /// </summary>
 /// <param name="str">待加密字符串</param>
 /// <returns>加密后字符串</returns>
 public static string AesEncrypt(string str)
 {
     try
     {
         string key = AES_KEY;
         //分组加密算法
         AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
         byte[] inputByteArray = Encoding.UTF8.GetBytes(str);//得到需要加密的字节数组
         //设置密钥及密钥向量
         aes.Key = Encoding.UTF8.GetBytes(key);
         //aes.IV = Encoding.UTF8.GetBytes(key);
         aes.Mode = CipherMode.ECB;
         aes.Padding = PaddingMode.PKCS7;
         byte[] cipherBytes = null;
         using (MemoryStream ms = new MemoryStream())
         {
             using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(inputByteArray, 0, inputByteArray.Length);
                 cs.FlushFinalBlock();
                 cipherBytes = ms.ToArray();//得到加密后的字节数组
                 cs.Close();
                 ms.Close();
             }
         }
         return Convert.ToBase64String(cipherBytes);
     }
     catch { }
     return str;
 }
예제 #31
0
        byte[] Transform(byte[] dataBytes, byte[] passwordBytes, bool encrypt)
        {
            /// <summary>Encrypt by using AES-256 algorithm.</summary>
            // Create an instance of the AES class.
            var cipher = new System.Security.Cryptography.AesCryptoServiceProvider();
            // Calculate salt to make it harder to guess key by using a dictionary attack.
            var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes);
            var salt = hmac.ComputeHash(passwordBytes);
            // Generate Secret Key from the password and salt.
            // Note: Set number of iterations to 10 in order for JavaScript example to work faster.
            var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10);
            // Create a encryptor from the existing SecretKey bytes by using
            // 32 bytes (256 bits) for the secret key and
            // 16 bytes (128 bits) for the initialization vector (IV).
            var key = secretKey.GetBytes(32);
            var iv  = secretKey.GetBytes(16);
            // Get cryptor as System.Security.Cryptography.ICryptoTransform class.
            var cryptor = encrypt
                                ? cipher.CreateEncryptor(key, iv)
                                : cipher.CreateDecryptor(key, iv);
            // Create new Input.
            var inputBuffer = new byte[dataBytes.Length];

            // Copy data bytes to input buffer.
            System.Buffer.BlockCopy(dataBytes, 0, inputBuffer, 0, inputBuffer.Length);
            // Create a MemoryStream to hold the output bytes.
            var stream = new System.IO.MemoryStream();
            // Create a CryptoStream through which we are going to be processing our data.
            var mode         = System.Security.Cryptography.CryptoStreamMode.Write;
            var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);

            // Start the crypting process.
            cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
            // Finish crypting.
            cryptoStream.FlushFinalBlock();
            // Convert data from a memoryStream into a byte array.
            var outputBuffer = stream.ToArray();

            // Close both streams.
            stream.Close();
            cryptoStream.Close();
            return(outputBuffer);
        }
예제 #32
0
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainBytes">明文字节数组</param>
        /// <returns>返回密文字节数组</returns>
        public byte[] Encrypt(byte[] plainBytes)
        {
            var aes = new System.Security.Cryptography.AesCryptoServiceProvider();

            aes.Mode    = this.CipherMode;
            aes.Padding = this.PaddingMode;
            aes.Key     = GetKeyBytes();
            if (aes.Mode == CipherMode.CBC && IV == null)
            {
                IV = initIV(keyBytes.Length);
            }
            if (IV != null)
            {
                aes.IV = IV;
            }
            var encryptor = aes.CreateEncryptor();
            var bResult   = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);

            return(bResult);
        }
예제 #33
0
        static public string AesLoginDynamicKey = @"d_&^t";            // 5

        /// <summary>
        /// 문자열을 AES로 암호화 한다
        /// </summary>
        public static string Encrypt(string dynamincKey, string text)
        {
            var comleteAesKey = dynamincKey.Substring(0, 5) + AesKey;

            System.Security.Cryptography.AesCryptoServiceProvider aes = new System.Security.Cryptography.AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize   = 128;
            aes.IV        = Encoding.UTF8.GetBytes(AesIV);
            aes.Key       = Encoding.UTF8.GetBytes(comleteAesKey);
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;

            // 문자열을 바이트형 배열로 변환
            byte[] src = Encoding.Unicode.GetBytes(text);

            // 암호화 한다
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // 바이트형 배열에서 Base64형식의 문자열로 변환
                return(Convert.ToBase64String(dest));
            }
        }