.NET的编码转换实例 (常用于数据加密)

4/25/2010来源:ASP.NET技巧人气:6637

asp.net字符串的编码转换,常用在密码加密上,比如注册时,注册密码输入的是123456,而为了保密,
我们将转换成Base64编码的字符串(类似:MTIzNDU2),再保存进数据库

将输入的字符串转换成Base64编码

if (string.IsNullOrEmpty(TextBox1.Text))
            {
                Response.Write("<script>alert(\"不能为空!\")</script>");
                TextBox1.Focus();
                return;
            }
            else
            {
                //将字符串转换成UFT-8编码的字节数组
                byte[] buffer = Encoding.UTF8.GetBytes(TextBox1.Text);
                //将UTF-8编码的字节数组转换成Base64编码的字符串
                string result = Convert.ToBase64String(buffer);
                TextBox1.Text = result;
            }


再将编码为Base64的字符串转换回UFT-8编码

 if (string.IsNullOrEmpty(TextBox2.Text))
            {
                Response.Write("<script>alert(\"不能为空!\")</script>");
                TextBox2.Focus();
                return;
            }
            else
            {
                byte[] buffer = Convert.FromBase64String(TextBox2.Text);
                string result = Encoding.UTF8.GetString(buffer);
                TextBox2.Text = result;
            }