Exemplo n.º 1
0
    public string Encrypt(string plainText, string password)
    {
        if (plainText == null)
        {
            throw new ArgumentNullException("plainText");
        }
        if (string.IsNullOrEmpty(password))
        {
            throw new ArgumentNullException("password");
        }
        DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();

        dESCryptoServiceProvider.GenerateIV();
        Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, dESCryptoServiceProvider.get_IV(), 1000);

        byte[] bytes = rfc2898DeriveBytes.GetBytes(8);
        string result;

        using (MemoryStream memoryStream = new MemoryStream())
        {
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(bytes, dESCryptoServiceProvider.get_IV()), 1))
            {
                memoryStream.Write(dESCryptoServiceProvider.get_IV(), 0, dESCryptoServiceProvider.get_IV().Length);
                byte[] bytes2 = Encoding.get_UTF8().GetBytes(plainText);
                cryptoStream.Write(bytes2, 0, bytes2.Length);
                cryptoStream.FlushFinalBlock();
                result = Convert.ToBase64String(memoryStream.ToArray());
            }
        }
        return(result);
    }