欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#编写DES加密、解密类

程序员文章站 2023-01-22 12:54:56
这个c#类封装的des加密解密,可以使用默认秘钥进行加密、解密,也可以自定义秘钥进行加密、解密,调用简单方便。 示例一: using system; usin...

这个c#类封装的des加密解密,可以使用默认秘钥进行加密、解密,也可以自定义秘钥进行加密、解密,调用简单方便。

示例一:

using system;
using system.security.cryptography; 
using system.text;
namespace dotnet.utilities
{
  /// <summary>
  /// des加密/解密类。
  /// </summary>
  public class desencrypt
  {
    public desencrypt()
    {     
    }
 
    #region ========加密========
 
    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static string encrypt(string text)
    {
      return encrypt(text,"sharejs.com");
    }
    /// <summary>
    /// 加密数据
    /// </summary>
    /// <param name="text"></param>
    /// <param name="skey"></param>
    /// <returns></returns>
    public static string encrypt(string text,string skey)
    {
      descryptoserviceprovider des = new descryptoserviceprovider();
      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.memorystream ms=new system.io.memorystream();
      cryptostream cs=new cryptostream(ms,des.createencryptor(),cryptostreammode.write);
      cs.write(inputbytearray,0,inputbytearray.length);
      cs.flushfinalblock();
      stringbuilder ret=new stringbuilder();
      foreach( byte b in ms.toarray())
      {
        ret.appendformat("{0:x2}",b);
      }
      return ret.tostring();
    }
 
    #endregion
     
    #region ========解密========
  
 
    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static string decrypt(string text)
    {
      return decrypt(text,"sharejs.com");
    }
    /// <summary>
    /// 解密数据
    /// </summary>
    /// <param name="text"></param>
    /// <param name="skey"></param>
    /// <returns></returns>
    public static string decrypt(string text,string skey)
    {
      descryptoserviceprovider des = new descryptoserviceprovider();
      int len;
      len=text.length/2;
      byte[] inputbytearray = new byte[len];
      int x,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.memorystream ms=new system.io.memorystream();
      cryptostream cs=new cryptostream(ms,des.createdecryptor(),cryptostreammode.write);
      cs.write(inputbytearray,0,inputbytearray.length);
      cs.flushfinalblock();
      return encoding.default.getstring(ms.toarray());
    }
 
    #endregion
 
 
  }
}

示例二:

///<summary><![cdata[加密解密帮助类]]></summary> 
  public class help_encrypt 
  { 
 
    ///<summary><![cdata[字符串des加密函数]]></summary> 
    ///<param name="str"><![cdata[被加密字符串 ]]></param> 
    ///<param name="key"><![cdata[密钥 ]]></param>  
    ///<returns><![cdata[加密后字符串]]></returns>   
    public static string encode(string str, string key) 
    { 
      try 
      { 
        descryptoserviceprovider provider = new descryptoserviceprovider(); 
        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); 
        memorystream stream = new memorystream(); 
        cryptostream stream2 = new cryptostream(stream, provider.createencryptor(), cryptostreammode.write); 
        stream2.write(bytes, 0, bytes.length); 
        stream2.flushfinalblock(); 
        stringbuilder builder = new stringbuilder(); 
        foreach (byte num in stream.toarray()) 
        { 
          builder.appendformat("{0:x2}", num); 
        } 
        stream.close(); 
        return builder.tostring(); 
      } 
      catch (exception) { return "xxxx"; } 
    } 
    ///<summary><![cdata[字符串des解密函数]]></summary> 
    ///<param name="str"><![cdata[被解密字符串 ]]></param> 
    ///<param name="key"><![cdata[密钥 ]]></param>  
    ///<returns><![cdata[解密后字符串]]></returns>   
    public static string decode(string str, string key) 
    { 
      try 
      { 
        descryptoserviceprovider provider = new descryptoserviceprovider(); 
        provider.key = encoding.ascii.getbytes(key.substring(0, 8)); 
        provider.iv = encoding.ascii.getbytes(key.substring(0, 8)); 
        byte[] buffer = new byte[str.length / 2]; 
        for (int i = 0; i < (str.length / 2); i++) 
        { 
          int num2 = convert.toint32(str.substring(i * 2, 2), 0x10); 
          buffer[i] = (byte)num2; 
        } 
        memorystream stream = new memorystream(); 
        cryptostream stream2 = new cryptostream(stream, provider.createdecryptor(), cryptostreammode.write); 
        stream2.write(buffer, 0, buffer.length); 
        stream2.flushfinalblock(); 
        stream.close(); 
        return encoding.getencoding("gb2312").getstring(stream.toarray()); 
      } 
      catch (exception) { return ""; } 
    } 
  } 
