C#编写DES加密、解密类
这个C#类封装的DES加密解密,可以使用默认秘钥进行加密、解密,也可以自定义秘钥进行加密、解密,调用简单方便。
示例一:
usingSystem; usingSystem.Security.Cryptography; usingSystem.Text; namespaceDotNet.Utilities { ///<summary> ///DES加密/解密类。 ///</summary> publicclassDESEncrypt { publicDESEncrypt() { } #region========加密======== ///<summary> ///加密 ///</summary> ///<paramname="Text"></param> ///<returns></returns> publicstaticstringEncrypt(stringText) { returnEncrypt(Text,"sharejs.com"); } ///<summary> ///加密数据 ///</summary> ///<paramname="Text"></param> ///<paramname="sKey"></param> ///<returns></returns> publicstaticstringEncrypt(stringText,stringsKey) { DESCryptoServiceProviderdes=newDESCryptoServiceProvider(); byte[]inputByteArray; inputByteArray=Encoding.Default.GetBytes(Text); des.Key=ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey,"md5").Substring(0,8)); des.IV=ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey,"md5").Substring(0,8)); System.IO.MemoryStreamms=newSystem.IO.MemoryStream(); CryptoStreamcs=newCryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write); cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); StringBuilderret=newStringBuilder(); foreach(bytebinms.ToArray()) { ret.AppendFormat("{0:X2}",b); } returnret.ToString(); } #endregion #region========解密======== ///<summary> ///解密 ///</summary> ///<paramname="Text"></param> ///<returns></returns> publicstaticstringDecrypt(stringText) { returnDecrypt(Text,"sharejs.com"); } ///<summary> ///解密数据 ///</summary> ///<paramname="Text"></param> ///<paramname="sKey"></param> ///<returns></returns> publicstaticstringDecrypt(stringText,stringsKey) { DESCryptoServiceProviderdes=newDESCryptoServiceProvider(); intlen; len=Text.Length/2; byte[]inputByteArray=newbyte[len]; intx,i; for(x=0;x<len;x++) { i=Convert.ToInt32(Text.Substring(x*2,2),16); inputByteArray[x]=(byte)i; } des.Key=ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey,"md5").Substring(0,8)); des.IV=ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey,"md5").Substring(0,8)); System.IO.MemoryStreamms=newSystem.IO.MemoryStream(); CryptoStreamcs=newCryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write); cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); returnEncoding.Default.GetString(ms.ToArray()); } #endregion } }
示例二:
///<summary><![CDATA[加密解密帮助类]]></summary> publicclassHelp_Encrypt { ///<summary><![CDATA[字符串DES加密函数]]></summary> ///<paramname="str"><![CDATA[被加密字符串]]></param> ///<paramname="key"><![CDATA[密钥]]></param> ///<returns><![CDATA[加密后字符串]]></returns> publicstaticstringEncode(stringstr,stringkey) { try { DESCryptoServiceProviderprovider=newDESCryptoServiceProvider(); provider.Key=Encoding.ASCII.GetBytes(key.Substring(0,8)); provider.IV=Encoding.ASCII.GetBytes(key.Substring(0,8)); byte[]bytes=Encoding.GetEncoding("GB2312").GetBytes(str); MemoryStreamstream=newMemoryStream(); CryptoStreamstream2=newCryptoStream(stream,provider.CreateEncryptor(),CryptoStreamMode.Write); stream2.Write(bytes,0,bytes.Length); stream2.FlushFinalBlock(); StringBuilderbuilder=newStringBuilder(); foreach(bytenuminstream.ToArray()) { builder.AppendFormat("{0:X2}",num); } stream.Close(); returnbuilder.ToString(); } catch(Exception){return"xxxx";} } ///<summary><![CDATA[字符串DES解密函数]]></summary> ///<paramname="str"><![CDATA[被解密字符串]]></param> ///<paramname="key"><![CDATA[密钥]]></param> ///<returns><![CDATA[解密后字符串]]></returns> publicstaticstringDecode(stringstr,stringkey) { try { DESCryptoServiceProviderprovider=newDESCryptoServiceProvider(); provider.Key=Encoding.ASCII.GetBytes(key.Substring(0,8)); provider.IV=Encoding.ASCII.GetBytes(key.Substring(0,8)); byte[]buffer=newbyte[str.Length/2]; for(inti=0;i<(str.Length/2);i++) { intnum2=Convert.ToInt32(str.Substring(i*2,2),0x10); buffer[i]=(byte)num2; } MemoryStreamstream=newMemoryStream(); CryptoStreamstream2=newCryptoStream(stream,provider.CreateDecryptor(),CryptoStreamMode.Write); stream2.Write(buffer,0,buffer.Length); stream2.FlushFinalBlock(); stream.Close(); returnEncoding.GetEncoding("GB2312").GetString(stream.ToArray()); } catch(Exception){return"";} } } JAVADES加密解密类 packagecom.bgxt.messages; importjava.io.UnsupportedEncodingException; importjava.security.*; importjavax.crypto.Cipher; importjavax.crypto.SecretKey; importjavax.crypto.SecretKeyFactory; importjavax.crypto.spec.DESKeySpec; importjavax.crypto.spec.IvParameterSpec; /** *字符串工具集合 *@authorLiudong */ publicclassStringUtils{ privatestaticfinalStringPASSWORD_CRYPT_KEY=XmlUtil.getConfig().getPasswdKey().substring(0,8); //privatefinalstaticStringDES="DES"; //privatestaticfinalbyte[]desKey; //解密数据 publicstaticStringdecrypt(Stringmessage,Stringkey)throwsException{ byte[]bytesrc=convertHexString(message); Ciphercipher=Cipher.getInstance("DES/CBC/PKCS5Padding"); DESKeySpecdesKeySpec=newDESKeySpec(key.getBytes("UTF-8")); SecretKeyFactorykeyFactory=SecretKeyFactory.getInstance("DES"); SecretKeysecretKey=keyFactory.generateSecret(desKeySpec); IvParameterSpeciv=newIvParameterSpec(key.getBytes("UTF-8")); cipher.init(Cipher.DECRYPT_MODE,secretKey,iv); byte[]retByte=cipher.doFinal(bytesrc); returnnewString(retByte); } publicstaticbyte[]encrypt(Stringmessage,Stringkey) throwsException{ Ciphercipher=Cipher.getInstance("DES/CBC/PKCS5Padding"); DESKeySpecdesKeySpec=newDESKeySpec(key.getBytes("UTF-8")); SecretKeyFactorykeyFactory=SecretKeyFactory.getInstance("DES"); SecretKeysecretKey=keyFactory.generateSecret(desKeySpec); IvParameterSpeciv=newIvParameterSpec(key.getBytes("UTF-8")); cipher.init(Cipher.ENCRYPT_MODE,secretKey,iv); returncipher.doFinal(message.getBytes("UTF-8")); } publicstaticStringencrypt(Stringvalue){ Stringresult=""; try{ value=java.net.URLEncoder.encode(value,"utf-8"); result=toHexString(encrypt(value,PASSWORD_CRYPT_KEY)).toUpperCase(); }catch(Exceptionex){ ex.printStackTrace(); return""; } returnresult; } publicstaticbyte[]convertHexString(Stringss) { bytedigest[]=newbyte[ss.length()/2]; for(inti=0;i<digest.length;i++) { StringbyteString=ss.substring(2*i,2*i+2); intbyteValue=Integer.parseInt(byteString,16); digest[i]=(byte)byteValue; } returndigest; } publicstaticStringtoHexString(byteb[]){ StringBufferhexString=newStringBuffer(); for(inti=0;i<b.length;i++){ StringplainText=Integer.toHexString(0xff&b[i]); if(plainText.length()<2) plainText="0"+plainText; hexString.append(plainText); } returnhexString.toString(); } publicstaticvoidmain(String[]args)throwsException{ Stringvalue="01"; System.out.println("加密数据:"+value); System.out.println("密码为:"+XmlUtil.getConfig().getPasswdKey()); Stringa=encrypt(value); System.out.println("加密后的数据为:"+a); } }
以上所述就是本文的全部内容了,希望大家能够喜欢。