问题描述
c#实现des加密中,对于解密还是有问题,请教下谁能帮我解决这个问题或者谁能帮我改动下,不甚感激。usingSystem;usingSystem.IO;usingSystem.Data;usingSystem.Text;usingSystem.Diagnostics;usingSystem.Security;usingSystem.Security.Cryptography;classDes{//方法//加密方法publicstringEncrypt(stringpToEncrypt,stringsKey){DESCryptoServiceProviderdes=newDESCryptoServiceProvider();//把字符串放到byte数组中//原来使用的UTF8编码,我改成Unicode编码了,不行byte[]inputByteArray=Encoding.Default.GetBytes(pToEncrypt);//byte[]inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt);//建立加密对象的密钥和偏移量//原文使用ASCIIEncoding.ASCII方法的GetBytes方法//使得输入密码必须输入英文文本if(sKey.Length!=8)return("wrongkey");des.Key=ASCIIEncoding.ASCII.GetBytes(sKey);des.IV=ASCIIEncoding.ASCII.GetBytes(sKey);MemoryStreamms=newMemoryStream();CryptoStreamcs=newCryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write);//Writethebytearrayintothecryptostream//(Itwillendupinthememorystream)cs.Write(inputByteArray,0,inputByteArray.Length);cs.FlushFinalBlock();//Getthedatabackfromthememorystream,andintoastringStringBuilderret=newStringBuilder();foreach(bytebinms.ToArray()){//Formatashexret.AppendFormat("{0:X2}",b);}ret.ToString();returnret.ToString();}//解密方法publicstringDecrypt(stringpToDecrypt,stringsKey){DESCryptoServiceProviderdes=newDESCryptoServiceProvider();//Puttheinputstringintothebytearraytry{byte[]inputByteArray=newbyte[pToDecrypt.Length/2];for(intx=0;x<pToDecrypt.Length/2;x++){inti=(Convert.ToInt32(pToDecrypt.Substring(x*2,2),16));inputByteArray[x]=(byte)i;}//建立加密对象的密钥和偏移量,此值重要,不能修改//inputByteArray=Convert.FromBase64String(pToDecrypt);des.Key=ASCIIEncoding.ASCII.GetBytes(sKey);des.IV=ASCIIEncoding.ASCII.GetBytes(sKey);MemoryStreamms=newMemoryStream();CryptoStreamcs=newCryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write);cs.Write(inputByteArray,0,inputByteArray.Length);cs.FlushFinalBlock();StringBuilderret=newStringBuilder();returnSystem.Text.Encoding.Default.GetString(ms.ToArray());}catch(Exceptionef){returnef.Message;}}classProgram{staticvoidMain(string[]args){Desdes1=newDes();Console.WriteLine("请输入字符串:");stringstr=Console.ReadLine();Console.WriteLine("加密后:");Console.WriteLine(des1.Encrypt(str,"12345678"));Console.WriteLine("解密后:");Console.WriteLine(des1.Decrypt(str,"12345678"));Console.Read();}}}
解决方案
解决方案二:
路过帮顶=============11月6日,论坛升级公告,积分已经做了调整!此次调整增加了两个新的可用分获取渠道:1:帖子被推荐(加精)后,帖主可以获得88分的可用分奖励;2:帖子结帖后会返还帖主50%的悬赏分,无满意结帖不返还分数;3:接下来会不断增加新的可用分获取途径,比如参与活动赠送等,请大家多关注;