javades加密解密类 
package com.bgxt.messages; 
import java.io.unsupportedencodingexception; 
import java.security.*; 
import javax.crypto.cipher; 
import javax.crypto.secretkey; 
import javax.crypto.secretkeyfactory; 
import javax.crypto.spec.deskeyspec;  
import javax.crypto.spec.ivparameterspec; 
/** 
* 字符串工具集合 
* @author liudong 
*/ 
public class stringutils { 
 
private static final string password_crypt_key = xmlutil.getconfig().getpasswdkey().substring(0,8);  
//private final static string des = "des";  
//private static final byte[] deskey;  
//解密数据   
public static string decrypt(string message,string key) throws exception {   
     
    byte[] bytesrc =converthexstring(message);    
    cipher cipher = cipher.getinstance("des/cbc/pkcs5padding");     
    deskeyspec deskeyspec = new deskeyspec(key.getbytes("utf-8"));    
    secretkeyfactory keyfactory = secretkeyfactory.getinstance("des");    
    secretkey secretkey = keyfactory.generatesecret(deskeyspec);    
    ivparameterspec iv = new ivparameterspec(key.getbytes("utf-8"));   
    cipher.init(cipher.decrypt_mode, secretkey, iv);      
    byte[] retbyte = cipher.dofinal(bytesrc);     
    return new string(retbyte);   
}  
public static byte[] encrypt(string message, string key)   
    throws exception {   
  cipher cipher = cipher.getinstance("des/cbc/pkcs5padding");  
  deskeyspec deskeyspec = new deskeyspec(key.getbytes("utf-8"));  
  secretkeyfactory keyfactory = secretkeyfactory.getinstance("des");   
  secretkey secretkey = keyfactory.generatesecret(deskeyspec);   
  ivparameterspec iv = new ivparameterspec(key.getbytes("utf-8"));   
  cipher.init(cipher.encrypt_mode, secretkey, iv);  
  return cipher.dofinal(message.getbytes("utf-8"));   
}  
public static string encrypt(string value){ 
string result=""; 
try{ 
value=java.net.urlencoder.encode(value, "utf-8");  
result=tohexstring(encrypt(value, password_crypt_key)).touppercase(); 
}catch(exception ex){ 
  ex.printstacktrace(); 
  return ""; 
} 
return result;  
} 
public static byte[] converthexstring(string ss)   
{   
byte digest[] = new byte[ss.length() / 2];   
for(int i = 0; i < digest.length; i++)   
{   
string bytestring = ss.substring(2 * i, 2 * i + 2);   
int bytevalue = integer.parseint(bytestring, 16);   
digest[i] = (byte)bytevalue;   
}   
return digest;   
}   
public static string tohexstring(byte b[]) {   
  stringbuffer hexstring = new stringbuffer();   
  for (int i = 0; i < b.length; i++) {   
    string plaintext = integer.tohexstring(0xff & b[i]);   
    if (plaintext.length() < 2)   
      plaintext = "0" + plaintext;   
    hexstring.append(plaintext);   
  }    
  return hexstring.tostring();   
}   
public static void main(string[] args) throws exception {   
  string value="01";   
  system.out.println("加密数据:"+value);  
  system.out.println("密码为:"+xmlutil.getconfig().getpasswdkey());  
  string a=encrypt( value);   
  system.out.println("加密后的数据为:"+a);   
}   
} 

以上所述就是本文的全部内容了,希望大家能够喜欢。