Newer
Older
SensorHub / SensorHub.Servers / SM4 / DesTools.cs
root on 17 Sep 2021 4 KB first commit
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SensorHub.Servers.SM4
{
    public class DesTools
    {
        #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)
        {
            byte[] str = strToHexByte(aStrString);
            byte[] key = strToHexByte(aStrKey + aStrKey.Substring(0, 16));

            TripleDESCryptoServiceProvider tdsc = new TripleDESCryptoServiceProvider();
            tdsc.Padding = PaddingMode.None;

            byte[] IV = { 0xB0, 0xA2, 0xB8, 0xA3, 0xDA, 0xCC, 0xDA, 0xCC };
            //指定密匙长度,默认为192位
            tdsc.KeySize = 128;
            //使用指定的key和IV(加密向量)
            Type t = Type.GetType("System.Security.Cryptography.CryptoAPITransformMode");
            object obj = t.GetField("Encrypt", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).GetValue(t);
            MethodInfo mi = tdsc.GetType().GetMethod("_NewEncryptor", BindingFlags.Instance | BindingFlags.NonPublic);
            ICryptoTransform desCrypt = (ICryptoTransform)mi.Invoke(tdsc, new object[] { key, CipherMode.ECB, null, 0, obj });
            tdsc.IV = IV;
            //加密模式,偏移
            tdsc.Mode = CipherMode.ECB;

            //进行加密转换运算
            //ICryptoTransform ct = tdsc.CreateDecryptor();
            //8很关键,加密结果是8字节数组
            byte[] results = desCrypt.TransformFinalBlock(str, 0, str.Length);

            return byteToHexStr(results).ToUpper(); ;

        }

        #endregion


        public static String generalStringToAscii(int length)
        {

            int num = 1;
            for (int i = 0; i < length; i++)
            {
                num *= 10;
            }

            Random rand = new Random();
            String strRandom = (rand.Next(num).ToString()).PadLeft(length, '0');

            StringBuilder sb = new StringBuilder();
            byte[] bytes = Encoding.ASCII.GetBytes(strRandom);
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append((int)bytes[i]);
            }

            return sb.ToString();
        }

        public static String padding80(String data)
        {

            int padlen = 8 - (data.Length / 2) % 8;
            String padstr = "";
            for (int i = 0; i < padlen - 1; i++)
            {
                padstr += "00";
            }
            data = data + "80" + padstr;
            return data;
        }

        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += "0";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <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;
        }
    }
}