Imports System.IO
Imports System.Security.Cryptography'数据加/解密 类
Public Class CryData
    '加密密钥,初始化向量
    Public ReadOnly cryKey As Byte() = {9, 4, 2, 8, 5, 1, 4, 9, 7, 6, 9, 5, 1, 13, 7, 5, 14, 9, 10, 15, 0, 1, 14, 5, 9, 4, 3, 8, 2, 10}
    Public ReadOnly cryIV As Byte() = {7, 1, 8, 8, 2, 8, 7, 1, 4, 5, 6, 3, 5, 6, 7}  
    ' 文件加密
    Public Sub EncryptData(ByVal inName As String, ByVal outName As String, _
                     Optional ByVal rijnKey() As Byte = Nothing, _
                     Optional ByVal rijnIV() As Byte = Nothing)        If rijnKey Is Nothing Then
            rijnKey = cryKey
        End If
        If rijnIV Is Nothing Then
            rijnIV = cryIV        End If
        ReDim Preserve rijnKey(31)
        ReDim Preserve rijnIV(15)        'Create the file streams to handle the input and output files.
        Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
        Dim fout As New FileStream(outName, FileMode.OpenOrCreate, FileAccess.ReadWrite)
        fout.SetLength(0)        'Create variables to help with read and write.
        Dim bin(1024) As Byte 'This is intermediate storage for the encryption.
        Dim rdlen As Long = 0 'This is the total number of bytes written.
        Dim totlen As Long = fin.Length 'Total length of the input file.
        Dim len As Integer 'This is the number of bytes to be written at a time.
        'Creates the default implementation, which is RijndaelManaged.
        Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
        Dim encStream As New CryptoStream(fout, _
                                         rijn.CreateEncryptor(rijnKey, rijnIV), CryptoStreamMode.Write)        ' Console.WriteLine("Encrypting...")        'Read from the input file, then encrypt and write to the output file.
        While rdlen < totlen
            len = fin.Read(bin, 0, 1024)
            encStream.Write(bin, 0, len)
            rdlen = Convert.ToInt32(rdlen + len)
            '  Console.WriteLine("{0} bytes processed", rdlen)
        End While
        'fout.Seek(0, SeekOrigin.Begin)
        'Dim returnValue As String
        'returnValue = New StreamReader(fout).ReadToEnd()        encStream.Close()
        fout.Close()
        fin.Close()    End Sub    '文件解密    Public Sub DecryptData(ByVal inName As String, ByVal outName As String, _
                     Optional ByVal rijnKey() As Byte = Nothing, _
                     Optional ByVal rijnIV() As Byte = Nothing)        If rijnKey Is Nothing Then
            rijnKey = cryKey        End If        If rijnIV Is Nothing Then
            rijnIV = cryIV        End If        ReDim Preserve rijnKey(31)
        ReDim Preserve rijnIV(15)        'Create the file streams to handle the input and output files.
        Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
        Dim fout As New FileStream(outName, FileMode.OpenOrCreate, _
        FileAccess.ReadWrite)
        fout.SetLength(0)        'Create variables to help with read and write.
        Dim bin(1024) As Byte 'This is intermediate storage for the encryption.
        Dim rdlen As Long = 0 'This is the total number of bytes written.
        Dim totlen As Long = fin.Length 'Total length of the input file.
        Dim len As Integer 'This is the number of bytes to be written at a time.
        'Creates the default implementation, which is RijndaelManaged.
        Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
        Dim encStream As New CryptoStream(fout, _
                                          rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Write)        '  Console.WriteLine("Encrypting...")        'Read from the input file, then encrypt and write to the output file.
        While rdlen < totlen
            len = fin.Read(bin, 0, 1024)
            encStream.Write(bin, 0, len)
            rdlen = Convert.ToInt32(rdlen + len)
            ' Console.WriteLine("{0} bytes processed", rdlen)        End While        encStream.Close()
        fout.Close()
        fin.Close()    End Sub
    '文件解密    Public Function DecryptData(ByVal inName As String, _
                        Optional ByVal rijnKey() As Byte = Nothing, _
                        Optional ByVal rijnIV() As Byte = Nothing) As String        If rijnKey Is Nothing Then
            rijnKey = cryKey        End If        If rijnIV Is Nothing Then
            rijnIV = cryIV        End If        ReDim Preserve rijnKey(31)
        ReDim Preserve rijnIV(15)        'Create the file streams to handle the input and output files.
        Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
        '  Dim fout As New FileStream(outName, FileMode.OpenOrCreate, _
        ' FileAccess.ReadWrite)
        '存储流,
        Dim outStream As New MemoryStream() '(arrInByte, True)  '(arrInByte, True)
        'Create variables to help with read and write.
        Dim bin(1024) As Byte 'This is intermediate storage for the encryption.
        Dim rdlen As Long = 0 'This is the total number of bytes written.
        Dim totlen As Long = fin.Length 'Total length of the input file.
        Dim len As Integer 'This is the number of bytes to be written at a time.
        'Creates the default implementation, which is RijndaelManaged.
        While rdlen < totlen
            len = fin.Read(bin, 0, 1024)
            outStream.Write(bin, 0, len)
            rdlen = Convert.ToInt32(rdlen + len)
            ' Console.WriteLine("{0} bytes processed", rdlen)        End While        outStream.Seek(0, SeekOrigin.Begin)        Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
        Dim encStream As New CryptoStream(outStream, _
                                          rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Read)        '  Console.WriteLine("Encrypting...")        'Read from the input file, then encrypt and write to the output file.
        Dim returnValue As String
        returnValue = New StreamReader(encStream, New System.Text.UnicodeEncoding()).ReadToEnd()
        encStream.Close()
        outStream.Close()
        fin.Close()
        Return returnValue    End Function

