CreateEncryptor() public method

public CreateEncryptor ( ) : ICryptoTransform
return ICryptoTransform
Ejemplo n.º 1
0
        public String EncryptIt(String s)
        {
            Encoding byteEncoder = Encoding.UTF8;

            byte[] rijnKey = byteEncoder.GetBytes("h504lXb1erd4ilw7"); //this is key for encrypt data
            byte[] rijnIV = byteEncoder.GetBytes("4hx7e4bwM15d0CrL"); //this is iv for encrypt data

            String result;
            
            AesManaged rijn = new AesManaged();
            
            //Using AES-128
            rijn.KeySize = 128;
            rijn.BlockSize = 128;

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (ICryptoTransform encryptor = rijn.CreateEncryptor(rijnKey, rijnIV))
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(s);
                        }
                    }
                }
                result = Convert.ToBase64String(msEncrypt.ToArray());
            }
            rijn.Clear();

            return result;
        }
Ejemplo n.º 2
0
        public static string Encrypt(string plainText, string key)
        {
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, _saltSize))
            {
                var saltBytes = keyDerivationFunction.Salt;
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                using (var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes))
                using (var memoryStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    using (var streamWriter = new StreamWriter(cryptoStream))
                        streamWriter.Write(plainText);

                    var cipherTextBytes = memoryStream.ToArray();
                    Array.Resize(ref saltBytes, saltBytes.Length + cipherTextBytes.Length);
                    Array.Copy(cipherTextBytes, 0, saltBytes, _saltSize, cipherTextBytes.Length);

                    return Convert.ToBase64String(saltBytes);
                }
            }
        }
        /// <summary>
        /// Encrypts the plainText input using the given Key.
        /// A 128 bit random salt will be generated and prepended to the ciphertext before it is returned.
        /// </summary>
        /// <param name="plainText">The plain text to encrypt.</param>
        /// <param name="password">The plain text encryption key.</param>
        /// <returns>The salt and the ciphertext</returns>
        public static byte[] Encrypt(byte[] plainText, string password)
        {
            if (plainText == null || plainText.Length == 0) throw new ArgumentNullException("plainText");
            if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");

            // Derive a new Salt, Key, and IV from the password
            using (var keyDerivationFunction = new Rfc2898DeriveBytes(password, SaltSize))
            {
                var saltBytes = keyDerivationFunction.Salt;
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes = keyDerivationFunction.GetBytes(16);

                using (var aesManaged = new AesManaged())
                using (var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes))
                using (var memoryStream = new MemoryStream())
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    using (var streamWriter = new BinaryWriter(cryptoStream))
                    {
                        streamWriter.Write(plainText);
                    }

                    var cipherTextBytes = memoryStream.ToArray();
                    Array.Resize(ref saltBytes, saltBytes.Length + cipherTextBytes.Length);
                    Array.Copy(cipherTextBytes, 0, saltBytes, SaltSize, cipherTextBytes.Length);

                    return saltBytes;
                }
            }
        }
Ejemplo n.º 4
0
        public Secret Encrypt(string plainText)
        {
            Secret result = new Secret();

            using (MemoryStream ms = new MemoryStream())
            {
                using (Aes aesAlg = new AesManaged())
                {
                    aesAlg.Key = _key;
                    result.IV = aesAlg.IV;

                    ICryptoTransform encryptor = aesAlg.CreateEncryptor();

                    using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        byte[] rawPlaintext = Encoding.Unicode.GetBytes(plainText);
                        cs.Write(rawPlaintext, 0, rawPlaintext.Length);
                        cs.FlushFinalBlock();

                        // get the encrypted text
                        ms.Seek(0, SeekOrigin.Begin);
                        byte[] content = new byte[ms.Length];
                        ms.Read(content, 0, content.Length);
                        result.Data = content;
                    }
                }
            }

            return result;
        }
