【java学习】DES加密解密算法详解

来源:互联网 发布:软件架构师课程 编辑:程序博客网 时间:2024/05/08 00:19

1,概念

 1)数据加密标准(DES,Data Encryption Standard):

   是一种使用密钥加密的块密码。

   基于使用56位密钥的对称算法。

 2)对称加密(私钥加密、传统密码算法、秘密密钥算法、单密钥算法):

   指加密和解密使用相同密钥的加密算法,加密密钥能从解密密钥中推算出来,同时解密密钥也能从加密密钥中推算出来。

   特点:算法公开、计算量小、加密速度快、加密效率高。不足之处是,交易双方都使用同样钥匙,安全性得不到保证。

2,Java实现

package function;import javax.crypto.*;import javax.crypto.spec.DESKeySpec;import javax.crypto.spec.IvParameterSpec;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import java.security.Key;import java.security.spec.AlgorithmParameterSpec;/*** 使用DES加密和解密的方法*/public class Des {   private final byte[] DESkey = "abcdefgh".getBytes("UTF-8");// 设置密钥,略去   private final byte[] DESIV = {0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};// 设置向量,略去   private AlgorithmParameterSpec iv = null;// 加密算法的参数接口,IvParameterSpec是它的一个实现   private Key key = null;   public Des() throws Exception {       DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数       iv = new IvParameterSpec(DESIV);// 设置向量       SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂       key = keyFactory.generateSecret(keySpec);// 得到密钥对象   }   /**    * 加密    * @param data    * @return    * @throws Exception    */   public String encode(String data) throws Exception {       Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher       enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量       byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));       BASE64Encoder base64Encoder = new BASE64Encoder();       return base64Encoder.encode(pasByte);   }   /**    * 解密    * @param data    * @return    * @throws Exception    */   public String decode(String data) throws Exception {       Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");       deCipher.init(Cipher.DECRYPT_MODE, key, iv);       BASE64Decoder base64Decoder = new BASE64Decoder();       byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));       return new String(pasByte, "UTF-8");   }}

3,C#实现

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Security.Cryptography;using System.Text;namespace RESTServiceWxzp.Method{    /// <summary>    /// 加密类    /// </summary>    public class EncryptDecrypt    {        #region 必要变量        //默认密钥向量        private static byte[] pri_Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };        private readonly static string pri_encryptKey = "abcdefgh";        #endregion        public EncryptDecrypt()        {        }        /// <summary>        /// DES加密字符串        /// </summary>        /// <param name="par_EncryptString">待加密的字符串</param>        /// <param name="encryptKey">加密密钥,要求为8位</param>        /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>        public static string EncryptDES(string par_EncryptString)        {            try            {                byte[] rgbKey = Encoding.UTF8.GetBytes(pri_encryptKey.Substring(0, 8));                byte[] rgbIV = pri_Keys;                byte[] inputByteArray = Encoding.UTF8.GetBytes(par_EncryptString);                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();                MemoryStream mStream = new MemoryStream();                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);                cStream.Write(inputByteArray, 0, inputByteArray.Length);                cStream.FlushFinalBlock();                return Convert.ToBase64String(mStream.ToArray());            }            catch            {                return par_EncryptString;            }        }        /// <summary>        /// DES解密字符串        /// </summary>        /// <param name="par_decryptString">待解密的字符串</param>        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>        /// <returns>解密成功返回解密后的字符串,失败返源串</returns>        public static string DecryptDES(string par_decryptString)        {            try            {                byte[] rgbKey = Encoding.UTF8.GetBytes(pri_encryptKey);                byte[] rgbIV = pri_Keys;                byte[] inputByteArray = Convert.FromBase64String(par_decryptString);                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();                MemoryStream mStream = new MemoryStream();                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);                cStream.Write(inputByteArray, 0, inputByteArray.Length);                cStream.FlushFinalBlock();                return Encoding.UTF8.GetString(mStream.ToArray());            }            catch            {                return string.Empty;            }        }    }}


0 0