程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 3DES加密詳解

C# 3DES加密詳解

編輯:C#入門知識

C# 3DES加密詳解。本站提示廣大學習愛好者:(C# 3DES加密詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是C# 3DES加密詳解正文


比來一個項目中,由於辦事端是用的java開辟的,客戶端是用的C#,因為通訊部門采取到了3DES加密,所以做個記載,以備今後須要的時刻直接用。

  這是對方(java)的加密算法,和網下流傳的代碼也差不多(主密鑰直接寫逝世了,便利測試)

package org.zwork.market.mina.msg;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zwork.market.MktContants;
public class ThreeEncryptDecrypt {
  private static final Logger LOGGER = LoggerFactory.getLogger(ThreeEncryptDecrypt.class);
  // 界說 加密算法,可用 DES,DESede,Blowfish
  public static final String Algorithm = "DESede";
  public static String DES = "DES/ECB/NoPadding";
  public static String TriDes = "DESede/ECB/NoPadding";
  // des加密
  public static byte[] des_crypt(byte key[], byte data[]) {
    try {
      KeySpec ks = new DESKeySpec(key);
      SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
      SecretKey ky = kf.generateSecret(ks);
      Cipher c = Cipher.getInstance(DES);
      c.init(Cipher.ENCRYPT_MODE, ky);
      return c.doFinal(data);
    } catch (Exception e) {
      LOGGER.error("des_crypt error:", e);
      return null;
    }
  }
  // des解密
  public static byte[] des_decrypt(byte key[], byte data[]) {
    try {
      KeySpec ks = new DESKeySpec(key);
      SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
      SecretKey ky = kf.generateSecret(ks);
      Cipher c = Cipher.getInstance(DES);
      c.init(Cipher.DECRYPT_MODE, ky);
      return c.doFinal(data);
    } catch (Exception e) {
      LOGGER.error("des_decrypt error:", e);
      return null;
    }
  }
  // 3DES加密
  public static byte[] trides_crypt(byte key[], byte data[]) {
    try {
      byte[] k = new byte[24];
      int len = data.length;
      if (data.length % 8 != 0) {
        len = data.length - data.length % 8 + 8;
      }
      byte[] needData = null;
      if (len != 0)
        needData = new byte[len];
      for (int i = 0; i < len; i++) {
        needData[i] = 0x00;
      }
      System.arraycopy(data, 0, needData, 0, data.length);
      if (key.length == 16) {
        System.arraycopy(key, 0, k, 0, key.length);
        System.arraycopy(key, 0, k, 16, 8);
      } else {
        System.arraycopy(key, 0, k, 0, 24);
      }
      KeySpec ks = new DESedeKeySpec(k);
      SecretKeyFactory kf = SecretKeyFactory.getInstance("DESede");
      SecretKey ky = kf.generateSecret(ks);
      Cipher c = Cipher.getInstance(TriDes);
      c.init(Cipher.ENCRYPT_MODE, ky);
      return c.doFinal(needData);
    } catch (Exception e) {
      LOGGER.error("trides_crypt error:", e);
      return null;
    }
  }
  // 3DES解密
  public static byte[] trides_decrypt(byte key[], byte data[]) {
    try {
      byte[] k = new byte[24];
      int len = data.length;
      if (data.length % 8 != 0) {
        len = data.length - data.length % 8 + 8;
      }
      byte[] needData = null;
      if (len != 0)
        needData = new byte[len];
      for (int i = 0; i < len; i++) {
        needData[i] = 0x00;
      }
      System.arraycopy(data, 0, needData, 0, data.length);
      if (key.length == 16) {
        System.arraycopy(key, 0, k, 0, key.length);
        System.arraycopy(key, 0, k, 16, 8);
      } else {
        System.arraycopy(key, 0, k, 0, 24);
      }
      KeySpec ks = new DESedeKeySpec(k);
      SecretKeyFactory kf = SecretKeyFactory.getInstance("DESede");
      SecretKey ky = kf.generateSecret(ks);
      Cipher c = Cipher.getInstance(TriDes);
      c.init(Cipher.DECRYPT_MODE, ky);
      return c.doFinal(needData);
    } catch (Exception e) {
      LOGGER.error("trides_decrypt error:", e);
      return null;
    }
  }
  public static String getPass(String source) {
    byte[] data= hexToBytes(source);
    byte[] key ="111111111111111111111111111a1.1.".getBytes();
    String result = byte2hex(trides_decrypt(key, data)).toUpperCase();
    return result.substring(2, 8);
  }
  public static String byte2hex(byte[] data) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < data.length; i++) {
      String temp = Integer.toHexString(((int) data[i]) & 0xFF);
      for (int t = temp.length(); t < 2; t++) {
        sb.append("0");
      }
      sb.append(temp);
    }
    return sb.toString();
  }
  public static byte[] hexToBytes(String str) {
    if (str == null) {
      return null;
    } else if (str.length() < 2) {
      return null;
    } else {
      int len = str.length() / 2;
      byte[] buffer = new byte[len];
      for (int i = 0; i < len; i++) {
        buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
      }
      return buffer;
    }
  }
}

  由於客戶端只擔任數據加密,所以我這裡只寫了加密的部門。因為java和C#說話很類似,所以我就仿這他們給的java代碼改成C#的,固然也在網上參考了一些代碼,不外中央照樣湧現了些成績,好比C#不支撐弱密鑰(把密鑰弄龐雜點),由於沒留意年夜小寫形成加密成果紛歧致等等。編程這器械一個點都能讓全部體系瓦解,所以小細節很主要!!!

