Des Decrypt读入C#

时间:2017-03-20 14:55:55

标签: c# encryption des

static byte[] desdecrypt(Mode mode, byte[] IV, byte[] key, byte[] msg)
    {
        using (var des = new DESCryptoServiceProvider())
        {
            des.IV = IV;
            des.Key = key;
            des.Mode = CipherMode.CBC;
            des.Padding = PaddingMode.PKCS7;

            using (var mstream = new MemoryStream())
            {
                CryptoStream cs = null;
                if (mode == Mode.DECRYPT)
                {
                    cs = new CryptoStream(mstream, des.CreateDecryptor(), CryptoStreamMode.Read);
                }
                if (cs == null)
                    return null;

                cs.Read(msg, 0, msg.Length); 
                return mstream.ToArray();
            }
        }
        return null;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string a = textBox4.Text;
        string ab = textBox6.Text;
        byte[] IV = Encoding.ASCII.GetBytes(ab);
        string aa = textBox7.Text;
        byte[] key = Encoding.ASCII.GetBytes(aa);
        byte[] decrypted = desdecrypt(Mode.DECRYPT, IV, key, Encoding.ASCII.GetBytes(a));
        textBox5.Text = Encoding.ASCII.GetString(decrypted);
    }
此行中出现

cs.Read(msg,0,msg.Length)错误(错误数据) 我的应用程序中发生了未处理的异常 我不知道有什么帮助,请我尝试了几乎所有的东西

1 个答案:

答案 0 :(得分:1)

如果您在基础流中有数据并希望将其解密为数组,请使用CryptoStreamMode.ReadRead

由于您有一个收集数据的空流,您应该使用CryptoStreamMode.WriteWrite

标准警告适用:

  • DES是一个糟糕的,破碎的算法
  • 不要使用ASCII(或Unicode)数据作为密钥
  • 不要假设加密数据可以表示为ASCII(或Unicode)数据
  • 除非您能解释,否则切勿将加密技术添加到已发布的软件中
    • 它做什么
    • 在什么条件下会被视为过时
    • 当它过时时你将如何发展它
      • 当你这样做时,它是如何赢得所有用户的,或让它们变得不安全。