Ejemplo n.º 5
0
    public static bool ForCodeCoverage()
    {
        AesManaged aes = new AesManaged();
        using (ICryptoTransform cte = aes.CreateEncryptor(), ctd = aes.CreateDecryptor())
        {
            byte[] plain1 = new byte[64];
            for (int i = 0; i < plain1.Length; i++)
                plain1[i] = (byte)i;

            byte[] encr1 = cte.TransformFinalBlock(plain1, 0, plain1.Length);
            using(MemoryStream ms = new MemoryStream())
            using(CryptoStream cs = new CryptoStream(ms, ctd, CryptoStreamMode.Write))
            {
                cs.Write(encr1, 0, 16);
                cs.Write(encr1, 16, 16);
                cs.Write(encr1, 32, 16);
                cs.Write(encr1, 48, encr1.Length-48);
                cs.FlushFinalBlock();
                byte[] plain2 = ms.ToArray();

                if (!Compare(plain1, plain2))
                {
                    Console.WriteLine("CodeCoverage case failed");
                    return false;
                }
                return true;
            }
        }
    }
        public static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] IV)
        {
            byte[] encrypted;

            using (Aes aesAlg = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IV, 0, IV.Length), key);
                aesAlg.Key = deriveBytes.GetBytes(128 / 8);
                aesAlg.IV = aesAlg.Key;

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

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

            return encrypted;
        }
Ejemplo n.º 7
0
        /// <summary>Encrypt the given string using AES.  The string can be decrypted using
        /// DecryptStringAes().  The sharedSecret parameters must match.</summary>
        /// <param name="plainText">The text to encrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
        /// <param name="salt">The salt used for encryption.</param>
        /// <returns></returns>
        public static string EncryptStringAes(string plainText, string sharedSecret, string salt)
        {
            Guard.AgainstNullOrEmpty(plainText);
            Guard.AgainstNullOrEmpty(sharedSecret);
            Guard.AgainstNullOrEmpty(salt);

            try
            {
                using (var key = new Rfc2898DeriveBytes(sharedSecret, Encoding.ASCII.GetBytes(salt)))
                using (var aesManaged = new AesManaged())
                {
                    aesManaged.Key = key.GetBytes(aesManaged.KeySize / 8);
                    aesManaged.IV = key.GetBytes(aesManaged.BlockSize / 8);

                    using (var encryptor = aesManaged.CreateEncryptor(aesManaged.Key, aesManaged.IV))
                    using (var memoryStream = new MemoryStream())
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    using (var streamWriter = new StreamWriter(cryptoStream))
                    {
                        //Write all data to the stream.
                        streamWriter.Write(plainText);
                        streamWriter.Close();
                        return Convert.ToBase64String(memoryStream.ToArray());
                    }
                }
            }
            catch
            {
                return string.Empty;
            }
        }
Ejemplo n.º 8
0
 public static string Encrypt(this string text)
 {
     if (string.IsNullOrEmpty(text))
     {
         return null;
     }
     byte[] rawPlaintext = System.Text.Encoding.Unicode.GetBytes(text);
     byte[] cipherText = null;
     using (Aes aes = new AesManaged())
     {
         aes.Padding = PaddingMode.PKCS7;
         aes.KeySize = AesKeySizeInBits;
         int KeyStrengthInBytes = aes.KeySize / 8;
         System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 =
             new System.Security.Cryptography.Rfc2898DeriveBytes(Password, Salt, Rfc2898KeygenIterations);
         aes.Key = rfc2898.GetBytes(KeyStrengthInBytes);
         aes.IV = rfc2898.GetBytes(KeyStrengthInBytes);
         using (MemoryStream ms = new MemoryStream())
         {
             using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
             {
                 cs.Write(rawPlaintext, 0, rawPlaintext.Length);
             }
             cipherText = ms.ToArray();
         }
         return ByteArrayToString(cipherText);
     }
 }
			public void DecryptsToOriginalPlainText()
			{
				byte[] plaintextBytes = Encoding.UTF8.GetBytes("This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least.");
				byte[] decryptedBytes;

				using (SymmetricAlgorithm algorithm = new AesManaged())
				{
					byte[] wrongDecryptionKey = algorithm.Key;

					algorithm.GenerateKey();

					byte[] encryptionKey = algorithm.Key;

					Assert.AreNotEqual(encryptionKey, wrongDecryptionKey);

					byte[] ciphertextBytes, iv;
					using (Encryptor encryptor = algorithm.CreateEncryptor(encryptionKey, out iv))
					{
						Assert.AreEqual(encryptionKey, encryptor.Algorithm.Key);
						Assert.AreEqual(iv, encryptor.Algorithm.IV);

						ciphertextBytes = encryptor.Encrypt(plaintextBytes);
					}

					using (Decryptor decryptor = new Decryptor(algorithm, encryptionKey, iv, Encryption.DefaultOptions))
					{
						Assert.AreEqual(encryptionKey, decryptor.Algorithm.Key);
						Assert.AreEqual(iv, decryptor.Algorithm.IV);

						decryptedBytes = decryptor.Decrypt(ciphertextBytes);
					}
				}

				Assert.AreEqual(plaintextBytes, decryptedBytes);
			}
