C#对加密算法的一些心得 DES、MD5、RSA

最近几天看加密方法,我的理解并不是很深,但是也有一些总结。

1、DES 这是一种可逆的加密,就是可以加密解密。

2、MD5这是一种只能加密不能解密的方法。

3、RSA加密,这种是让我头疼的方法,今天也是着重说一下这个在C#的用法。


RSA加密,先把代码奉上,这些代码也是网上找到了,也没修改什么

emptynamespace WebSafe
{
 public class RSASafe
    {
        /// 
        /// 生成公私钥
        /// 
        /// 
        /// 
        public static void RSAKey(string PrivateKeyPath, string PublicKeyPath)
        {
            try
            {
                //声明一个RSA算法的实例,由RSACryptoServiceProvider类型的构造函数指定了密钥长度为1024位
                //实例化RSACryptoServiceProvider后,RSACryptoServiceProvider会自动生成密钥信息。
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                //将RSA算法的私钥导出到字符串PrivateKey中,参数为true表示导出私钥
                CreatePrivateKeyXML(PrivateKeyPath, provider.ToXmlString(true));
                //将RSA算法的公钥导出到字符串PublicKey中,参数为false表示不导出私钥
                CreatePublicKeyXML(PublicKeyPath, provider.ToXmlString(false));
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        /// 
        /// 对原始数据进行MD5加密
        /// 
        /// 待加密数据
        /// 
   
   
    
    返回机密后的数据
   
   
        public static string GetHash(string m_strSource)
        {
            HashAlgorithm algorithm = HashAlgorithm.Create("MD5");
            byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
            byte[] inArray = algorithm.ComputeHash(bytes);
            return Convert.ToBase64String(inArray);
        }
        /// 
        /// RSA加密
        /// 
        /// 公钥
        /// MD5加密后的数据
        /// 
   
   
    
    RSA公钥加密后的数据
   
   
        public static string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
        {
            string str2;
            try
            {
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                provider.FromXmlString(xmlPublicKey);
                byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString);
                str2 = Convert.ToBase64String(provider.Encrypt(bytes, false));
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return str2;
        }
        /// 
        /// RSA解密
        /// 
        /// 私钥
        /// 待解密的数据
        /// 
   
   
    
    解密后的结果
   
   
        public static  string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
        {
            string str2;
            try
            {
                RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
                provider.FromXmlString(xmlPrivateKey);
                byte[] rgb = Convert.FromBase64String(m_strDecryptString);
                byte[] buffer2 = provider.Decrypt(rgb, false);
                str2 = new UnicodeEncoding().GetString(buffer2);
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return str2;
        }
        /// 
        /// 对MD5加密后的密文进行签名
        /// 
        /// 私钥
        /// MD5加密后的密文
        /// 
   
   
        public static string SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature)
        {
            byte[] rgbHash = Convert.FromBase64String(m_strHashbyteSignature);
            RSACryptoServiceProvider key = new RSACryptoServiceProvider();
            key.FromXmlString(p_strKeyPrivate);
            RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
            formatter.SetHashAlgorithm("MD5");
            byte[] inArray = formatter.CreateSignature(rgbHash);
            return Convert.ToBase64String(inArray);
        }
        /// 
        /// 签名验证
        /// 
        /// 公钥
        /// 待验证的用户名
        /// 注册码
        /// 
   
   
        public static bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
        {
            try
            {
                byte[] rgbHash = Convert.FromBase64String(p_strHashbyteDeformatter);
                RSACryptoServiceProvider key = new RSACryptoServiceProvider();
                key.FromXmlString(p_strKeyPublic);
                RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
                deformatter.SetHashAlgorithm("MD5");
                byte[] rgbSignature = Convert.FromBase64String(p_strDeformatterData);
                if (deformatter.VerifySignature(rgbHash, rgbSignature))
                {
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
        /// 
        /// 获取硬盘ID
        /// 
        /// 
   
   
    
    硬盘ID
   
   
        public static string GetHardID()
        {
            string HDInfo = "";
            ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection moc1 = cimobject1.GetInstances();
            foreach (ManagementObject mo in moc1)
            {
                HDInfo = (string)mo.Properties["Model"].Value;
            }
            return HDInfo;
        }
        /// 
        /// 获得主板ID
        /// 
        /// 
   
   
        public static string GetBIOSNumber()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_baseboard");
            string biosNumber = null;
            foreach (ManagementObject mgt in searcher.Get())
            {
                biosNumber = mgt["SerialNumber"].ToString();
            }
            return biosNumber;
        }
        /// 
        /// 获得Mac地址
        /// 
        /// 
   
   
        public static string GetMACAddress()
        {
            string MoAddress = "";
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                    MoAddress = mo["MacAddress"].ToString();
                mo.Dispose();
            }
            return MoAddress;
        }
        /// 
        /// 读注册表中指定键的值
        /// 
        /// 键名
        /// 
   
   
    
    返回键值
   
   
        private static string ReadReg(string key)
        {
            string temp = "";
            try
            {
                RegistryKey myKey = Registry.LocalMachine;
                RegistryKey subKey = myKey.OpenSubKey(@"SOFTWARE/JX/Register");


                temp = subKey.GetValue(key).ToString();
                subKey.Close();
                myKey.Close();
                return temp;
            }
            catch (Exception)
            {
                throw;//可能没有此注册项;
            }


        }
        /// 
        /// 创建注册表中指定的键和值
        /// 
        /// 键名
        /// 键值
        private static void WriteReg(string key, string value)
        {
            try
            {
                RegistryKey rootKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE/JX/Register");
                rootKey.SetValue(key, value);
                rootKey.Close();
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// 
        /// 创建公钥文件
        /// 
        /// 
        /// 
        public static void CreatePublicKeyXML(string path, string publickey)
        {
            try
            {
                FileStream publickeyxml = new FileStream(path, FileMode.Create);
                StreamWriter sw = new StreamWriter(publickeyxml);
                sw.WriteLine(publickey);
                sw.Close();
                publickeyxml.Close();
            }
            catch
            {
                throw;
            }
        }
        /// 
        /// 创建私钥文件
        /// 
        /// 
        /// 
        public static void CreatePrivateKeyXML(string path, string privatekey)
        {
            try
            {
                FileStream privatekeyxml = new FileStream(path, FileMode.Create);
                StreamWriter sw = new StreamWriter(privatekeyxml);
                sw.WriteLine(privatekey);
                sw.Close();
                privatekeyxml.Close();
            }
            catch
            {
                throw;
            }
        }
        /// 
        /// 读取公钥
        /// 
        /// 
        /// 
   
   
        public static string ReadPublicKey(string path)
        {
            StreamReader reader = new StreamReader(path);
            string publickey = reader.ReadToEnd();
            reader.Close();
            return publickey;
        }
        /// 
        /// 读取私钥
        /// 
        /// 
        /// 
   
   
        public static string ReadPrivateKey(string path)
        {
            StreamReader reader = new StreamReader(path);
            string privatekey = reader.ReadToEnd();
            reader.Close();
            return privatekey;
        }
        /// 
        /// 初始化注册表,程序运行时调用,在调用之前更新公钥xml
        /// 
        /// 公钥路径
        public static void InitialReg(string path)
        {
            Registry.LocalMachine.CreateSubKey(@"SOFTWARE/JX/Register");
            Random ra = new Random();
            string publickey = ReadPublicKey(path);
            if (Registry.LocalMachine.OpenSubKey(@"SOFTWARE/JX/Register").ValueCount <= 0)
            {
                WriteReg("RegisterRandom", ra.Next(1, 100000).ToString());
                WriteReg("RegisterPublicKey", publickey);
            }
            else
            {
                WriteReg("RegisterPublicKey", publickey);
            }
        } 
    }
}
}

后台使用代码,这些事自己测试使用的例子:


 #region 创建文件


        if (!Directory.Exists(Server.MapPath("KeyFile/PrivatePublicKey")))
        { Directory.CreateDirectory(Server.MapPath("KeyFile/PrivatePublicKey")); }


        if (!File.Exists(privateKeyPath))
            File.Delete(privateKeyPath);
        if (!File.Exists(publicKeyPath))
            File.Delete(publicKeyPath);
        #endregion
        //生成秘钥文件
        WebSafe.RSASafe.RSAKey(privateKeyPath, publicKeyPath);
        //读取私钥
        string privateWord = WebSafe.RSASafe.ReadPrivateKey(privateKeyPath);
        LabPrivateKey.Text = privateWord;
        //读取公钥
        string publicWord = WebSafe.RSASafe.ReadPublicKey(publicKeyPath);
        LabPublicKey.Text = publicWord;
        //加密字符串
        string word = "CB3403924430"; //labMotherBoardID.Text + "*" + labEndDateKey.Text + "*" + labCountKey.Text;
        string Encryptword = WebSafe.RSASafe.GetHash(word);
        //Response.Write("Encryptword:" + Encryptword + "<br/>");
        RSA加密字符串
        string RSAEncryptWord = WebSafe.RSASafe.RSAEncrypt(publicWord, Encryptword);
        LabActivityNumber.Text = RSAEncryptWord;
        //string RSADecryptWord = RSASafe.RSADecrypt(privateWord, RSAEncryptWord);

到最后我并没有使用这种方法,因为C#提供的这种方法只能用公钥加密,私钥解密。网上也查到用私钥加密公钥解密的,但是里面用到一些数学的知识,本人不才参不透,最后下的有例子,用大整数处理的,但是生成的内容是乱码。而且此种方法加密后的字符串长度有点长,而且每次生成的都不一样。如果有需要使用就留作以后再研究吧。


RSASafe这个类中,加密字符串采用的是MD5方法,如果要用可解密的算法,自己看着修改一下,MD5是不可解密的。


最后再奉上DES加密,解密的方法,这种方法我觉得在机密后可以按规则替换一些字符,这样就没有那么好破解了。

      

  /// 
        /// DES加密字符串 
        /// 
        /// 要加密的字符串
        /// 密钥
        /// 
   
   
    
     加密后并经base64编码的字符串 
   
    
        /// 
   
   
    
     静态方法,采用默认ascii编码 
   
   
        public static string DesEncrypt(string strText, string strEncrKey)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Length>8?strEncrKey.Substring(0,8):"abcdefg");
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                //CryptoStream.FlushFinalBlock():用缓冲区的当前状态更新基础数据源或储存库,随后清除缓冲区。
                return Convert.ToBase64String(ms.ToArray()).Replace("+", "%2B");


            }
            catch (System.Exception error)
            {
                return "error:" + error.Message + "\r";
            }
        }


        /// 
        /// DES解密字符串
        /// 
        /// 要解密的字符串
        /// 密钥
        /// 
   
   
    
     加密后并经base64编码的字符串 
   
    
        /// 
   
   
    
     静态方法,采用默认ascii编码 
   
   
        public  static string DesDecrypt(string strText, string sDecrKey)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = new Byte[strText.Length];
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Length > 8 ? sDecrKey.Substring(0, 8) : "abcdefg");
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();//用缓冲区的当前状态更新基础数据源或存储库,随后清除缓冲区。
                System.Text.Encoding encoding = new System.Text.UTF8Encoding();
                return encoding.GetString(ms.ToArray());
            }
            catch (System.Exception error)
            {
                return "error:" + error.Message + "\r";
            }


        }
        
        ///MD5加密
        
          public static string GetHash(string m_strSource)
        {
            HashAlgorithm algorithm = HashAlgorithm.Create("MD5");
            byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
            byte[] inArray = algorithm.ComputeHash(bytes);
            return Convert.ToBase64String(inArray);
        }

可以看一下这些介绍:

代码从哪里copy的找不到网页了,还请原作者见谅。

http://www.cnblogs.com/chengmin/archive/2011/09/26/2192230.html

http://blog.csdn.net/scollins/article/details/5694306

http://blog.csdn.net/mengdong_zy/article/details/41695393


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值