您的位置:首页 > 编程语言 > Java开发

C#(TripleDES)对应Java(3DES)加密工具类

2014-10-14 11:48 246 查看
    3DES又称Triple DES,是DES加密算法的一种模式,它使用3条56位的密钥对3DES数据进行三次加密。
    加密过程为:C=Ek3(Dk2(Ek1(P)))
    解密过程为:P=Dk1(EK2(Dk3(C)))
    C#已经对3DES加密进行了封装,可使用System.Security.Cryptography中的TripleDESCryptoServiceProvider类来实现,项目的需求是采用24位KEY、ECB模式来对应java平台的加解密。其中还涉及unix时间戳,MD5散列,base64编码的综合使用。
    开始的时候对HttpWebRequest认识不深,在对base64的编码“+”符号上犯错,POST与GET请求中“+”【%2B】会出现替换的不同,以至于平台解析不成功。以下是测试后的代码:

using System;
using System.Text;
using System.Security.Cryptography;

namespace TestProject
{
/// <summary>
/// 数据加密工具类
/// </summary>
public sealed class EncryptionUtils
{
#region DES解密
//3DES(DESede>Jave)24位KEY
private const string ENCRYPT_KEY = "3DES_MD5_Timestamp123456";

/// <summary>
/// 3DES加密
/// base64小细节,当使用get请求时,base64生成字符中有“+”号,
/// 注意需要转换“%2B”,否则会被替换成空格。POST不存在
/// while (str.IndexOf('+') != -1) {
///	 str = str.Replace("+","%2B");
//  }
/// </summary>
public static string Encrypt3DES (string fValue)
{
if(string.IsNullOrEmpty(fValue)){
return fValue;
}
try{
Encoding encoding = Encoding.GetEncoding("UTF-8");
var DES = new TripleDESCryptoServiceProvider();
DES.Key = encoding.GetBytes(ENCRYPT_KEY);
DES.Mode = CipherMode.ECB;
ICryptoTransform DESEncrypt = DES.CreateEncryptor();
byte[] Buffer = encoding.GetBytes(fValue);
return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
}catch(Exception ex){
Log.Error("Encrypt3DES>>"+ex.Message);
return string.Empty;
}
}

/// <summary>
/// 3DES解密
/// </summary>
/// <returns>解密串</returns>
/// <param name="a_strString">加密串</param>
public static string Decrypt3DES (string a_strString)
{
if(string.IsNullOrEmpty(a_strString)){
return a_strString;
}
try {
var DES = new TripleDESCryptoServiceProvider ();
DES.Key = ASCIIEncoding.ASCII.GetBytes (ENCRYPT_KEY);
DES.Mode = CipherMode.ECB;
DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
ICryptoTransform DESDecrypt = DES.CreateDecryptor ();
byte[] Buffer = Convert.FromBase64String (a_strString);
return ASCIIEncoding.ASCII.GetString (DESDecrypt.TransformFinalBlock (Buffer, 0, Buffer.Length));
} catch (Exception e) {
Log.Error("Decrypt3DES>>"+e.Message);
return string.Empty;
}
}
#endregion

#region 基础方法
/// <summary>
/// MD5编码
/// </summary>
public static string MD5(string str){
if(string.IsNullOrEmpty(str)){
return str;
}
var md5 = new MD5CryptoServiceProvider();
var datas = Encoding.UTF8.GetBytes(str);
var hash = md5.ComputeHash(datas);
md5.Clear();
str = string.Empty;
//把MD5所得用16进制小写的字符串形式,让函数返回一个32字节长的可打印字符串。
for(int i =0;i<hash.Length;i++){
str += hash[i].ToString("X").PadLeft(2,'0');
}
return str;
}

/// <summary>
/// 并进行base64编码
/// </summary>
public static string ToBase64String(string str){
if(string.IsNullOrEmpty(str)){
return string.Empty;
}
return Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
}

/// <summary>
/// unix时间戳
/// </summary>
public static string GetTimestamp()
{
DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime (new System.DateTime (1970, 1, 1, 0, 0, 0, 0));
DateTime nowTime = DateTime.Now;
long unixTime = (long)Math.Round ((nowTime - startTime).TotalMilliseconds, MidpointRounding.AwayFromZero);
return unixTime.ToString ();
}
#endregion
}

public static class Log
{
public static void Error(string msg)
{
Console.WriteLine ("Error"+msg);
}

public static void Info(string msg)
{
Console.WriteLine ("Info"+msg);
}
}
}
测试代码:

public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");

string line = string.Empty;
while ((line = Console.ReadLine ()) != null) {
var encrypt = EncryptionUtils.Encrypt3DES (line);
var decrypt = EncryptionUtils.Decrypt3DES (encrypt);
Log.Info ("输入>>" + line);
Log.Info ("密文>>" + encrypt);
Log.Info ("明文>>" + decrypt);
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息