星期零

技术改变生活,分享让我们快乐!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#的DES加密解密算法【vs2005】

Posted on 2007-12-05 09:43  weekzero  阅读(22961)  评论(6编辑  收藏  举报

des是常用的对称加密解密方法,下面是C#下的核心代码

/// <summary>
        
/// 进行DES加密。
        
/// </summary>
        
/// <param name="pToEncrypt">要加密的字符串。</param>
        
/// <param name="sKey">密钥,且必须为8位。</param>
        
/// <returns>以Base64格式返回的加密字符串。</returns>

        public string Encrypt(string pToEncrypt, string sKey)
        
{
            
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            
{
                
byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
                des.Key 
= ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV 
= ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
                
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                
{
                    cs.Write(inputByteArray, 
0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }

                
string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                
return str;
            }

        }


        
/// <summary>
        
/// 进行DES解密。
        
/// </summary>
        
/// <param name="pToDecrypt">要解密的以Base64</param>
        
/// <param name="sKey">密钥,且必须为8位。</param>
        
/// <returns>已解密的字符串。</returns>

        public string Decrypt(string pToDecrypt, string sKey)
        
{
            
byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
            
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            
{
                des.Key 
= ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV 
= ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
                
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                
{
                    cs.Write(inputByteArray, 
0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }

                
string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                
return str;
            }

        }
        


在代码中还要应用个类库:using System.Security.Cryptography;
des加密在java中也有相应的算法,而且和.net下的一致,可以用于不同语言编写的系统的加解密调用
下面一段为java下的des加密,C#下的解密小例子:

java中使用DES加密,C#中解密过程如下,
java中的加密代码,DES.java类代码:

————————————————————————————————————————————————
package welcome;

import javax.crypto.*;
import javax.crypto.*;
import java.io.UnsupportedEncodingException;
import java.security.spec.*;
import javax.crypto.spec.*;

public class DES {

    
public DES()
    {
    }

     
public String encrypt(String str) {

        
byte[] enc = null;
        
try {
          enc 
= desEncrypt(str, "abcdefgh");
        }
        
catch (Exception ex) {
        }
       
         
return new sun.misc.BASE64Encoder().encode(enc);
     }
     
     
public static byte[] desEncrypt(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"));
         }
}

————————————————————————————————————————————————

调用示例代码,jsp1.jsp:

————————————————————————————————————————————————

<%@ page contentType="text/html; charset=gb2312" %>
<jsp:useBean id="DES" scope="page" class="welcome.DES" />
<html>
<head><title>DES File</title></head>

<body bgcolor="#FFFFFF">
<div align="center"><center>
<%
String Test 
= request.getParameter("Test");
if(Test==null || Test.equals("")) {
%>
    
<form name="form" method="post" action="jsp1.jsp">
    
<input type="text" name="Test" size="25" value=""/>
    
<input type="submit" name="button" value=" 确定 "/>
    
</form>
    
<%
}
else{
            out.println(
"加密前的数据:"+Test +"<br/>");
            out.println(
"加密后的数据:"+DES.encrypt(Test) +"<br/><a href='http://localhost:9003/JiaMi.aspx?str="+DES.encrypt(Test)+"' target=_blank>连接</a>");
      }
    
%>
</center></div>
</body>
</html>


————————————————————————————————————————————————

C#中的解码函数:

/// <summary>
//
/ 进行DES解密。
//
/ </summary>
//
/ <param name="pToDecrypt">要解密的以Base64</param>
//
/ <returns>已解密的字符串。</returns>
public string Decrypt(string pToDecrypt,string sKey)
{
    
byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
    using(DESCryptoServiceProvider des 
= new DESCryptoServiceProvider())
    {
        des.Key
=ASCIIEncoding.ASCII.GetBytes(sKey);
        des.IV
=ASCIIEncoding.ASCII.GetBytes(sKey);
        System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
        using(CryptoStream cs 
= new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write))
        {
            cs.Write(inputByteArray,
0,inputByteArray.Length);
            cs.FlushFinalBlock();
            cs.Close();
        }
        string str 
= Encoding.UTF8.GetString(ms.ToArray());
        ms.Close();
        
return str;
    }
}
————————————————————————————————————————————————
调用:
string str 
= Page.Request.QueryString["str"];
Page.Response.Write(
"得到的为:"+Decrypt(str,"abcdefgh"));