C# 3Des加密解密

第三方的加密规则约定:加密经过3DES加密后的Base64 编码

最近在对接一个第三方接口,请求参数和响应参数全采用3des加密规则,由于我是用.NET对接的,而第三方是Java开发的,所以两种程序之间采用的算法有一点差异,java的3des加密采用的是"DESede/CBC/PKCS5Padding"规则,所以对应的C#规则是"PaddingMode.PKCS7和CipherMode.CBC",使用CBC模式的话在C#下必须传入加密向量IV(固定长度8位),默认"12345678",加密密钥和IV双方约定好即可,如果是ECB编码模式,那么就无须使用加密向量。

C#代码如下:

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

namespace TCWireless.Utility

{

public class DESHelper
{
  #region 3des加密

/// <summary>
/// 3des ecb模式加密
/// </summary>
/// <param name="aStrString">待加密的字符串</param>
/// <param name="aStrKey">密钥</param>
/// <param name="iv">加密矢量:只有在CBC解密模式下才适用</param>
/// <param name="mode">运算模式</param>
/// <returns>加密后的字符串</returns>
public static string Encrypt3Des(string aStrString, string aStrKey, CipherMode mode = CipherMode.ECB, string iv = "12345678")
{
  try
  {
    var des = new TripleDESCryptoServiceProvider
    {
      Key = Encoding.UTF8.GetBytes(aStrKey),
      Mode = mode
    };
    if (mode == CipherMode.CBC)
    {
      des.IV = Encoding.UTF8.GetBytes(iv);
    }
    var desEncrypt = des.CreateEncryptor();
    byte[] buffer = Encoding.UTF8.GetBytes(aStrString);
    return Convert.ToBase64String(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length));
  }
  catch (Exception e)
  {
    return string.Empty;
  }
}

#endregion

#region 3des解密

/// <summary>
/// des 解密
/// </summary>
/// <param name="aStrString">加密的字符串</param>
/// <param name="aStrKey">密钥</param>
/// <param name="iv">解密矢量:只有在CBC解密模式下才适用</param>
/// <param name="mode">运算模式</param>
/// <returns>解密的字符串</returns>
public static string Decrypt3Des(string aStrString, string aStrKey, CipherMode mode = CipherMode.ECB, string iv = "12345678")
{
  try
  {
    var des = new TripleDESCryptoServiceProvider
    {
      Key = Encoding.UTF8.GetBytes(aStrKey),
      Mode = mode,
      Padding = PaddingMode.PKCS7
    };
    if (mode == CipherMode.CBC)
    {
      des.IV = Encoding.UTF8.GetBytes(iv);
    }
    var desDecrypt = des.CreateDecryptor();
    var result = "";
    byte[] buffer = Convert.FromBase64String(aStrString);
    result = Encoding.UTF8.GetString(desDecrypt.TransformFinalBlock(buffer, 0, buffer.Length));
    return result;
  }
  catch (Exception e)
  {
    return string.Empty;
  }
}
#endregion

  }
}

posted @ 2015-01-26 14:21  小小周  阅读(17361)  评论(14编辑  收藏  举报