Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26284
  • 博文数量: 19
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-30 12:33
文章分类
文章存档

2014年(19)

我的朋友
最近访客

分类: C#/.net

2014-08-30 12:40:41

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32; //对注册表操作
using System.Collections; //使用Arraylist
using System.Security.Cryptography;//加密解密
using System.IO;    //文件操作
using System.Runtime.InteropServices;//调用DLL DllImport
using System.Management;  //获取硬件信息
using System.Net;       //获取IP地址是用到
using System.Drawing;   //image 
using System.Net.NetworkInformation;    //ping 用到
using System.Text.RegularExpressions;   //正则
using System.Data;
using System.Data.SqlClient;
using Microsoft.VisualBasic;   //简体转繁体时用到
using System.Web;       //html UrlEncode
 
 技术参考:bet4584.com/
//注册表操作
    public class GF_RegReadWrite
    {
        
        /// 
        /// 读取路径为keypath,键名为keyname的注册表键值,缺省返回def
        /// 
        /// 
        /// 路径
        /// 键名
        /// 默认为null
        ///         
        static public bool GetRegVal(RegistryKey rootkey, string keypath, string keyname, out string rtn)
        {
            rtn = "";
            try
            {
                RegistryKey key = rootkey.OpenSubKey(keypath);
                rtn = key.GetValue(keyname).ToString();
                key.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
      
        /// 
        /// 设置路径为keypath,键名为keyname的注册表键值为keyval
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        static public bool SetRegVal(RegistryKey rootkey, string keypath, string keyname, string keyval)
        {
            try
            {
                RegistryKey key = rootkey.OpenSubKey(keypath, true);
                if (key == null)
                    key = rootkey.CreateSubKey(keypath);
                key.SetValue(keyname, (object)keyval);
                key.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        /// 创建路径为keypath的键
        private RegistryKey CreateRegKey(RegistryKey rootkey, string keypath)
        {
            try
            {
                return rootkey.CreateSubKey(keypath);
            }
            catch
            {
                return null;
            }
        }
        /// 删除路径为keypath的子项
        private bool DelRegSubKey(RegistryKey rootkey, string keypath)
        {
            try
            {
                rootkey.DeleteSubKey(keypath);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// 删除路径为keypath的子项及其附属子项
        private bool DelRegSubKeyTree(RegistryKey rootkey, string keypath)
        {
            try
            {
                rootkey.DeleteSubKeyTree(keypath);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// 删除路径为keypath下键名为keyname的键值
        private bool DelRegKeyVal(RegistryKey rootkey, string keypath, string keyname)
        {
            try
            {
                RegistryKey key = rootkey.OpenSubKey(keypath, true);
                key.DeleteValue(keyname);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
 技术参考:bet2431.com/
 
//类型转换
    public class GF_Convert
    {
        /// 
        /// 字符串 转换 char数组
        /// 
        /// 
        /// 
        /// 
        public static char[] string2chararray(string in_str, int in_len)
        {
            char[] ch = new char[in_len];
            in_str.ToCharArray().CopyTo(ch, 0);
            return ch;
        }
 
        /// 
        /// char数组 转换 字符串
        /// 
        /// 
        ///         
        public static string chararray2string(char[] in_str)
        {
            string out_str;
            out_str = new string(in_str);
            int i = out_str.IndexOf('\0', 0);
            if (i == -1)
                i = 16;
            return out_str.Substring(0, i);
        }
 
        /// 
        /// byte数组 转换 字符串
        /// 
        /// 
        /// 
        public static string bytearray2string(byte[] in_str)
        {
            string out_str;
            out_str = System.Text.Encoding.Default.GetString(in_str);
            return out_str.Substring(0, out_str.IndexOf('\0', 0));
 
        }
 
        /// 
        /// 字符串 转换 byte数组  注意转换出来会使原来的bytearray长度变短
        /// 
        /// 
        /// 
        public static byte[] string2bytearray(string in_str)
        {
            return System.Text.Encoding.Default.GetBytes(in_str);
        }
 
        /// 
        /// 字符串 转换 byte数组  长度为传如的长度
        /// 
        /// 传入字符串
        /// 目标字节数组长度
        /// 
        public static byte[] string2bytearray(string in_str, int iLen)
        {
            byte[] bytes = new byte[iLen];
            byte[] bsources=System.Text.Encoding.Default.GetBytes(in_str);
            Array.Copy(bsources, bytes, bsources.Length);
             
             
            return bytes;
        }
         
        /// 
        /// 将字符串编码为Base64字符串
        /// 
        /// 
        /// 
        public static string Base64Encode(string str)
        {
            byte[] barray;
            barray = Encoding.Default.GetBytes(str);
            return Convert.ToBase64String(barray);
        }
 
        /// 
        /// 将Base64字符串解码为普通字符串
        /// 
        /// 
        /// 
        public static string Base64Decode(string str)
        {
            byte[] barray;
            try
            {
                barray = Convert.FromBase64String(str);
                return Encoding.Default.GetString(barray);
            }
            catch
            {
                return str;
            }
        }
 
        /// 
        /// 图片 转换 byte数组
        /// 
        /// 
        /// 
        /// 
        public static byte[] image_Image2Byte(Image pic, System.Drawing.Imaging.ImageFormat fmt)
        {
            MemoryStream mem = new MemoryStream();
            pic.Save(mem, fmt);
            mem.Flush();
            return mem.ToArray();
        }
        /// 
        /// byte数组 转换 图片
        /// 
        /// 
        /// 
        public static Image image_Byte2Image(byte[] bytes)
        {
            MemoryStream mem = new MemoryStream(bytes, true);
            mem.Read(bytes, 0, bytes.Length);
            mem.Flush();
            Image aa = Image.FromStream(mem);
            return aa;
        }
                 
        /// 
        /// ip 转换 长整形
        /// 
        /// 
        /// 
        public static long IP2Long(string strIP)
        {
 
            long[] ip = new long[4];
 
            string[] s = strIP.Split('.');
            ip[0] = long.Parse(s[0]);
            ip[1] = long.Parse(s[1]);
            ip[2] = long.Parse(s[2]);
            ip[3] = long.Parse(s[3]);
 
            return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
        }
 
        /// 
        /// 长整形 转换 IP
        /// 
        /// 
        /// 
        public static string Long2IP(long longIP)
        {
 
 
            StringBuilder sb = new StringBuilder("");
            sb.Append(longIP >> 24);
            sb.Append(".");
 
            //将高8位置0,然后右移16为
 
 
            sb.Append((longIP & 0x00FFFFFF) >> 16);
            sb.Append(".");
 
 
            sb.Append((longIP & 0x0000FFFF) >> 8);
            sb.Append(".");
 
            sb.Append((longIP & 0x000000FF));
 
 
            return sb.ToString();
        }
 
        /// 
        /// 将8位日期型整型数据转换为日期字符串数据
        /// 
        /// 整型日期
        /// 是否以中文年月日输出
        /// 
        public static string FormatDate(int date, bool chnType)
        {
            string dateStr = date.ToString();
 
            if (date <= 0 || dateStr.Length != 8)
                return dateStr;
 
            if (chnType)
                return dateStr.Substring(0, 4) + "年" + dateStr.Substring(4, 2) + "月" + dateStr.Substring(6) + "日";
 
            return dateStr.Substring(0, 4) + "-" + dateStr.Substring(4, 2) + "-" + dateStr.Substring(6);
        }
 
 
        /// 
        /// string型转换为bool型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的bool类型结果
        public static bool StrToBool(object expression, bool defValue)
        {
            if (expression != null)
                return StrToBool(expression, defValue);
 
            return defValue;
        }
 
        /// 
        /// string型转换为bool型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的bool类型结果
        public static bool StrToBool(string expression, bool defValue)
        {
            if (expression != null)
            {
                if (string.Compare(expression, "true", true) == 0)
                    return true;
                else if (string.Compare(expression, "false", true) == 0)
                    return false;
            }
            return defValue;
        }
 
 /// 
        /// 将对象转换为Int32类型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的int类型结果
        public static int ObjectToInt(object expression)
        {
            return ObjectToInt(expression, 0);
        }
 
        /// 
        /// 将对象转换为Int32类型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的int类型结果
        public static int ObjectToInt(object expression, int defValue)
        {
            if (expression != null)
                return StrToInt(expression.ToString(), defValue);
 
            return defValue;
        }
 
        /// 
        /// 将对象转换为Int32类型,转换失败返回0
        /// 
        /// 要转换的字符串
        /// 转换后的int类型结果
        public static int StrToInt(string str)
        {
            return StrToInt(str, 0);
        }
 
        /// 
        /// 将对象转换为Int32类型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的int类型结果
        public static int StrToInt(string str, int defValue)
        {
            if (string.IsNullOrEmpty(str) || str.Trim().Length >= 11 || !Regex.IsMatch(str.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))
                return defValue;
 
            int rv;
            if (Int32.TryParse(str, out rv))
                return rv;
 
            return Convert.ToInt32(StrToFloat(str, defValue));
        }
 
        /// 
        /// string型转换为float型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的int类型结果
        public static float StrToFloat(object strValue, float defValue)
        {
            if ((strValue == null))
                return defValue;
 
            return StrToFloat(strValue.ToString(), defValue);
        }
 
        /// 
        /// string型转换为float型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的int类型结果
        public static float ObjectToFloat(object strValue, float defValue)
        {
            if ((strValue == null))
                return defValue;
 
            return StrToFloat(strValue.ToString(), defValue);
        }
 
        /// 
        /// string型转换为float型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的int类型结果
        public static float ObjectToFloat(object strValue)
        {
            return ObjectToFloat(strValue.ToString(), 0);
        }
 
        /// 
        /// string型转换为float型
        /// 
        /// 要转换的字符串
        /// 转换后的int类型结果
        public static float StrToFloat(string strValue)
        {
            if ((strValue == null))
                return 0;
 
            return StrToFloat(strValue.ToString(), 0);
        }
 
        /// 
        /// string型转换为float型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的int类型结果
        public static float StrToFloat(string strValue, float defValue)
        {
            if ((strValue == null) || (strValue.Length > 10))
                return defValue;
 
            float intValue = defValue;
            if (strValue != null)
            {
                bool IsFloat = Regex.IsMatch(strValue, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
                if (IsFloat)
                    float.TryParse(strValue, out intValue);
            }
            return intValue;
        }
 
        /// 
        /// 将对象转换为日期时间类型
        /// 
        /// 要转换的字符串
        /// 缺省值
        /// 转换后的int类型结果
        public static DateTime StrToDateTime(string str, DateTime defValue)
        {
            if (!string.IsNullOrEmpty(str))
            {
                DateTime dateTime;
                if (DateTime.TryParse(str, out dateTime))
                    return dateTime;
            }
            return defValue;
        }
 
        /// 
        /// 将对象转换为日期时间类型
        /// 
        /// 要转换的字符串
        /// 转换后的int类型结果
        public static DateTime StrToDateTime(string str)
        {
            return StrToDateTime(str, DateTime.Now);
        }
 
        /// 
        /// 将对象转换为日期时间类型
        /// 
        /// 要转换的对象
        /// 转换后的int类型结果
        public static DateTime ObjectToDateTime(object obj)
        {
            return StrToDateTime(obj.ToString());
        }
 
        /// 
        /// 将对象转换为日期时间类型
        /// 
        /// 要转换的对象
        /// 缺省值
        /// 转换后的int类型结果
        public static DateTime ObjectToDateTime(object obj, DateTime defValue)
        {
            return StrToDateTime(obj.ToString(), defValue);
        }
 
        /// 
        /// 替换回车换行符为html换行符
        /// 
        public static string StrFormat(string str)
        {
            string str2;
 
            if (str == null)
            {
                str2 = "";
            }
            else
            {
                str = str.Replace("\r\n", "");
                str = str.Replace("\n", "");
                str2 = str;
            }
            return str2;
        }
 
        /// 
        /// 转换为简体中文
        /// 
        public static string ToSChinese(string str)
        {
            return Strings.StrConv(str, VbStrConv.SimplifiedChinese, 0);
             
        }
 
        /// 
        /// 转换为繁体中文
        /// 
        public static string ToTChinese(string str)
        {
            return Strings.StrConv(str, VbStrConv.TraditionalChinese, 0);
             
        }
 
 
        /// 
        /// 清除字符串数组中的重复项
        /// 
        /// 字符串数组
        /// 字符串数组中单个元素的最大长度
        /// 
        public static string[] DistinctStringArray(string[] strArray, int maxElementLength)
        {
            Hashtable h = new Hashtable();
 
            foreach (string s in strArray)
            {
                string k = s;
                if (maxElementLength > 0 && k.Length > maxElementLength)
                {
                    k = k.Substring(0, maxElementLength);
                }
                h[k.Trim()] = s;
            }
 
            string[] result = new string[h.Count];
 
            h.Keys.CopyTo(result, 0);
 
            return result;
        }
 
        /// 
        /// 清除字符串数组中的重复项
        /// 
        /// 字符串数组
        /// 
        public static string[] DistinctStringArray(string[] strArray)
        {
            return DistinctStringArray(strArray, 0);
        }
 
//加密解密
    public class GF_Encrypt
    {
        /// 
        /// DES加密
        /// 
        /// 加密字符串
        /// 密钥
        /// 
        public static string string_Encrypt(string pToEncrypt, string sKey)
        {
            if (pToEncrypt == "") return "";
            if (sKey.Length < 8) sKey = sKey + "xuE29xWp";
            if (sKey.Length > 8) sKey = sKey.Substring(0, 8);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            //把字符串放到byte数组中  
            //原来使用的UTF8编码,我改成Unicode编码了,不行  
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            //建立加密对象的密钥和偏移量  
            //原文使用ASCIIEncoding.ASCII方法的GetBytes方法  
            //使得输入密码必须输入英文文本  
            des.Key = ASCIIEncoding.Default.GetBytes(sKey);
            des.IV = ASCIIEncoding.Default.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            //Write  the  byte  array  into  the  crypto  stream  
            //(It  will  end  up  in  the  memory  stream)  
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            //Get  the  data  back  from  the  memory  stream,  and  into  a  string  
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                //Format  as  hex  
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }
 
        /// 
        /// DES解密
        /// 
        /// 解密字符串
        /// 解密密钥
        /// 返回值
        ///  
        public static bool string_Decrypt(string pToDecrypt, string sKey, out string outstr)
        {
            if (pToDecrypt == "")
            {
                outstr = "";
                return true;
            };
            if (sKey.Length < 8) sKey = sKey + "xuE29xWp";
            if (sKey.Length > 8) sKey = sKey.Substring(0, 8);
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                //Put  the  input  string  into  the  byte  array  
                byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }
                //建立加密对象的密钥和偏移量,此值重要,不能修改  
                des.Key = ASCIIEncoding.Default.GetBytes(sKey);
                des.IV = ASCIIEncoding.Default.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                //Flush  the  data  through  the  crypto  stream  into  the  memory  stream  
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                //Get  the  decrypted  data  back  from  the  memory  stream  
                //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象  
                StringBuilder ret = new StringBuilder();
                outstr = System.Text.Encoding.Default.GetString(ms.ToArray());
                return true;
            }
            catch
            {
                outstr = "";
                return false;
            }
        }
 
        ///  
        /// 加密
        ///  
        public class AES
        {
            //默认密钥向量
            private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };
 
            public static string Encode(string encryptString, string encryptKey)
            {
                encryptKey = GF_GET.GetSubString(encryptKey, 32, "");
                encryptKey = encryptKey.PadRight(32, ' ');
 
                RijndaelManaged rijndaelProvider = new RijndaelManaged();
                rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
                rijndaelProvider.IV = Keys;
                ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
 
                byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
                byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
 
                return Convert.ToBase64String(encryptedData);
            }
 
            public static string Decode(string decryptString, string decryptKey)
            {
                try
                {
                    decryptKey = GF_GET.GetSubString(decryptKey, 32, "");
                    decryptKey = decryptKey.PadRight(32, ' ');
 
                    RijndaelManaged rijndaelProvider = new RijndaelManaged();
                    rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
                    rijndaelProvider.IV = Keys;
                    ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
 
                    byte[] inputData = Convert.FromBase64String(decryptString);
                    byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
 
                    return Encoding.UTF8.GetString(decryptedData);
                }
                catch
                {
                    return "";
                }
 
            }
 
        }
 技术参考:ylc5426.com/
        ///  
        /// 加密
        ///  
        public class DES
        {
            //默认密钥向量
            private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
 
            /// 
            /// DES加密字符串
            /// 
            /// 待加密的字符串
            /// 加密密钥,要求为8位
            /// 加密成功返回加密后的字符串,失败返回源串
            public static string Encode(string encryptString, string encryptKey)
            {
                encryptKey = GF_GET.GetSubString(encryptKey, 8, "");
                encryptKey = encryptKey.PadRight(8, ' ');
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
 
            }
 
            /// 
            /// DES解密字符串
            /// 
            /// 待解密的字符串
            /// 解密密钥,要求为8位,和加密密钥相同
            /// 解密成功返回解密后的字符串,失败返源串
            public static string Decode(string decryptString, string decryptKey)
            {
                try
                {
                    decryptKey = GF_GET.GetSubString(decryptKey, 8, "");
                    decryptKey = decryptKey.PadRight(8, ' ');
                    byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                    byte[] rgbIV = Keys;
                    byte[] inputByteArray = Convert.FromBase64String(decryptString);
                    DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
 
                    MemoryStream mStream = new MemoryStream();
                    CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                    cStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cStream.FlushFinalBlock();
                    return Encoding.UTF8.GetString(mStream.ToArray());
                }
                catch
                {
                    return "";
                }
            }
        }
 
        /// 
        /// MD5函数
        /// 
        /// 原始字符串
        /// MD5结果
        public static string MD5(string str)
        {
            byte[] b = Encoding.UTF8.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');
 
            return ret;
        }
 
        /// 
        /// SHA256函数
        /// 
        /// /// 原始字符串
        /// SHA256结果
        public static string SHA256(string str)
        {
            byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
            SHA256Managed Sha256 = new SHA256Managed();
            byte[] Result = Sha256.ComputeHash(SHA256Data);
            return Convert.ToBase64String(Result);  //返回长度为44字节的字符串
        }
    }
参考资料:bet7568.com/
阅读(459) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~