Ejemplo n.º 10
0
        internal static void EncryptFile(string inputFile, string outputFile, string password)
        {

            try {
                var UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);

                string cryptFile = outputFile;
                var fsCrypt = new FileStream(cryptFile, FileMode.Create);

                var AesMngd = new AesManaged();

                var cs = new CryptoStream(fsCrypt,
                    AesMngd.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);

                using (var fsIn = new FileStream(inputFile, FileMode.Open)) {
                    int data;
                    while ((data = fsIn.ReadByte()) != -1)
                        cs.WriteByte((byte)data);
                }
                cs.Close();
                fsCrypt.Close();
            } catch {
                Shared.MSGBOX(Shared.GetRes("#D.02#","Error"),"Encryption failed!",System.Windows.Application.Current.MainWindow);
            }
        }
Ejemplo n.º 11
0
 public string Encrypt(byte[] key, string dataToEncrypt)
 {
     // Initialize
     AesManaged encryptor = new AesManaged();
     // Set the key
     encryptor.Key = key;
     encryptor.IV = key;
     // create a memory stream
     using (MemoryStream encryptionStream = new MemoryStream())
     {
         // Create the crypto stream
         using (
             CryptoStream encrypt = new CryptoStream(encryptionStream, encryptor.CreateEncryptor(),
                 CryptoStreamMode.Write))
         {
             // Encrypt
             byte[] utfD1 = UTF8Encoding.UTF8.GetBytes(dataToEncrypt);
             encrypt.Write(utfD1, 0, utfD1.Length);
             encrypt.FlushFinalBlock();
             encrypt.Close();
             // Return the encrypted data
             return Convert.ToBase64String(encryptionStream.ToArray());
         }
     }
 }
Ejemplo n.º 12
0
 public byte[] EncryptAES(ParametroEntreda Entrada)
 {
     if (Entrada.plainText == null || Entrada.plainText.Length <= 0)
         throw new ArgumentNullException("plainText");
     if (Entrada.Key == null || Entrada.Key.Length <= 0)
         throw new ArgumentNullException("Key");
     if (Entrada.IV == null || Entrada.IV.Length <= 0)
         throw new ArgumentNullException("Key");
     byte[] encrypted;
     using (AesManaged aesAlg = new AesManaged())
     {
         aesAlg.Key = Entrada.Key;
         aesAlg.IV = Entrada.IV;
         ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
         using (MemoryStream msEncrypt = new MemoryStream())
         {
             using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
             {
                 using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                 {
                     swEncrypt.Write(Entrada.plainText);
                 }
                 encrypted = msEncrypt.ToArray();
             }
         }
     }
     return encrypted;
 }
Ejemplo n.º 13
0
        public static string Encrypt(string key, string text)
        {
            // Our symmetric encryption algorithm
            AesManaged aes = new AesManaged();

            // We're using the PBKDF2 standard for password-based key generation
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("password", Encoding.UTF8.GetBytes(key));

            // Setting our parameters
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;

            aes.Key = rfc.GetBytes(aes.KeySize / 8);
            aes.IV = rfc.GetBytes(aes.BlockSize / 8);

            // Encryption
            ICryptoTransform encryptTransf = aes.CreateEncryptor();

            // Output stream, can be also a FileStream
            MemoryStream encryptStream = new MemoryStream();
            CryptoStream encryptor = new CryptoStream(encryptStream, encryptTransf, CryptoStreamMode.Write);

            byte[] utfData = Encoding.Unicode.GetBytes(text);

            encryptor.Write(utfData, 0, utfData.Length);
            encryptor.Flush();
            encryptor.Close();

            // return encrypted content
            return Convert.ToBase64String(encryptStream.ToArray());
        }
