Licence.cs 13.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
//----------------------------------------------------------------
// Copyright (C) 2000-2003 Shangxin Corporation
// All rights reserved.
// 文件名: Licence.cs
// 创建者: 葛卫新
// 创建日期: 2003-12-04
// 概述: 本文件作用是实现对Escalade Licence 验证,存取操作的封装
// 修改纪录:潘小锋
// 备注:该项目使用Hashtable存在隐患,Hashtable的顺序不受人为控制,所以通过去key及value来组成字符串的方式会导致校验时候失败
// ----------------------------------------------------------------

using System;
using System.IO;
using System.Data;
using System.Security.Cryptography;
using System.Text;
using System.Collections;
using System.Xml;
using System.Management;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MyCMMI.CreateLicense
{
	/// <summary>
	/// Licence 的摘要说明。
	/// </summary>
	//[ClassInterfaceAttribute(ClassInterfaceType.AutoDual)] 
	public class Licence
    {

		// xfpan [5/31/2004]
		// 获取硬盘物理序列号
		[DllImport("DiskSerialNo.dll")]
		private static extern string GetDiskSerialNo();

		// 获取网卡序列号
		[DllImport("DiskSerialNo.dll")]
		private static extern string GetMacAddr();
		// xfpan [5/31/2004]

		private string m_LicencePath="";
		private string m_SignedString = "";
		private string PUBLICKEY = "<RSAKeyValue><Modulus>wD+BfPFh06qyNMMjyIZfbSeNSVGppoH4VCR6iVTnsrWm+Czjg24EycKvQfZd9SVYHJMASHuKr0VlBCPye2REs2b9UCT3b+yLqhFrde0v7k6m6FTZe4kH4USmhsQaJstcU94LCRDM3PNfWS3r9qZ11ZtJDmrGH1zFtOJsYBWdZAM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
		UnicodeEncoding ByteConverter = new UnicodeEncoding();
		private bool _IsLoad = false;
		private bool _IsValidated = false;
		private string _LastErrorInfo = "";

		private DataSet m_ds = null;
		private const string TABLENAME = "Value";
 
//		/// <summary>
//		/// 构造函数
//		/// </summary>
//		/// <param name="f_LicencePath">licence文件路径</param>
//		public Licence(string f_LicencePath)
//		{
//			m_LicencePath = f_LicencePath;
//			InitDataSet();
//			Initialize(f_LicencePath);
//		}

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="f_LicencePath">licence文件路径</param>
		public Licence()
		{
			InitDataSet();
		}

		private void InitDataSet()
		{
			m_ds = new DataSet();
			DataTable m_dt = m_ds.Tables.Add(TABLENAME);
			m_dt.Columns.Add("DiskID",typeof(System.String));
			m_dt.Columns.Add("CompanyName",typeof(System.String));
			m_dt.Columns.Add("UserCount",typeof(System.String));
			m_dt.Columns.Add("ProductName",typeof(System.String));
			m_dt.Columns.Add("Version",typeof(System.String));
			m_dt.Columns.Add("FromDate",typeof(System.String));
			m_dt.Columns.Add("ToDate",typeof(System.String));			
		}

		/// <summary>
		/// 初始化
		/// </summary>
		public void Initialize(string f_LicencePath)
		{
			m_LicencePath = f_LicencePath;
			if(LoadLicenceFile())
			{
				_IsLoad = true;
			}
			else
			{
				_IsLoad = false;
			}
		}

		/// <summary>
		/// 加载许可证文件
		/// </summary>
		/// <returns>成功为true,失败为false</returns>
		private bool LoadLicenceFile()
		{
			string f_TmpString = "";
			string f_XmlString = "";
			if(m_ds == null || m_ds.Tables[TABLENAME] == null)
			{
				return false;
			}

			if(!File.Exists(m_LicencePath))
			{
				return false;//文件不存在
			}
			else
			{
				//先以流方式读出
				try
				{
					FileStream fs = File.OpenRead(m_LicencePath);
					StreamReader f_srfs = new StreamReader(fs,System.Text.Encoding.Unicode);
					f_srfs.BaseStream.Seek(0, SeekOrigin.Begin);
					while (f_srfs.Peek() > -1) 
					{
						f_XmlString += f_TmpString;//拼装Xml流
						f_TmpString = f_srfs.ReadLine();
					}
					m_SignedString = f_TmpString;//获取最后一行密文
					f_srfs.Close();
				}
				catch
				{
					return false;
				}
				XmlDocument doc = new XmlDocument();
				//加载Xml流
				try
				{
					doc.LoadXml(f_XmlString);
				}
				catch
				{
					return false;
				}
				XmlNode node =doc.FirstChild;
				int i,nodecount;
				string f_Key = "";
				string f_Value = "";
				
				m_ds.Tables[TABLENAME].Rows.Clear();
				DataRow m_dr = m_ds.Tables[TABLENAME].NewRow();
				nodecount = node.ChildNodes.Count;
				node = node.FirstChild;
				//获取许可证明文值,加载到哈希表中
				for(i=0;i<nodecount;i++)
				{
					f_Key = node.Attributes["key"].Value;
					f_Value = node.Attributes["value"].Value;
					m_dr[f_Key] = f_Value;
					node = node.NextSibling;
				}
				m_ds.Tables[TABLENAME].Rows.Add(m_dr);

				return true;
			}
		}

		/// <summary>
		/// 验证硬件序列号
		/// </summary>
		/// <returns>验证成功为true,不成功为false</returns>
		public bool ValidateSerialNo()
		{
			String DiskID = GetValidateInfo("DiskID");
			WriteLog("The DiskID is " + DiskID + " that read from licensefile");

			String DiskSn = GetDiskID();
			WriteLog("The DiskID is " + DiskSn + " that read from hardware");

			if(DiskID == "" || DiskSn == "" || DiskSn == null || DiskID != DiskSn)
			{
				WriteLog("The DiskID of licensefile (" + DiskID + ") is not equal of the DiskID of hareware (" + DiskSn + ")");
				_LastErrorInfo = "The DiskID of licensefile (" + DiskID + ") is not equal of the DiskID of hareware (" + DiskSn + ")";
				// 系统未注册
				return false;//Const.ERROR_ESCALADE_NOTREGISTER;
			}
			return true;
		}

		// xfpan [5/17/2004]
		/// <summary>
		/// 获取机器唯一标志
		/// </summary>
		/// <returns>机器唯一标志</returns>
		public string GetDiskID()
		{
			string DiskID = "";

			DiskID = GetMAC().Trim();
			if (DiskID != "")
			{
				DiskID = "MA-" + DiskID;
				return DiskID;
			}
			WriteLog("MAC ID is null");

			try
			{
				DiskID = GetDiskSerialNo().Trim();
				if(DiskID != "")
				{
					DiskID = "HD" + DiskID;
					return DiskID;
				}
				WriteLog("HD ID is null");
			}
			catch(Exception de)
			{
				_LastErrorInfo = "Getting DiskSerialNo,catch a exception.It's information that " + de.Message.ToString();
				WriteLog("Getting DiskSerialNo,catch a exception.It's information that " + de.Message.ToString());
			}			

			DiskID = GetCPUId();
			if (DiskID != "")
			{
				DiskID = "CP" + DiskID;
				return DiskID;
			}
			WriteLog("CPU ID is null");

			return "";
		}	

		private string GetCPUId()
		{
			String HDid = "";
			ManagementClass cimobject = new ManagementClass("Win32_Processor");
			try
			{
				ManagementObjectCollection moc = cimobject.GetInstances();
				foreach(ManagementObject mo in moc)
				{
					HDid = mo["UniqueId"].ToString();
					if(HDid != "")
						break;
				}
			}
			catch(Exception he)
			{
				WriteLog("When getting CPU ID,catch a exception.It's message that " + he.Message.ToString());
				_LastErrorInfo = "When getting CPU ID,catch a exception.It's message that " + he.Message.ToString();
				HDid = "";
			}
			return HDid.Trim();
		}

		private string GetMAC()
		{
			string strMac = "";
			try
			{
				strMac = GetMacAddr();
			}
			catch(Exception me)
			{
				WriteLog("When getting Mac Address,catch a exception.It's message that " + me.Message.ToString());
				_LastErrorInfo = "When getting Mac Address,catch a exception.It's message that " + me.Message.ToString();
				strMac = "";
			}
			return strMac.Trim();
		}

		/// <summary>
		/// 验证许可时间
		/// </summary>
		/// <returns>验证成功为true,不成功为false</returns>
		public bool ValidateDate()
		{
			string CurrentDate = System.DateTime.Now.ToShortDateString();
			string FromDate = GetValidateInfo("FromDate");
			string ToDate = GetValidateInfo("ToDate");
			if(Convert.ToDateTime(CurrentDate) < Convert.ToDateTime(FromDate))
			{
				_LastErrorInfo = "许可证允许使用日期尚未开始";
				return false;//Const.ERROR_TELEPHONIST_TIMENOTARRIVE;
			}
			if(Convert.ToDateTime(CurrentDate) > Convert.ToDateTime(ToDate))
			{
				_LastErrorInfo = "许可证已过期";
				return false;//Const.ERROR_TELEPHONIST_OVERDUE;
			}
			return true;
		}

		/// <summary>
		/// 验证许可证文件
		/// </summary>
		/// <returns>验证成功为true,不成功为false</returns>
		public bool ValidateAuthority()
		{
			string f_UnSignedInfo = "";
			if(m_SignedString == "" || m_ds == null || m_ds.Tables[TABLENAME] == null || m_ds.Tables[TABLENAME].Rows.Count != 1)
			{
				return false;
			}
			
			for(int i = 0;i < m_ds.Tables[TABLENAME].Columns.Count;i++)
			{
				f_UnSignedInfo += m_ds.Tables[TABLENAME].Columns[i].ColumnName;
				f_UnSignedInfo += m_ds.Tables[TABLENAME].Rows[0][i].ToString();
			}
			byte[] UnSignedInfoByte = ByteConverter.GetBytes(f_UnSignedInfo);
			byte[] SignedInfoByte = ByteConverter.GetBytes(m_SignedString);
			try
			{
				// xfpan [5/20/2004]
				CspParameters CSPParam = new CspParameters();
				CSPParam.Flags = CspProviderFlags.UseMachineKeyStore;
				RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(CSPParam);
				// xfpan [5/20/2004]
				RSA.FromXmlString(PUBLICKEY);
				HashAlgorithm sha = new SHA1CryptoServiceProvider();
				IsValidated = RSA.VerifyData(UnSignedInfoByte,sha,SignedInfoByte);
			}
			catch
			{
				return false;
			}
			return IsValidated;
		}

		/// <summary>
		/// 获取许可证信息
		/// </summary>
		/// <param name="f_ValidateKey">许可证信息主键</param>
		/// <returns>许可证信息对应值</returns>
		private string GetValidateInfo(string f_ValidateKey)
		{
			string f_ValidateInfo = "";

			if(m_ds == null || m_ds.Tables[TABLENAME] == null || m_ds.Tables[TABLENAME].Rows.Count != 1 || m_ds.Tables[TABLENAME].Columns[f_ValidateKey] == null)
			{
				f_ValidateInfo = "";
			}
			else
			{
				try
				{
					f_ValidateInfo = m_ds.Tables[TABLENAME].Rows[0][f_ValidateKey].ToString();
				}
				catch
				{
					f_ValidateInfo = "";
				}
			}
			return f_ValidateInfo;
		}

		//wuxiangrong 2005.10.19
		//获取许可证中的硬盘序列号
		public string GetDiskIDFromLicence()
		{
			try
			{
				return m_ds.Tables[TABLENAME].Rows[0]["DiskID"].ToString();
			}
			catch
			{
				return "";
			}
		}

		//获取许可证中的公司名称
		public string GetCompanyNameFromLicence()
		{
			try
			{
				return m_ds.Tables[TABLENAME].Rows[0]["CompanyName"].ToString();
			}
			catch
			{
				return "";
			}
		}

		//获取许可证中的用户数量
		public string GetUserCountFromLicence()
		{
			try
			{
				return m_ds.Tables[TABLENAME].Rows[0]["UserCount"].ToString();
			}
			catch
			{
				return "";
			}
		}

		//获取许可证中的产品名称
		public string GetProductNameFromLicence()
		{
			try
			{
				return m_ds.Tables[TABLENAME].Rows[0]["ProductName"].ToString();
			}
			catch
			{
				return "";
			}
		}

		//获取许可证中的版本号
		public string GetVersionFromLicence()
		{
			try
			{
				return m_ds.Tables[TABLENAME].Rows[0]["Version"].ToString();
			}
			catch
			{
				return "";
			}
		}

		//获取许可证中的有效期的启起日期
		public string GetFromDateFromLicence()
		{
			try
			{
				return m_ds.Tables[TABLENAME].Rows[0]["FromDate"].ToString();
			}
			catch
			{
				return "";
			}
		}

		//获取许可证中的有效期的截止日期
		public string GetToDateFromLicence()
		{
			try
			{
				return m_ds.Tables[TABLENAME].Rows[0]["ToDate"].ToString();
			}
			catch
			{
				return "";
			}
		}
		//wuxiangrong 2005.10.19


		/// <summary>
		/// 加载是否成功标志
		/// </summary>
		public bool IsLoad
		{
			get
			{
				return _IsLoad;
			}
			set
			{
				_IsLoad = value;
			}
		}

		/// <summary>
		/// 验证是否成功标志
		/// </summary>
		public bool IsValidated
		{
			get
			{
				return _IsValidated;
			}
			set
			{
				_IsValidated = value;
			}
		}

		// 测试使用
		private void WriteLog(String ErrInfos)
		{
			FileStream fs;
			StreamWriter sw;
			try
			{
				fs = new FileStream("c:\\ErrorLog.txt", FileMode.OpenOrCreate | FileMode.Append);			
				sw = new StreamWriter(fs);
				sw.WriteLine(DateTime.Now.ToString() + " " + ErrInfos);
				sw.Close();
			}
			catch{}
		}

		/// <summary>
		/// 最后的错误信息
		/// </summary>
		public string LastErrorInfo
		{
			get
			{
				return _LastErrorInfo;
			}
			set
			{
				_LastErrorInfo = value;
			}
		}

		/// <summary>
		/// 验证,包括验证是否加载成功、许可证文件是否有效、时间是否在有效期内、序列号是否正确
		/// </summary>
		/// <param name="f_LicencePath">许可证路径</param>
		/// <param name="ProductName">产品名称</param>
		/// <returns>验证成功为true,不成功为false</returns>
		public bool Validate(string f_LicencePath,string ProductName)
		{
			Initialize(f_LicencePath);

			// 验证是否加载成功
			if(_IsLoad == false)
			{
				_LastErrorInfo = "加载许可文件失败";
				return false;
			}

			// 验证许可证文件是否有效
			if(!ValidateAuthority())
			{
				_LastErrorInfo = "验证许可证文件失败";
				return false;
			}
			
			// 验证时间是否在有效期内
			if(!ValidateDate())
			{
				// 错误信息在底层已经给出 [9/22/2005]
				return false;
			}
			
			// 验证序列号是否正确
			if(!ValidateSerialNo())
			{
				// 错误信息在底层已经给出 [9/22/2005]
				return false;
			}

			// 验证产品名称是否正确
			if(!ValidateProductName(ProductName))
			{
				// 错误信息在底层已经给出 [9/22/2005]
				return false;
			}
			
			// 验证成功
			return true;
		}

		/// <summary>
		/// 校验产品名称
		/// </summary>
		/// <param name="ProductName">产品名称</param>
		/// <returns>返回值,正确返回true,错误返回false</returns>
		public bool ValidateProductName(string ProductName)
		{
			string ProName = GetValidateInfo("ProductName").Trim();
			if(ProName != ProductName)
			{
				_LastErrorInfo = "错误信息:请使用正确的许可证,当前运行的产品为" + ProductName + ",而使用的是产品为" + ProName + "的许可证";
				return false;
			}
			return true;
		}
	}
}