public class DESHelper
{
  /// <summary>
  /// 將暗碼轉成直接數組
  /// </summary>
  /// <param name="str"></param>
  /// <returns></returns>
  public static byte[] HexToBytes(String str)
  {
    if (str == null)
    {
      return null;
    }
    else if (str.Length < 2)
    {
      return null;
    }
    else
    {
      int len = str.Length / 2;
      byte[] buffer = new byte[len];
      for (int i = 0; i < len; i++)
      {
        var temp = str.Substring(i * 2, 2);
        buffer[i] = (byte)Convert.ToInt32(temp, 16);
      }
      return buffer;
    }
  }
  /// <summary>
  /// 3DES加密
  /// </summary>
  /// <param name="key"></param>
  /// <param name="data"></param>
  /// <returns></returns>
  public static byte[] GetDes3EncryptedText(byte[] key, byte[] data)
  {
    byte[] k = new byte[24];
    int len = data.Length;
    if (data.Length % 8 != 0)
    {
      len = data.Length - data.Length % 8 + 8;
    }
    byte[] needData = null;
    if (len != 0)
      needData = new byte[len];
    for (int i = 0; i < len; i++)
    {
      needData[i] = 0x00;
    }
    Buffer.BlockCopy(data, 0, needData, 0, data.Length);
    if (key.Length == 16)
    {
      Buffer.BlockCopy(key, 0, k, 0, key.Length);
      Buffer.BlockCopy(key, 0, k, 16, 8);
    }
    else
    {
      Buffer.BlockCopy(key, 0, k, 0, 24);
    }
    var des3 = new TripleDESCryptoServiceProvider();
    des3.Key = k;
    des3.Mode = CipherMode.ECB;
    des3.Padding = PaddingMode.Zeros;
    using (MemoryStream ms = new MemoryStream())
    using (CryptoStream cs = new CryptoStream(ms, des3.CreateEncryptor(), CryptoStreamMode.Write))
    {
      cs.Write(data, 0, data.Length);
      cs.FlushFinalBlock();
      return ms.ToArray();
    }
  }
  /// <summary>
  /// 將加密成果轉成字符串
  /// </summary>
  /// <param name="data"></param>
  /// <returns></returns>
  public static String GetByte2Hex(byte[] data)
  {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < data.Length; i++)
    {
      String temp = string.Format("{0:X}", ((int)data[i]) & 0xFF);
      for (int t = temp.Length; t < 2; t++)
      {
        sb.Append("0");
      }
      sb.Append(temp);
    }
    return sb.ToString();
  }
}

以上所述就是本文的全體內容了,願望年夜家可以或許愛好。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved