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


    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"));


  • 相关阅读:
    Python脚本运行出现语法错误:IndentationError: unindent does not match any outer indentation level
    Python3 运算符
    Python3 注释
    Python3 解释器
    Python3 环境搭建
    Python 3 教程
    Python3 基本数据类型
    趣闻|Python之禅(The Zen of Python)
    ios开发笔记根据传入字符串的长度动态生成label,并按照屏幕宽度排列
    iOS开发设置tableview的分割线
  • 原文地址:https://www.cnblogs.com/weekzero/p/983143.html
Copyright © 2020-2023  润新知