Ejemplo n.º 14
0
Archivo: AES.cs Proyecto: 2nfro/dotNet
        public static string Encrypt(string plainText, string key)
        {
            if(string.IsNullOrEmpty(plainText)) {
                throw new ArgumentNullException("plainText");
            }

            if(string.IsNullOrEmpty(key)) {
                throw new ArgumentNullException("key");
            }

            using(var keyDerivationFunction = new Rfc2898DeriveBytes(key, SALT_SIZE)) {
                byte[] saltBytes = keyDerivationFunction.Salt;
                byte[] keyBytes = keyDerivationFunction.GetBytes(32);
                byte[] ivBytes = keyDerivationFunction.GetBytes(16);

                using(var aesManaged = new AesManaged()) {
                    aesManaged.KeySize = 256;

                    using(var encryptor = aesManaged.CreateEncryptor(keyBytes, ivBytes)) {
                        MemoryStream memoryStream = null;
                        CryptoStream cryptoStream = null;

                        return WriteMemoryStream(plainText, ref saltBytes, encryptor, ref memoryStream, ref cryptoStream);
                    }
                }
            }
        }
Ejemplo n.º 15
0
 public static string EncryptText(string textToEncrypt, string key, string salt)
 {
     if (string.IsNullOrWhiteSpace(textToEncrypt)) return null;
     if (string.IsNullOrWhiteSpace(key)) return null;
     if (string.IsNullOrWhiteSpace(salt)) return null;
     using (MemoryStream ms = new MemoryStream())
     {
         try
         {
             using (AesManaged aes = new AesManaged())
             {
                 Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(salt));
                 aes.Key = deriveBytes.GetBytes(128 / 8);
                 ms.Write(BitConverter.GetBytes(aes.IV.Length), 0, sizeof(int));
                 ms.Write(aes.IV, 0, aes.IV.Length);
                 using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                 {
                     byte[] bytesFromText = Encoding.Unicode.GetBytes(textToEncrypt);
                     cs.Write(bytesFromText, 0, bytesFromText.Length);
                     cs.FlushFinalBlock();
                 }
                 return BytesToBase64String(ms.ToArray());// Return the encrypted bytes from the memory stream and convert to Base64                        
             }
         }
         catch
         {
             return null;
         }
     }
 }
