memory.Seek(0, SeekOrigin.Begin)
            If memory.CanRead Then
                Thread.CurrentThread.Sleep(1000)
                memory.Read(output, 0, memory.Length)
            End If这些都不要,换成:Dim bytes memory.ToArray()这样就可以获得字节数组,你可以在字节数组的基础上按照你的编码转换成字符串

解决方案 »

  1.   

    SorryDim bytes = memory.ToArray()
      

  2.   

    http://chs.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/howto/samples/cryptography/fileencrypt/encrypt.src&file=CS\fileencrypt.cs&font=3
      

  3.   

    其实没有什么的。
    你只是不知道调用一个重要的步骤:
    enc.Write(buf, 0, buf.Length)
    enc.FlushFinalBlock
      

  4.   

    .Net类库提供的方法都是基于流的加解密这很方便啊你要转成什么
      

  5.   

    Lostinet(NeverCodeBehind)(迷失网络)
    说的对你还要调用:
    enc.FlushFinalBlock你的流没有更新,你当然得不到数据
      

  6.   

    恩。
    主要是因为很多算法都是基于固定长度的字节的。
    加密提供者使用FlushFinalBlock来把最后不完整的block补全然后输出。
    当然,基于流是一个基本的算法提供。
    如果不习惯,完全可以自己写一个方法来实现自己的不同要求。
      

  7.   

    调用的方法有问题,加密的方式就是CryptoStream,本身就是流的调用。按照 timmy3310(Tim)说的去试试。
      

  8.   

    以下是解密的方法,还是有问题啊,大家看一看吧。
    Dim des As DESCryptoServiceProvider = New DESCryptoServiceProvider()
            Dim memory As New MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(input))
            Dim buf(128) As Byte
            Dim enc As New CryptoStream(memory, des.CreateDecryptor(key, IV), CryptoStreamMode.Read)
            enc.Read(buf, 0, memory.Length)'这里报错:不正确的数据,我的输入就是刚才加密的输入。
            enc.Close()
            Return System.Text.UTF8Encoding.UTF8.GetString(buf)
      

  9.   

    。。
    CryptoStreamMode仍然是Write
    而且仍然是使用enc.Write
      

  10.   


    我把我做的系统的所有页面的基类的验证登陆部分的代码帖出来吧:关于using(EnterQuery()),可以参考我在asp.net版发的关键字为ISqlScope的帖子/// <summary>
    /// 页面是否需要登陆
    /// </summary>
    protected virtual bool NeedLogin()
    {
    return true;
    }
    protected override void OnInit(EventArgs e)
    { if(NeedLogin())
    {
    try
    {
    GetEmployee();
    }
    catch(EmployeeNotLoginException)
    {
    Response.Redirect((MapAppPath("/Login.aspx"),true);
    }
    } base.OnInit(e);
    }#region 登陆状态 GetEmployee() ...EmployeeInfo _ei;
    /// <summary>
    /// 取登陆的员工信息
    /// </summary>
    public EmployeeInfo GetEmployee()
    {
    if(_ei==null)
    {
    _ei=GetEmployeeInternal();
    }
    return _ei;
    }
    #region private EmployeeInfo GetEmployeeInternal()
    /// <summary>
    /// 取登陆的员工信息
    /// </summary>
    private EmployeeInfo GetEmployeeInternal()
    {
    HttpCookie cookie=Request.Cookies["ECO"];
    if(cookie==null)
    throw(new EmployeeNotLoginException("oc-n"));

    string name=cookie["N"];//Encrypt
    string pass=cookie["P"];//Hash
    string addr=cookie["A"];//Hash
    if(name==null||name.Length==0)
    throw(new EmployeeNotLoginException("n-n"));
    if(pass==null||pass.Length==0)
    throw(new EmployeeNotLoginException("p-n")); string dbname;
    try
    {
    dbname=DecryptString(name);
    }
    catch
    {
    throw(new EmployeeNotLoginException("n-x"));
    } if(addr==null||addr.Length==0)
    throw(new EmployeeNotLoginException("a-n"));
    if(addr!=HashString(Request.UserHostAddress))
    throw(new EmployeeNotLoginException("a-x")); object oei=Session[typeof(EmployeeInfo).FullName]; if(oei!=null)
    {
    EmployeeInfo ei=(EmployeeInfo)oei;
    if(ei.Name==dbname)
    return ei;
    } return LoginAs(dbname,pass);
    }
    #endregion/// <summary>
    /// 登陆错误所抛出的异常
    /// </summary>
    public class EmployeeNotLoginException:Exception
    {
    public EmployeeNotLoginException(){}
    public EmployeeNotLoginException(string Message)
    :base(Message)
    {
    }
    }/// <summary>
    /// 登陆,并且取登陆的员工信息
    /// </summary>
    /// <param name="name">用户名</param>
    /// <param name="pass">密码</param>
    public EmployeeInfo LoginAs(string name,string hashedpass)
    {
    if(name==null)
    throw(new ArgumentNullException("name"));
    if(hashedpass==null)
    throw(new ArgumentNullException("hashedpass")); if(Session[typeof(EmployeeInfo).FullName]!=null)
    Session.Remove(typeof(EmployeeInfo).FullName); using(EnterQuery())
    {
    using(SqlCommand cmd=CreateCommand("SELECT * FROM coyg WHERE mc=@mc"))
    {
    cmd.Parameters.Add("@mc",name);
    using(SqlDataReader sdr=cmd.ExecuteReader())
    {
    if(!sdr.Read())
    throw(new EmployeeNotLoginException("r-n"));//notlogin string dbpass=sdr.GetString(sdr.GetOrdinal("mm")); string passhash=HashString(dbpass); if(passhash!=hashedpass)
    throw(new EmployeeNotLoginException("p-x"+":"+passhash+":"+hashedpass));//notlogin EmployeeInfo ei=new EmployeeInfo(
    Convert.ToInt32(sdr["id"]),
    Convert.ToString(sdr["mc"]),
    dbpass,
    Convert.ToInt32(sdr["gwid"]),
    Convert.ToString(sdr["gwmc"])
    ); HttpCookie cookie=Response.Cookies["ECO"]; cookie["N"]=EncryptString(ei.Name);
    cookie["P"]=passhash;
    cookie["A"]=HashString(Request.UserHostAddress);
    cookie.Path=MapAppPath("/");
    Session[typeof(EmployeeInfo).FullName]=ei; return ei;
    }
    }
    }
    }/// <summary>
    /// 注销
    /// </summary>
    protected void DoLogout()
    {
    if(Session[typeof(EmployeeInfo).FullName]!=null)
    Session.Remove(typeof(EmployeeInfo).FullName); HttpCookie cookie=Response.Cookies["ECO"]; cookie.Expires=DateTime.MinValue;
    cookie["A"]="";
    cookie["N"]="";
    cookie["P"]=""; cookie.Path=MapAppPath("/");
    }
    #region public string EncryptString(string str),DecryptString(string str),HashString(string str)#region GetEncryptKey(),GetEncryptIV()
    static private byte[] _encKey=null;
    static private byte[] GetEncryptKey()
    {
    if(_encKey==null)
    {
    byte[] bs=new SHA1CryptoServiceProvider().ComputeHash(Encoding.Unicode.GetBytes("[_Lostinet_CRMOA_Key_]"));
    byte[] key=new byte[24];
    for(int i=0;i<key.Length;i++)
    {
    key[i]=bs[i%bs.Length];
    }
    _encKey=key;
    }
    return _encKey;
    }
    static private byte[] _encIV=null;
    static private byte[] GetEncryptIV()
    {
    if(_encIV==null)
    {
    byte[] bs=new SHA1CryptoServiceProvider().ComputeHash(Encoding.Unicode.GetBytes("[_Lostinet_CRMOA_IV_]"));
    byte[] iv=new byte[24];
    for(int i=0;i<iv.Length;i++)
    {
    iv[i]=bs[i%bs.Length];
    }
    _encIV=iv;
    }
    return _encIV;
    }
    #endregion/// <summary>
    /// 加密字符串
    /// </summary>
    public string EncryptString(string str)
    {
    string prefix=("LostinetCO"+Request.UserHostAddress+Request.UserAgent).GetHashCode().ToString("X");
    string fullstr=prefix+str; byte[] source=Encoding.Unicode.GetBytes(fullstr);

    using(MemoryStream ms=new MemoryStream())
    {
    TripleDESCryptoServiceProvider des=new TripleDESCryptoServiceProvider(); using(CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(GetEncryptKey(),GetEncryptIV()),CryptoStreamMode.Write))
    {
    cs.Write(source,0,source.Length);
    cs.FlushFinalBlock();
    } return Convert.ToBase64String(ms.ToArray());
    }
    }/// <summary>
    /// 解密字符串
    /// </summary>
    public string DecryptString(string str)
    {
    string prefix=("LostinetCO"+Request.UserHostAddress+Request.UserAgent).GetHashCode().ToString("X"); byte[] source=Convert.FromBase64String(str);

    using(MemoryStream ms=new MemoryStream())
    {
    TripleDESCryptoServiceProvider des=new TripleDESCryptoServiceProvider();
    using(CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(GetEncryptKey(),GetEncryptIV()),CryptoStreamMode.Write))
    {
    cs.Write(source,0,source.Length);
    cs.FlushFinalBlock();
    } string fullstr=Encoding.Unicode.GetString(ms.ToArray());
    if(!fullstr.StartsWith(prefix))
    throw(new Exception("bad source"));
    return fullstr.Substring(prefix.Length);
    }
    }
    /// <summary>
    /// 创建Hash值
    /// </summary>
    public string HashString(string str)
    {
    string prefix=("LostinetCO"+Request.UserHostAddress+Request.UserAgent).GetHashCode().ToString("X");
    string fullstr=prefix+str; SHA1CryptoServiceProvider sha=new SHA1CryptoServiceProvider();
    byte[] source=Encoding.Unicode.GetBytes(fullstr);
    byte[] result=sha.ComputeHash(source);
    return Convert.ToBase64String(result);
    }
    #endregion#endregion
      

  11.   

    上面输出成的cookie是:
    ECO=N=8qr84vfOjlqXG5hqNDh8qO4xTDfJmbypbXdf0NkKjKQ=&P=ZtDLOTRMCNdY5HqSp2ulG/Xdy7A=&A=CtKM/pbHHXh7KxAfKgly40iPev8=; ASP.NET_SessionId=o45zizm1uhd3olqlodue4c2y 上面的代码完全可以改装成不使用Session或不使用Cookie的。
    我个人认为整个程序禁止使用Session有明显的性能好处。
    而且也不会出现同Session的请求队列了。
      

  12.   

    呵呵
    发现了一个错误了。~~~~
    忘记了检测密码~~~ if(oei!=null)
    {
    EmployeeInfo ei=(EmployeeInfo)oei;
    if(ei.Name==dbname&&HashString(ei.Pass)==pass)
    return ei;
    }
      

  13.   

    我要晕,还是不行。我把所有的代码都出来: Label1.Text = Crypto.DeCrypt(Crypto.EnCrypt(TextBox1.Text))
     Public Shared Function DeCrypt(ByVal input As String) As String
    Dim des As DESCryptoServiceProvider = New DESCryptoServiceProvider()
            Dim memory As New MemoryStream(256)
            Dim buf() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
            Dim output(128) As Byte
            If memory.CanWrite Then
                Dim enc As New CryptoStream(memory, des.CreateDecryptor(key, IV), CryptoStreamMode.Write)
                enc.Write(buf, 0, buf.Length)
                enc.FlushFinalBlock()
                memory.Seek(0, SeekOrigin.Begin)
                memory.Read(output, 0, memory.Length)
                enc.Close()
            End If        Return System.Text.ASCIIEncoding.ASCII.GetString(output)
      

  14.   

    Public Shared Function EnCrypt(ByVal input As String) As String
                   Dim des As DESCryptoServiceProvider = New DESCryptoServiceProvider()
            Dim memory As New MemoryStream(128)
            Dim buf() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
            Dim output(128) As Byte
            If memory.CanWrite Then
                Dim enc As New CryptoStream(memory, des.CreateEncryptor(key, IV), CryptoStreamMode.Write)
                enc.Write(buf, 0, buf.Length)
                enc.FlushFinalBlock()
                memory.Seek(0, SeekOrigin.Begin)
                memory.Read(output, 0, memory.Length)
                enc.Close()
            End If        Return System.Text.ASCIIEncoding.ASCII.GetString(output)
        End Function
      

  15.   

    删除贴子,扣除信誉分5分。作者:Lostinet贴文时间:Oct    8  2002    1:57PM标题:[■转■]  3721公司欺骗国人  (欢迎大家近来发泄)
      

  16.   

    Dim output(128) As Byte
    不就明显地规定死了输出的大小了嘛。
      

  17.   

    static private byte[] _encIV=null;
    static private byte[] GetEncryptIV()
    {
    if(_encIV==null)
    {
    byte[] bs=new SHA1CryptoServiceProvider().ComputeHash(Encoding.Unicode.GetBytes("[_Lostinet_CRMOA_IV_]"));
    byte[] iv=new byte[24];
    for(int i=0;i<iv.Length;i++)
    {
    iv[i]=bs[i%bs.Length];
    }
    _encIV=iv;
    }
    return _encIV;
    }这个代码的确有问题。
    我才发现运算后iv变成00-00-00-00...了
    改成Clone就好了。static private byte[] _encIV=null;
    static private byte[] GetEncryptIV()
    {
    if(_encIV==null)
    {
    byte[] bs=new SHA1CryptoServiceProvider().ComputeHash(Encoding.Unicode.GetBytes("[_Lostinet_CRMOA_IV_]"));
    byte[] iv=new byte[24];
    for(int i=0;i<iv.Length;i++)
    {
    iv[i]=bs[i%bs.Length];
    }
    _encIV=iv;
    }
    return (byte[])_encIV.Clone();
    }
      

  18.   

    key和iv有什么特殊的要求吗,我一直没有成功过。
    我的代码执行解密时,在这一句出错啊:
    enc.Write(buf, 0, buf.Length)
    好像和
    Dim output(128) As Byte
    这句没有关系。
      

  19.   

    贴主:
    看样子你用的是DES加密解密方法,我有,已经成功。
    注意,key和iv有限制,只能用英文,区分大小写,只能8个字母。
    代码如下:
    Public Shared Function Encrypt(ByVal pToEncrypt As String, ByVal sKey As String) As String
            Dim des As New DESCryptoServiceProvider()
            Dim inputByteArray() As Byte
            inputByteArray = Encoding.Default.GetBytes(pToEncrypt)
            '建立加密对象的密钥和偏移量
            '原文使用ASCIIEncoding.ASCII方法的GetBytes方法
            '//使得输入密码必须输入英文文本
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
            '//写二进制数组到加密流
            '//(把内存流中的内容全部写入)
            Dim ms As New System.IO.MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateEncryptor, CryptoStreamMode.Write)
            '写二进制数组到加密流
            '(把内存流中的内容全部写入)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()        'Get the data back from the memory stream, and into a string
            Dim ret As New StringBuilder()
            Dim b As Byte
            For Each b In ms.ToArray()
                ret.AppendFormat("{0:X2}", b)
            Next        Return ret.ToString()
        End Function    Public Shared Function Decrypt(ByVal pToDecrypt As String, ByVal sKey As String) As String
            Dim des As New DESCryptoServiceProvider()
            '//把字符串放入byte数组
            Dim len As Integer
            len = pToDecrypt.Length / 2 - 1
            Dim inputByteArray(len) As Byte
            Dim x, i As Integer
            For x = 0 To len
                i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)
                inputByteArray(x) = CType(i, Byte)
            Next        '//建立加密对象的密钥和偏移量,此值重要,不能修改
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
            Dim ms As New System.IO.MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateDecryptor, CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Return Encoding.Default.GetString(ms.ToArray)    End Function
      

  20.   

    试试这段代码,我已经用了很久都没有出过问题using System;
    using System.Security.Cryptography;
    using System.IO;
    using System.Text;namespace FangHome_Crypto
    {
    /// <summary>
    /// SymmCrypto is a wrapper of System.Security.Cryptography.SymmetricAlgorithm classes
    /// and simplifies the interface. It supports customized SymmetricAlgorithm as well.
    /// </summary>
    public class SymmCrypto
    {
    /// <res>
    /// Supported .Net intrinsic SymmetricAlgorithm classes.
    /// </res>
    public enum SymmProvEnum : int
    {
    DES, RC2, Rijndael, TripleDES
    } private SymmetricAlgorithm mobjCryptoService; /// <res>
    /// Constructor for using an intrinsic .Net SymmetricAlgorithm class.
    /// </res>
    public SymmCrypto(SymmProvEnum NetSelected)
    {
    switch (NetSelected)
    {
    case SymmProvEnum.DES:
    mobjCryptoService = new DESCryptoServiceProvider();
    break;
    case SymmProvEnum.RC2:
    mobjCryptoService = new RC2CryptoServiceProvider();
    break;
    case SymmProvEnum.Rijndael:
    mobjCryptoService = new RijndaelManaged();
    break;
    case SymmProvEnum.TripleDES:
    mobjCryptoService = new TripleDESCryptoServiceProvider();
    break;
    }
    } /// <res>
    /// Constructor for using a customized SymmetricAlgorithm class.
    /// </res>
    public SymmCrypto(SymmetricAlgorithm ServiceProvider)
    {
    mobjCryptoService = ServiceProvider;
    } private byte[] GetLegalKey(string Key)
    {
    string sTemp = Key;
    mobjCryptoService.GenerateKey();
    byte[] bytTemp = mobjCryptoService.Key;
    int KeyLength = bytTemp.Length;
    if (sTemp.Length > KeyLength)
    sTemp = sTemp.Substring(0, KeyLength);
    else if (sTemp.Length < KeyLength)
    sTemp = sTemp.PadRight(KeyLength, ' '); return ASCIIEncoding.ASCII.GetBytes(sTemp);
    } private byte[] GetLegalIV()
    {
    // The initial string of IV may be modified with any data you like
    string sTemp = "救臆妲饣";
    mobjCryptoService.GenerateIV();
    byte[] bytTemp = mobjCryptoService.IV;
    int IVLength = bytTemp.Length;
    if (sTemp.Length > IVLength)
    sTemp = sTemp.Substring(0, IVLength);
    else if (sTemp.Length < IVLength)
    sTemp = sTemp.PadRight(IVLength, ' '); return ASCIIEncoding.ASCII.GetBytes(sTemp);
    } public string Encrypting(string Source, string Key)
    {
    // use UTF8 unicode conversion for two byte characters
    byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source); // create a MemoryStream so that the process can be done without I/O files
    System.IO.MemoryStream ms = new System.IO.MemoryStream(); // set the private key
    mobjCryptoService.Key = GetLegalKey(Key);
    mobjCryptoService.IV = GetLegalIV(); // create an Encryptor from the Provider Service instance
    ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(); // create Crypto Stream that transforms a stream using the encryption
    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); // write out encrypted content into MemoryStream
    cs.Write(bytIn, 0, bytIn.Length);
    cs.FlushFinalBlock(); ms.Close();
    byte[] bytOut = ms.ToArray(); // convert into Base64 so that the result can be used in xml
    return System.Convert.ToBase64String(bytOut);
    } public string Decrypting(string Source, string Key)
    {
    // convert from Base64 to binary
    byte[] bytIn = System.Convert.FromBase64String(Source);
    // create a MemoryStream with the input
    System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length); // set the private key
    mobjCryptoService.Key = GetLegalKey(Key);
    mobjCryptoService.IV = GetLegalIV(); // create a Decryptor from the Provider Service instance
    ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor(); // create Crypto Stream that transforms a stream using the decryption
    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read); // read out the result from the Crypto Stream
    System.IO.StreamReader sr = new System.IO.StreamReader( cs );
    return sr.ReadToEnd();
    }
    }
    }
      

  21.   

    TomMax的代码我试过了,为什么只能加解密英文和数字的,中文的解出乱码来了??
      

  22.   

    to cong2002:
    这是你Web.config的编码设置问题,没看见有这个代码Encoding.Default.GetString
    就是使用你应用程序设置的默认编码,你全部设置成gb2312,保证没有问题。