C# 双倍长3DES加密,ECB模式。


3DES算法类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace CBC3DES
{
    class Helper3DEScs
    {
        //3DES 加密   
        public static  string getDes3EncryptedText(string key, string IV, string sourceText)
        {
            var des3 = new TripleDESCryptoServiceProvider();

            des3.IV = HexStringToByteArray(IV);
            des3.Key = HexStringToByteArray(key);
            des3.Mode = CipherMode.ECB;         //ECB模式
            des3.Padding = PaddingMode.Zeros;   //0x00填充

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des3.CreateEncryptor(), CryptoStreamMode.Write);

            var data = HexStringToByteArray(sourceText);
            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock();

            var result = ms.ToArray();

            cs.Close();
            ms.Close();

            return ByteArrayToHexString(result);
        }

        //字节数组转换成16进制字符串
        public static string ByteArrayToHexString(byte[] ba)
        {
            string hex = BitConverter.ToString(ba);
            return hex.Replace("-", "");
        }

        private static byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "").Trim();
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }


        /// <summary>
        /// 字节数组转16进制字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }


    }
}

调用3DES双倍长算法进行加密:


string keyStr="30313233343536373938373635343332";
string IVStr = "0000000000000000":
string shuju = "303138393839383930373231373637383736353436393030";

string result = Helper3DEScs.getDes3EncryptedText(keyStr, IVStr, shuju);

结果值:EF80EC3FCE136123F932C0FE396D0E9117FE27803DDB631B


可以使用小工具测试结果的正确性。

小工具下载地址:http://download.csdn.net/detail/zhuni_xingfu/6515687

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值