专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Delphi

请问上c#DES加密没有关问题 ,解密解不出来,解密时老提示数组长度不对

发布时间:2011-06-24 19:38:13 文章来源:www.iduyao.cn 采编人员:星星草
请教下c#DES加密没问题 ,解密解不出来,解密时老提示数组长度不对。
自己下了段程序,想将加密和解密分开,但加密没问题 ,解密解不出来,解密时老提示数组长度不对,请高手帮下。
textBox1.Text是加密文档路径。
byte[] Key = { 0xF0, 0x3F, 0xB3, 0xF0, 0x8A, 0x0F, 0xA7, 0x9B };
byte[] IV  = {0x24 ,0xF9 ,0x04 ,0xCC ,0xDB ,0xF0 ,0xCC ,0x81} ;
CipherMode Mode=CipherMode.ECB;
PaddingMode Padding= PaddingMode.PKCS7;
byte[] cipherbytes;






加密如下:
SymmetricAlgorithm sa =CreateSymmetricAlgorithm();
sa.Key = Key;
sa.IV = IV;
sa.Mode = Mode;
sa.Padding = Padding;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(),CryptoStreamMode.Write);
StreamReader f = new StreamReader(textBox1.Text);
textPlaintext.Clear();
textPlaintext.Text = f.ReadToEnd();
f.Close();
byte[] plainbytes =Encoding.UTF8.GetBytes(textPlaintext.Text);
cs.Write(plainbytes, 0, plainbytes.Length);
cs.Close();
cipherbytes = ms.ToArray();
ms.Close();
textCiphertext.Text = Encoding.UTF8.GetString(cipherbytes);
StreamWriter ff = new StreamWriter(textBox1.Text);
ff.Write(textCiphertext.Text);
ff.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cipherbytes.Length; i++)
{sb.Append(String.Format("{0:X2} ", cipherbytes[i])); }
textCipherbytes.Text = sb.ToString();




解密如下:
SymmetricAlgorithm sa =CreateSymmetricAlgorithm();
sa.Key = Key;
sa.Mode = Mode;
sa.Padding = Padding;
sa.IV = IV;
StreamReader f = new StreamReader(textBox1.Text);
textCiphertext.Clear();
textCiphertext.Text = f.ReadToEnd();
f.Close();
MemoryStream ms = new MemoryStream(cipherbytes);CryptoStream cs = new CryptoStream(ms,sa.CreateDecryptor(),CryptoStreamMode.Read);
byte[] plainbytes =new Byte[cipherbytes.Length];
cs.Read(plainbytes, 0, cipherbytes.Length);
cs.Close();
ms.Close();
textRecoveredPlaintext.Text =Encoding.UTF8.GetString(plainbytes);
StreamWriter ff = new StreamWriter(textBox1.Text);
ff.Write(textRecoveredPlaintext.Text);
ff.Close();
------解决方案--------------------
下面是C#实现的DES算法的一个类:
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Web;
using System.Windows.Forms;


/// <summary>
/// Triple Data Encryption Standard algorithms implementations
/// </summary>
/// <Author>Yao</Author>
/// <Date>2005/4/20</Date>

public class CryptionData
{
 // The length of Encryptionstring should be 8 byte and not be a weak key
 private string EncryptionString;

 // The length of initialization vector should be 8 byte
 private static Byte[] EncryptionIV = Encoding.Default.GetBytes("abcdefgh");

 /// <summary>
 /// Constructor
 /// </summary>
 public CryptionData()
 {
 }

 /// <summary>
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: