C#非对称加密解密(DEC加密算法)
今天做一个功能,就是在软件使用前需要激活,防止被复制使用。最后选择了对称加密来做,使用base64加密来做也行,因为只是一个小软件,没必要使用安全等级很高的算法,也没有做代码混淆和防反编译。
机器码使用的是UUID,可以做到唯一标识。
加密解密代码
const string KEY_64 = "abcdefgh";//密钥,必须是8位 const string IV_64 = "abcdefgh";//初始化向量 public static string Encode(string data) { byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); int i = cryptoProvider.KeySize; MemoryStream ms = new MemoryStream(); CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write); StreamWriter sw = new StreamWriter(cst); sw.Write(data); sw.Flush(); cst.FlushFinalBlock(); sw.Flush(); return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); } public static string Decode(string data) { byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); byte[] byEnc; try { byEnc = Convert.FromBase64String(data); } catch { return null; } DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); MemoryStream ms = new MemoryStream(byEnc); CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read); StreamReader sr = new StreamReader(cst); return sr.ReadToEnd(); }
获取UUID代码
string uuid = null;//通用唯一识别码 SelectQuery query = new SelectQuery("select * from Win32_ComputerSystemProduct"); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (var item in searcher.Get()) { using (item) uuid = item["UUID"].ToString(); } }