天天看點

.NET程式設計 -- 使用DES加密解密代碼

c#

-----------------------------------------------

//名稱空間  

using  system;  

using  system.security.cryptography;  

using  system.io;  

using  system.text;  

//方法  

//加密方法  

public    string  encrypt(string  ptoencrypt,  string  skey)  

{  

           descryptoserviceprovider  des  =  new  descryptoserviceprovider();  

           //把字元串放到byte數組中  

                 //原來使用的utf8編碼,我改成unicode編碼了,不行  

           byte[]  inputbytearray  =  encoding.default.getbytes(ptoencrypt);  

           //byte[]  inputbytearray=encoding.unicode.getbytes(ptoencrypt);  

           //建立加密對象的密鑰和偏移量  

           //原文使用asciiencoding.ascii方法的getbytes方法  

           //使得輸入密碼必須輸入英文文本  

           des.key  =  asciiencoding.ascii.getbytes(skey);  

           des.iv  =  asciiencoding.ascii.getbytes(skey);  

           memorystream  ms  =  new  memorystream();  

           cryptostream  cs  =  new  cryptostream(ms,  des.createencryptor(),cryptostreammode.write);  

           //write  the  byte  array  into  the  crypto  stream  

           //(it  will  end  up  in  the  memory  stream)  

           cs.write(inputbytearray,  0,  inputbytearray.length);  

           cs.flushfinalblock();  

           //get  the  data  back  from  the  memory  stream,  and  into  a  string  

           stringbuilder  ret  =  new  stringbuilder();  

           foreach(byte  b  in  ms.toarray())  

                       {  

                       //format  as  hex  

                       ret.appendformat("{0:x2}",  b);  

                       }  

           ret.tostring();  

           return  ret.tostring();  

}  

//解密方法  

public    string  decrypt(string  ptodecrypt,  string  skey)  

           //put  the  input  string  into  the  byte  array  

           byte[]  inputbytearray  =  new  byte[ptodecrypt.length  /  2];  

           for(int  x  =  0;  x  <  ptodecrypt.length  /  2;  x++)  

           {  

                     int  i  =  (convert.toint32(ptodecrypt.substring(x  *  2,  2),  16));  

               inputbytearray[x]  =  (byte)i;  

           }  

           //建立加密對象的密鑰和偏移量,此值重要,不能修改  

           cryptostream  cs  =  new  cryptostream(ms,  des.createdecryptor(),cryptostreammode.write);  

           //flush  the  data  through  the  crypto  stream  into  the  memory  stream  

           //get  the  decrypted  data  back  from  the  memory  stream  

           //建立stringbuild對象,createdecrypt使用的是流對象,必須把解密後的文本變成流對象  

           return  system.text.encoding.default.getstring(ms.toarray());