Ejemplo n.º 16
0
        //平文から暗号化バイト配列を生成して返す
        static byte[] EncryptStringToBytes_Aes(string str,string password)
        {
            if (string.IsNullOrEmpty(str))
                throw new ArgumentNullException("plainText");
            if (password == null || password.Length <= 0)
                throw new ArgumentNullException("key");

            byte[] encrypted;
            using (AesManaged aesAlg = new AesManaged())
            {
                byte[] key, iv;
                GenerateKeyFromPassword(password, aesAlg.KeySize, out key, aesAlg.BlockSize, out iv);
                aesAlg.Key = key;
                aesAlg.IV = iv;

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(str);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            return encrypted;
        }
        public static void EncryptFile(string inputFile, string outputFile, string skey)
        {
            try
            {
                using (Aes aes = new AesManaged())
                {
                    var key = new Rfc2898DeriveBytes(skey, salt);

                    aes.Key = key.GetBytes(aes.KeySize / 8);
                    aes.IV = key.GetBytes(aes.BlockSize / 8);

                    using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
                    {
                        using (ICryptoTransform encryptor = aes.CreateEncryptor())
                        {
                            using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
                            {
                                using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
                                {
                                    int data;
                                    while ((data = fsIn.ReadByte()) != -1)
                                    {
                                        cs.WriteByte((byte)data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { throw; }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// <see cref="IAesManagedWrapper.Encrypt"/>
        /// </summary>
        public byte[] Encrypt(byte[] bytesToBeEncrypted, byte[] aesKey, out byte[] aesIv)
        {
            byte[] encryptedBytes;

            using (var ms = new MemoryStream())
            {
                using (var aes = new AesManaged())
                {
                    SetStandardConfiguration(aes);

                    aes.Key = aesKey;

                    aes.GenerateIV();
                    aesIv = aes.IV;

                    using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }

                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }
Ejemplo n.º 19
0
        public static byte[] Encrypt(string text, string password, byte[] salt = null)
        {
            if (string.IsNullOrEmpty(text)) throw new ArgumentNullException("text");
            if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");

            if (salt == null) salt = DefaultSalt;
            var aes = new AesManaged();

            byte[] encryptedData;

            try
            {
                aes.SetKey(password, salt);
                var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                using (var ms = new MemoryStream())
                {
                    ms.Write(BitConverter.GetBytes(aes.IV.Length), 0, sizeof(int));
                    ms.Write(aes.IV, 0, aes.IV.Length);
                    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    using (var sw = new StreamWriter(cs))
                        sw.Write(text);
                    encryptedData = ms.ToArray();
                }
            }
            finally
            {
                aes.Clear();
            }

            return encryptedData;
        }
Ejemplo n.º 20
0
        static byte[] EncryptedStringToBytes_Aes(string plainText, byte[] key, byte[] IV)
        {
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (key == null || key.Length <= 0)
                throw new ArgumentNullException("key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("SAL");

            byte[] encrypted;
            using (AesManaged aesAlg = new AesManaged())
            {
                aesAlg.Key = key;
                aesAlg.IV = IV;

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

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return encrypted;
        }
Ejemplo n.º 21
0
 public BlockConsensusRequest CreateRequest(MinerWallet wallet)
 {
     lock (SyncRoot)
     {
         if (!Valid) throw new InvalidOperationException();
         if (request == null)
         {
             request = new BlockConsensusRequest
             {
                 PrevHash = PrevHash,
                 Miner = my_pubkey,
                 NonceHash = NonceHashes[my_pubkey],
                 TransactionHashes = TransactionHashes.ToArray()
             };
             SplitSecret secret = SecretSharing.Split(Nonces[my_pubkey].ToArray(), (Miners.Length - 1) / 2 + 1);
             for (int i = 0; i < Miners.Length; i++)
             {
                 if (Miners[i].Equals(my_pubkey)) continue;
                 byte[] aeskey = wallet.GetAesKey(Miners[i]);
                 byte[] iv = aeskey.Take(16).ToArray();
                 byte[] piece = secret.GetShare(i + 1).ToArray();
                 using (AesManaged aes = new AesManaged())
                 using (ICryptoTransform encryptor = aes.CreateEncryptor(aeskey, iv))
                 {
                     piece = encryptor.TransformFinalBlock(piece, 0, piece.Length);
                 }
                 Array.Clear(aeskey, 0, aeskey.Length);
                 Array.Clear(iv, 0, iv.Length);
                 request.NoncePieces.Add(Miners[i], piece);
             }
         }
         return request;
     }
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Encrypt a string using AES
 /// </summary>
 /// <param name="Str">String to encrypt</param>
 /// <param name="Password">Encryption password</param>
 /// <param name="Salt">A salt string (at least 8 bytes)</param>
 /// <returns>Encrypted string in case of success; otherwise - empty string</returns>
 public static string EncryptString(string Str, string Password = "******", string Salt = "tdcm1234")
 {
     try
     {
         using (Aes aes = new AesManaged())
         {
             Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(Salt));
             aes.Key = deriveBytes.GetBytes(128 / 8);
             aes.IV = aes.Key;
             using (MemoryStream encryptionStream = new MemoryStream())
             {
                 using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                 {
                     byte[] utfD1 = UTF8Encoding.UTF8.GetBytes(Str);
                     encrypt.Write(utfD1, 0, utfD1.Length);
                     encrypt.FlushFinalBlock();
                 }
                 return Convert.ToBase64String(encryptionStream.ToArray());
             }
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine("Error : AES ~ EncryptString ; " + ex.Message);
         return "";
     }
 }
Ejemplo n.º 23
0
        public static byte[] Encrypt(byte[] input)
        {
            if (_key == null || _key.Length == 0) throw new Exception("Key can not be empty.");
            if (input == null || input.Length == 0) throw new ArgumentException("Input can not be empty.");

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

            try
            {
                using (var ms = new MemoryStream())
                {
                    using (var rd = new AesManaged { Key = _key })
                    {
                        rd.GenerateIV();

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

                    encdata = ms.ToArray();
                }
            }
            catch
            {
            }
            return encdata;
        }
 internal static byte[] Encrypt(byte[] data)
 {
     byte[] output = null;
     using (var aes = new AesManaged())
     {
         using (var encryptor = aes.CreateEncryptor(Configuration.Default.EncryptionKey, Configuration.Default.EncryptionIV))
         {
             using (var dataStream = new MemoryStream())
             {
                 using (var encryptionStream = new CryptoStream(dataStream, encryptor, CryptoStreamMode.Write))
                 {                            
                     encryptionStream.Write(data, 0, data.Length);
                     encryptionStream.FlushFinalBlock();
                     dataStream.Position = 0;
                     byte[] transformedBytes = new byte[dataStream.Length];
                     dataStream.Read(transformedBytes, 0, transformedBytes.Length);
                     encryptionStream.Close();
                     dataStream.Close();
                     output = transformedBytes;
                 }
             }
         }
     }
     return output;
 }
Ejemplo n.º 25
0
        /// <summary>
        /// 加密
        /// </summary>
        public static string AESEncrypt(string input)
        {
            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(input);
            byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(saltValue);

            // AesManaged - 高级加密标准(AES) 对称算法的管理类
            System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged( );
            // Rfc2898DeriveBytes - 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2 - 一种基于密码的密钥派生函数)
            // 通过 密码 和 salt 派生密钥
            System.Security.Cryptography.Rfc2898DeriveBytes rfc = new System.Security.Cryptography.Rfc2898DeriveBytes(pwdValue, salt);

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
            aes.Key       = rfc.GetBytes(aes.KeySize / 8);
            aes.IV        = rfc.GetBytes(aes.BlockSize / 8);

            // 用当前的 Key 属性和初始化向量 IV 创建对称加密器对象
            System.Security.Cryptography.ICryptoTransform encryptTransform = aes.CreateEncryptor( );
            // 加密后的输出流
            System.IO.MemoryStream encryptStream = new System.IO.MemoryStream( );
            // 将加密后的目标流(encryptStream)与加密转换(encryptTransform)相连接
            System.Security.Cryptography.CryptoStream encryptor = new System.Security.Cryptography.CryptoStream
                                                                      (encryptStream, encryptTransform, System.Security.Cryptography.CryptoStreamMode.Write);

            // 将一个字节序列写入当前 CryptoStream (完成加密的过程)
            encryptor.Write(data, 0, data.Length);
            encryptor.Close( );
            // 将加密后所得到的流转换成字节数组,再用Base64编码将其转换为字符串
            string encryptedString = Convert.ToBase64String(encryptStream.ToArray( ));

            return(encryptedString);
        }
Ejemplo n.º 26
0
        // should be used to encrypt a key with another key
        public static string EncryptWithKey(this string plaintext, string hexkey, string iv)
        {
            byte[] key = hexkey.ToByteArray ();
            byte[] byte_iv = iv.ToByteArray ();
            var aes = new AesManaged ();

            if (key.Length != 16 && key.Length != 20 && key.Length != 32)
                throw new Exception ("Key must be 128, 192 or 256 bits");

            ICryptoTransform encryptor = aes.CreateEncryptor (key, byte_iv);
            // 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(plaintext);
                    }
                    var encrypted = msEncrypt.ToArray();
                    return encrypted.ToHexString ();
                }
            }
        }
Ejemplo n.º 27
0
 public byte[] Encrypt(string plainText, byte[] Key, byte[] IV)
 {
     byte[] encrypted;
     // Create a new AesManaged.
     using (System.Security.Cryptography.AesManaged aes = new System.Security.Cryptography.AesManaged())
     {
         // Create encryptor
         System.Security.Cryptography.ICryptoTransform encryptor = aes.CreateEncryptor(Key, IV);
         // Create MemoryStream
         using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
         {
             // Create crypto stream using the CryptoStream class. This class is the key to encryption
             // and encrypts and decrypts data from any given stream. In this case, we will pass a memory stream
             // to encrypt
             using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
             {
                 // Create StreamWriter and write data to a stream
                 using (System.IO.StreamWriter sw = new System.IO.StreamWriter(cs))
                     sw.Write(plainText);
                 encrypted = ms.ToArray();
             }
         }
     }
     // Return encrypted data
     return(encrypted);
 }
Ejemplo n.º 28
0
		///<summary>Encrypts signature text and returns a base 64 string so that it can go directly into the database.</summary>
		public static string Encrypt(string str,byte[] key){
			//No need to check RemotingRole; no call to db.
			if(str==""){
				return "";
			}
			byte[] ecryptBytes=Encoding.UTF8.GetBytes(str);
			MemoryStream ms=new MemoryStream();
			CryptoStream cs=null;
			Aes aes=new AesManaged();
			aes.Key=key;
			aes.IV=new byte[16];
			ICryptoTransform encryptor=aes.CreateEncryptor(aes.Key,aes.IV);
			cs=new CryptoStream(ms,encryptor,CryptoStreamMode.Write);
			cs.Write(ecryptBytes,0,ecryptBytes.Length);
			cs.FlushFinalBlock();
			byte[] encryptedBytes=new byte[ms.Length];
			ms.Position=0;
			ms.Read(encryptedBytes,0,(int)ms.Length);
			cs.Dispose();
			ms.Dispose();
			if(aes!=null) {
				aes.Clear();
			}
			return Convert.ToBase64String(encryptedBytes);			
		}
Ejemplo n.º 29
0
    public static string Encrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;
                using (MemoryStream encryptionStream = new MemoryStream())
                {
                    using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] cleanText = Encoding.UTF8.GetBytes(text);
                        encrypt.Write(cleanText, 0, cleanText.Length);
                        encrypt.FlushFinalBlock();
                    }

                    byte[] encryptedData = encryptionStream.ToArray();
                    string encryptedText = Convert.ToBase64String(encryptedData);


                    return encryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
        public static string encrypt(string valueToEncrypt)
        {
            using (Aes aes = new AesManaged())
            {
                aes.Padding = PaddingMode.PKCS7;
                aes.KeySize = 128;          // in bits
                aes.Key = new byte[128 / 8];  // 16 bytes for 128 bit encryption
                aes.IV = new byte[128 / 8];   // AES needs a 16-byte IV
                // Should set Key and IV here.  Good approach: derive them from 
                // a password via Cryptography.Rfc2898DeriveBytes 
                byte[] cipherText = null;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(UTF8Encoding.UTF8.GetBytes(valueToEncrypt), 0, valueToEncrypt.Length);
                    }

                    cipherText = ms.ToArray();
                }

                return Convert.ToBase64String(cipherText);
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Encrypts the string using the Advanced Encryption Standard (AES) symmetric algorithm.
        /// </summary>
        /// <param name="plainText">The plain string to be encypted.</param>
        /// <param name="key">The secret key to use for the symmetric algorithm.</param>
        /// <param name="iv">The initialization vector to use for the symmetric algorithm.</param>
        /// <returns>A byte array containing the encypted string.</returns>
        public static byte[] EncryptString(string plainText, byte[] key, byte[] iv)
        {
            // Check arguments.
            if (string.IsNullOrEmpty(plainText))
                throw new ArgumentNullException("plainText");
            if (key == null || key.Length <= 0)
                throw new ArgumentNullException("key");
            if (iv == null || iv.Length <= 0)
                throw new ArgumentNullException("iv");

            using (var msEncrypt = new MemoryStream())
            using (var aes = new AesManaged())
            {
                aes.Key = key;
                aes.IV = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                using (var swEncrypt = new StreamWriter(csEncrypt))
                    swEncrypt.Write(plainText);

                return msEncrypt.ToArray();
            }
        }
Ejemplo n.º 32
0
        public int dbEncrypt(String partition, int size, String data, out String dataOut)
        {
            AesManaged aes = null;
            MemoryStream memoryStream = null;
            CryptoStream cryptoStream = null;

            try
            {
                aes = new AesManaged();
                aes.Key = readKeyFromFile(partition);

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

                byte[] buf = Encoding.UTF8.GetBytes(data);
                cryptoStream.Write(buf, 0, buf.Length);
                cryptoStream.FlushFinalBlock();

                dataOut = Convert.ToBase64String(memoryStream.ToArray());
            }
            finally
            {
                if (cryptoStream != null)
                    cryptoStream.Close();

                if (memoryStream != null)
                    memoryStream.Close();

                if (aes != null)
                    aes.Clear();
            }

            return getErrorCode() == 0 ? 1 : 0;
        }
Ejemplo n.º 33
0
        private void CreateCrytoTransform()
        {
            // Get shared secret
            GetSharedSecret(ref key, ref iv);
            if (key.Length == 0)
            {
                return;
            }
            // Set transform
            AesManaged aes         = new System.Security.Cryptography.AesManaged();
            AesManaged aes_decrypt = new AesManaged();

            aes.Key       = key;
            aes.IV        = iv;
            aes.Mode      = System.Security.Cryptography.CipherMode.CBC;
            aes.Padding   = System.Security.Cryptography.PaddingMode.PKCS7;
            aes.BlockSize = 128;
            transform     = aes.CreateEncryptor();

            aes_decrypt.Key       = key;
            aes_decrypt.IV        = iv;
            aes_decrypt.Mode      = System.Security.Cryptography.CipherMode.CBC;
            aes_decrypt.Padding   = System.Security.Cryptography.PaddingMode.None;
            aes_decrypt.BlockSize = 128;
            decryptTransform      = aes_decrypt.CreateDecryptor();
        }