解决方案 »

  1.   


        '加密
        'in:        inText      待加密原始文本
        'in:        rijnKey     32位密钥
        'in:        rijnIV      16位初始化向量    'out:       return      加密后的文本(为空则加密失败)    Public Function Crypt(ByVal inText As String, _
                          Optional ByVal rijnKey() As Byte = Nothing, _
                         Optional ByVal rijnIV() As Byte = Nothing) As String        'Create the file streams to handle the input and output files.
            '  Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
            Dim arrInByte As Byte() = (New System.Text.UnicodeEncoding()).GetBytes(inText)        Dim len As Long = arrInByte.Length        If (len Mod 32) > 0 Then
                Dim oldlen As Long = len            len = oldlen + 32 - oldlen Mod 32            ReDim Preserve arrInByte(len - 1)        End If        If rijnKey Is Nothing Then
                rijnKey = cryKey        End If
            If rijnIV Is Nothing Then
                rijnIV = cryIV        End If        ReDim Preserve rijnKey(31)        ReDim Preserve rijnIV(15)
            Dim outStream As New MemoryStream()   '(arrInByte, True)  '(arrInByte, True)        Dim rij As SymmetricAlgorithm = SymmetricAlgorithm.Create()        Dim encStream As New CryptoStream(outStream, _
                                             rij.CreateEncryptor(rijnKey, rijnIV), _
                                             CryptoStreamMode.Write)        encStream.Write(arrInByte, 0, len)
            outStream.Seek(0, SeekOrigin.Begin)        Dim returnValue As String
            returnValue = New StreamReader(outStream, New System.Text.UnicodeEncoding()).ReadToEnd()        encStream.Close()
            outStream.Close()        Return returnValue    End Function    '--------------------------------------------------------------------------------------------------------
        '解密     'in:        inText      待解密密文
        'in:        rijnKey     32位解密密钥(须跟加密时的相同)
        'in:        rijnIV      16位解密初始化向量(须跟加密时的相同)    'out:       return      解密后的文本(为空则解密失败)
        '解密 过程:把密文换成字节写到内存流,再跟据rijnKey和rijnIV创建解密流
        '从解密流中读取所有的数据
        '--------------------------------------------------------------------------------------------------------    Public Function Decrypt(ByVal inText As String, _
                          Optional ByVal rijnKey() As Byte = Nothing, _
                         Optional ByVal rijnIV() As Byte = Nothing) As String        '密文转换成字节        Dim arrInByte As Byte() = (New System.Text.UnicodeEncoding()).GetBytes(inText)        '存储流,
            Dim outStream As New MemoryStream() '(arrInByte, True)  '(arrInByte, True)        Dim len As Long = arrInByte.Length
            If rijnKey Is Nothing Then
                rijnKey = cryKey        End If        If rijnIV Is Nothing Then
                rijnIV = cryIV        End If        ReDim Preserve rijnKey(31)        ReDim Preserve rijnIV(15)
            Dim rij As SymmetricAlgorithm = SymmetricAlgorithm.Create()        outStream.Write(arrInByte, 0, len)        outStream.Seek(0, SeekOrigin.Begin)        Dim encStream As New CryptoStream(outStream, _
                                             rij.CreateDecryptor(rijnKey, rijnIV), _
                                             CryptoStreamMode.Read)        Dim returnValue As String
            returnValue = New StreamReader(encStream, New System.Text.UnicodeEncoding()).ReadToEnd()
            encStream.Close()
            outStream.Close()        Return returnValue    End Function
    End Class
      

  2.   

    有没有c#的啊 偶不懂vb 啊 最好能解释解释啊 !!!!
      

  3.   

    public static  string GetMD5(string str)
    {
    return FormsAuthentication.HashPasswordForStoringInConfigFile(str,"md5"); }直接使用这个函数就可以了,using System.Web.Security;
    有两种加密,md5和hash ,不清楚参考msdn
      

  4.   

    如果是这样的话是没有问题的,测试通过。
    <%@ Import Namespace="System.Web.Security" %>
    <%@ Page language="c#" %><HTML>
      <HEAD> 
    <script language="C#" runat="server"> 
    public void encryptString(Object sender, EventArgs e) 

    SHA1.Text = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text,"SHA1"); 
    MD5.Text =FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5") ; 

    </script>
    </HEAD> 
    <body> 
    <form runat="server" ID="Form1"> 
    <p> 
    <b>Original Clear Text Password: </b> <asp:Textbox id="txtPassword" runat="server" /> 
    <asp:Button runat="server" text="Encrypt String" onClick="encryptString" ID="Button1" /> 
    </p> 
    <p> 
    <b>Encrypted Password In SHA1: </b> 
    <asp:label id="SHA1" runat="server" /> 
    </p> 
    <p> 
    <b>Encrypted Password In MD5: </b> 
    <asp:label id="MD5" runat="server" /> 
    </p> 
    </form> 
    </body>
    </HTML>
      

  5.   

    MSDN Library中的例子:
    using System;
    using System.IO;
    using System.Text;
    using System.Security.Cryptography;namespace RijndaelManaged_Examples
    {
        class MyMainClass
        {
            public static void Main()
            {
                string original = "This is a much longer string of data than a public/private key algorithm will accept.";
                string roundtrip;
                ASCIIEncoding textConverter = new ASCIIEncoding();
                RijndaelManaged myRijndael = new RijndaelManaged();
                byte[] fromEncrypt;
                byte[] encrypted;
                byte[] toEncrypt;
                byte[] key;
                byte[] IV;            //Create a new key and initialization vector.
                myRijndael.GenerateKey();
                myRijndael.GenerateIV();            //Get the key and IV.
                key = myRijndael.Key;
                IV = myRijndael.IV;            //Get an encryptor.
                ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);
                
                //Encrypt the data.
                MemoryStream msEncrypt = new MemoryStream();
                CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);            //Convert the data to a byte array.
                toEncrypt = textConverter.GetBytes(original);            //Write all data to the crypto stream and flush it.
                csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
                csEncrypt.FlushFinalBlock();            //Get encrypted array of bytes.
                encrypted = msEncrypt.ToArray();            //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.
                ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);            //Now decrypt the previously encrypted message using the decryptor
                // obtained in the above step.
                MemoryStream msDecrypt = new MemoryStream(encrypted);
                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);            fromEncrypt = new byte[encrypted.Length];            //Read the data out of the crypto stream.
                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);            //Convert the byte array back into a string.
                roundtrip = textConverter.GetString(fromEncrypt);            //Display the original data and the decrypted data.
                Console.WriteLine("Original:   {0}", original);
                Console.WriteLine("Round Trip: {0}", roundtrip);
            }
        }
    }
      

  6.   

    我晕
    都贴那长的代码
    最简单的哈西函数加密
    注意看下面的代码 防止一个用户名有几个人同时登录
    你试试就会了
    private void Blogin_Click(object sender, System.EventArgs e)
    {
    //用户登录
    string UserName=this.Tusername.Value.ToString().Trim().Replace("'","''");
    if (UserName=="")
    {
    this.Labmsg.Text="请输入用户名.";
    return ;
    }
    string Password=this.Tuserpwd.Value.ToString().Trim();
    string NowDate=DateTime.Now.ToString();
    string SecurityPwd=FormsAuthentication.HashPasswordForStoringInConfigFile(Password,"md5");
    string strLogin="select * from Myuser where UserName='"+UserName+"' and UserPSW='"+SecurityPwd+"'";
    SqlDataAdapter LoginSD=new SqlDataAdapter(strLogin,myService.myConnme());
    DataTable LoginDT=new DataTable();
    LoginSD.Fill(LoginDT);
    if (LoginDT.Rows.Count>0)

    {//通过身份验证
    //将在线用户信息写入Session
    Session["sessUserName"]=UserName;
        Session["sessLoginTime"]=NowDate;
        Session["sessGroupQX"]=LoginDT.Rows[0][2].ToString().Trim();
        Session["sessUserQX"]=LoginDT.Rows[0][3].ToString().Trim();
        int howtime=Convert.ToInt32(LoginDT.Rows[0][6])+1;
    string strupd="update Myuser set JoinTime='"+NowDate+"',HowTime='"+howtime+"' where UserName='"+UserName+"'";
    SqlCommand upd=new SqlCommand(strupd,myService.myConnme());
    upd.ExecuteNonQuery(); FormsAuthentication.RedirectFromLoginPage(UserName,false);
    }
    else
    {//未通过身份验证
    this.Labmsg.Text="用户名或密码不正确。";
    }
    LoginDT.Dispose();
    LoginSD.Dispose();

    } }