RC2加密算法在C#的应用

using System;  using System.Security.Cryptography;  using System.Text;  using System.IO;  using System.Windows.Forms;  namespace Curllion  {  public class Crypt  {   ///    /// 新建一个大小为10261B的文件,以便将加密数据写入固定大小的文件。   ///    /// 文件保存的地址,包含文件名   public static void InitBinFile(string filePath)   {   byte[] tmp = new byte[10261];   try //创建文件流,将其内容全部写入0   {   System.IO.FileStream writeFileStream = new FileStream(filePath,   System.IO.FileMode.Create,   System.IO.FileAccess.Write,   System.IO.FileShare.None,512,false);   for(int i = 0 ;i< 10261;i++)   tmp[i] = 0;   writeFileStream.Write(tmp,0,10261);   writeFileStream.Flush();   writeFileStream.Close();   }   catch(System.IO.IOException)   {   MessageBox.Show("文件操作错误!","错误!",MessageBoxButtons.OK,MessageBoxIcon.Error);   }   }   ///    /// 将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,   /// 用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但   /// 一个byte的取值为0-127,所以,用两个byte来存放一个长度。   ///    /// 要加密的文本   /// 要写入的文件   /// 写入第几块,取值为1--10   /// 是否操作成功   public static bool EncryptToFile(string toEncryptText,string filePath,int dataIndex)   {   bool r = false;   if(dataIndex > 10 && dataIndex < 1)   {   MessageBox.Show("数据索引的取值范围在1至10之间!","错误!",   MessageBoxButtons.OK,MessageBoxIcon.Error);   return r;   }   byte[] encrypted;   //初始化向量   byte[] key = {106,51,25,141,157,142,23,111,234,159,187,154,215,34,37,204};   //密匙   byte[] IV = {135,186,133,136,184,149,153,144};   //创建UTF-16 编码,用来在byte[]和string之间转换   System.Text.UnicodeEncoding textConverter = new UnicodeEncoding();   //创建RC2服务   RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();   //打开要写入的文件,主要是为了保持原文件的内容不丢失   System.IO.FileStream tmpFileStream= new FileStream(filePath,   System.IO.FileMode.Open,   System.IO.FileAccess.Read,   System.IO.FileShare.None,1024,true);   byte[] index = new byte[10261];   //将读取的内容写到byte数组   tmpFileStream.Read(index,0,10261);   tmpFileStream.Close();   //定义基本的加密转换运算   System.Security.Cryptography.ICryptoTransform Encryptor = rc2CSP.CreateEncryptor(key,IV);   System.IO.MemoryStream msEncrypt = new MemoryStream();   //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。   System.Security.Cryptography.CryptoStream csEncrypt = new CryptoStream(msEncrypt,   Encryptor,CryptoStreamMode.Write);   //将要加密的文本转换成UTF-16 编码,保存在tmp数组。   byte[] tmp = textConverter.GetBytes(toEncryptText);   //将tmp输入csEncrypt,将通过Encryptor来加密。   csEncrypt.Write(tmp,0,tmp.Length);   //输出到msEnctypt   csEncrypt.FlushFinalBlock();   //将流转成byte[]   encrypted = msEncrypt.ToArray();   if(encrypted.Length>1024)   {   MessageBox.Show("加密后,数据长度大于1KB,无法保存");   return false;   }   //得到加密后数据的大小,将结果存在指定的位置。   index[dataIndex*2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length/128));   index[dataIndex*2] = Convert.ToByte(Convert.ToString(encrypted.Length%128));   //将加密后的结果写入index(覆盖)   for(int i=0;i<encrypted.Length;i++)   index[1024*(dataIndex-1)+21+i]=encrypted[i];   //建立文件流   tmpFileStream = new FileStream(filePath,   System.IO.FileMode.Truncate,   System.IO.FileAccess.Write,   System.IO.FileShare.None,1024,true);   //写文件   tmpFileStream.Write(index,0,10261);   tmpFileStream.Flush();   r = true;   tmpFileStream.Close();   return r;   }   ///    /// 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的   ///    /// 要解密的文件   /// 要从哪一个块中解密   /// 解密后的文本   public static string DecryptFromFile(string filePath,int dataIndex)   {   string r = "";   if(dataIndex > 10 && dataIndex < 1)   {   MessageBox.Show("数据索引的取值范围在1至10之间!","错误!",   MessageBoxButtons.OK,MessageBoxIcon.Error);   return r;   }   byte[] decrypted;   byte[] key = {106,51,25,141,157,142,23,111,234,159,187,154,215,34,37,204};   byte[] IV = {135,186,133,136,184,149,153,144};   System.Text.UnicodeEncoding textConverter = new UnicodeEncoding();   RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();   System.IO.FileStream tmpFileStream = new FileStream(filePath,   System.IO.FileMode.Open,   System.IO.FileAccess.Read,   System.IO.FileShare.None,1024,true);   System.Security.Cryptography.ICryptoTransform Decryptor = rc2CSP.CreateDecryptor(key,IV);   System.IO.MemoryStream msDecrypt = new MemoryStream();   System.Security.Cryptography.CryptoStream csDecrypt = new CryptoStream(msDecrypt,   Decryptor,CryptoStreamMode.Write);   byte[] index = new byte[10261];   tmpFileStream.Read(index,0,10261);   int startIndex = 1024*(dataIndex-1)+21;   int count = index[dataIndex*2 - 1]*128 + index[dataIndex*2];   byte[] tmp = new byte[count];   Array.Copy(index,1024*(dataIndex-1)+21,tmp,0,count);   csDecrypt.Write(tmp,0,count);   csDecrypt.FlushFinalBlock();   decrypted = msDecrypt.ToArray();   r = textConverter.GetString(decrypted,0,decrypted.Length);   tmpFileStream.Close();   return r;   }   ///    /// 将一段文本加密后保存到一个文件   ///    /// 要加密的文本数据   /// 要保存的文件   /// 是否加密成功   public static bool EncryptToFile(string toEncryptText,string filePath)   {   bool r = false;   byte[] encrypted;   byte[] key = {106,51,25,141,157,142,23,111,234,159,187,154,215,34,37,204};   byte[] IV = {135,186,133,136,184,149,153,144};   System.Text.UnicodeEncoding textConverter = new UnicodeEncoding();   RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();   System.IO.FileStream tmpFileStream = new FileStream(filePath,   System.IO.FileMode.OpenOrCreate,   System.IO.FileAccess.Write,   System.IO.FileShare.None,1024,true);   System.Security.Cryptography.ICryptoTransform Encryptor = rc2CSP.CreateEncryptor(key,IV);   System.IO.MemoryStream msEncrypt = new MemoryStream();   System.Security.Cryptography.CryptoStream csEncrypt = new CryptoStream(msEncrypt,   Encryptor,CryptoStreamMode.Write);   byte[] tmp = textConverter.GetBytes(toEncryptText);   csEncrypt.Write(tmp,0,tmp.Length);   csEncrypt.FlushFinalBlock();   encrypted = msEncrypt.ToArray();   tmpFileStream.Write(encrypted,0,encrypted.Length);   tmpFileStream.Flush();   r = true;   tmpFileStream.Close();   return r;   }   ///    /// 将一个被加密的文件解密   ///    /// 要解密的文件   /// 解密后的文本   public static string DecryptFromFile(string filePath)   {   string r = "";   byte[] decrypted;   byte[] key = {106,51,25,141,157,142,23,111,234,159,187,154,215,34,37,204};   byte[] IV = {135,186,133,136,184,149,153,144};   System.Text.UnicodeEncoding textConverter = new UnicodeEncoding();   RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();   System.IO.FileStream tmpFileStream = new FileStream(filePath,   System.IO.FileMode.Open,   System.IO.FileAccess.Read,   System.IO.FileShare.None,1024,true);   System.Security.Cryptography.ICryptoTransform Decryptor = rc2CSP.CreateDecryptor(key,IV);   System.IO.MemoryStream msDecrypt = new MemoryStream();   System.Security.Cryptography.CryptoStream csDecrypt = new CryptoStream(msDecrypt,   Decryptor,CryptoStreamMode.Write);   byte[] tmp = new byte[tmpFileStream.Length];   tmpFileStream.Read(tmp,0,tmp.Length);   csDecrypt.Write(tmp,0,tmp.Length);   csDecrypt.FlushFinalBlock();   decrypted = msDecrypt.ToArray();   r = textConverter.GetString(decrypted,0,decrypted.Length);   tmpFileStream.Close();   return r;   }  }  }
RC2是由著名密码学家Ron Rivest设计的一种传统对称分组加密算法,它可作为DES算法的建议替代算法。它的输入和输出都是64比特。密钥的长度是从8字节到128字节可变,但目前的实现是8字节(1998年)。 此算法被设计为可容易地在16位的微处理器上实现。在一个IBM AT机上,RC2加密算法的执行可比DES算法快两倍(假设进行密钥扩展)。在C#中用RC2CryptoServiceProvider可以实现此算法。 算法原理: 1.根据计算机cpu序列号 ,硬盘ID,网卡硬件地址 号生成注册码: //获取机器码 public static string getMachineCode() { string machineCode = ""; MD5CryptoServiceProvider provider1; byte[] array1; string text1; string text2; byte num1; byte[] array2; int num2; provider1 = new MD5CryptoServiceProvider(); string cpuInfo = "";//cpu序列号 ManagementClass cimobject = new ManagementClass("Win32_Processor"); ManagementObjectCollection moc = cimobject.GetInstances(); foreach (ManagementObject mo in moc) { cpuInfo += mo.Properties["ProcessorId"].Value.ToString(); } //获取硬盘ID string HDid = ""; ManagementClass cimobjectHDid = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection mocHDid = cimobjectHDid.GetInstances(); foreach (ManagementObject mo in mocHDid) { HDid += (string)mo.Properties["Model"].Value; } //获取网卡硬件地址 string strMac = ""; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection mocMac = mc.GetInstances(); foreach (ManagementObject mo in mocMac) { if ((bool)mo["IPEnabled"] == true) strMac += mo["MacAddress"].ToString(); mo.Dispose(); } array1 = provider1.ComputeHash(Encoding.Default.GetBytes(cpuInfo + strMac)); text1 = "ENTOPYMICROSYSTEMSDEVINIMMUHENDISLIK231456789ACD23456789AEFABGHJKLMNPRSTUVWYZXAHMETALIAKKASHAKANESKICI"; text2 = string.Empty; array2 = array1; for (num2 = 0; (num2 < array2.Length); num2 = (num2 + 1)) { num1 = array2[num2]; text2 = string.Concat(text2, text1.Substring((num1 % text1.Length), 1)); } machineCode = text2.Substring(0, 10); return machineCode; } 2.根据注册码按照RC2生成注册码: //根据算法得到注册码 public static string getRegisterCode(string machineCode,string _configName) { string computeCode = ""; byte[] array1, array2, array3, array4; MemoryStream stream1 = new MemoryStream(); BinaryFormatter formatter1 = new BinaryFormatter(); formatter1.Serialize(stream1, machineCode); array1 = stream1.ToArray(); RC2CryptoServiceProvider provider11 = new RC2CryptoServiceProvider(); provider11.KeySize = 128; #region byte[] str1 = new byte[8] ; byte[] str2 = new byte[16] ; DataTable dt = Xml.GetAllDataFromXml("Config.xml"); if (dt != null && dt.Rows.Count > 0) { foreach(DataRow dr in dt.Rows) { if (dr[1].ToString() == _configName) { str1 = new byte[] { byte.Parse(dr[2].ToString()), byte.Parse(dr[3].ToString()), byte.Parse(dr[4].ToString()), byte.Parse(dr[5].ToString()), byte.Parse(dr[6].ToString()), byte.Parse(dr[7].ToString()), byte.Parse(dr[8].ToString()), byte.Parse(dr[9].ToString()) }; str2 = new byte[] { byte.Parse(dr[10].ToString()), byte.Parse(dr[11].ToString()), byte.Parse(dr[12].ToString()), byte.Parse(dr[13].ToString()), byte.Parse(dr[14].ToString()), byte.Parse(dr[15].ToString()), byte.Parse(dr[16].ToString()), byte.Parse(dr[17].ToString()), byte.Parse(dr[18].ToString()), byte.Parse(dr[19].ToString()), byte.Parse(dr[20].ToString()), byte.Parse(dr[21].ToString()), byte.Parse(dr[22].ToString()), byte.Parse(dr[23].ToString()),byte.Parse(dr[24].ToString()),byte.Parse(dr[25].ToString()) }; break; } } } #endregion array2 =str1 ; array3 = str2 ; provider11.IV = array2; provider11.Key = array2; ICryptoTransform transform1 = provider11.CreateEncryptor(); stream1 = new MemoryStream(); CryptoStream stream2 = new CryptoStream(stream1, transform1, System.Security.Cryptography.CryptoStreamMode.Write); try { stream2.Write(array1, 0, array1.Length); stream2.FlushFinalBlock(); array4 = stream1.ToArray(); } finally { stream1.Close(); stream2.Close(); } stream1 = new MemoryStream(); formatter1.Serialize(stream1, array4); computeCode = Convert.ToBase64String(stream1.ToArray()).Trim(); return computeCode; } 3.check public static bool checkRegisterCode(string machineCode, string registerCode,string configName) { string computeCode = getRegisterCode(machineCode, configName); if (computeCode == registerCode) { return true; } else return false; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值