关于RSA的私钥加密,公钥解密的问题
程序代码:
/// <summary> /// 对原始数据进行MD5加密 /// </summary> /// <param name="key">待加密的注册码</param> /// <returns>加密后的注册码</returns> public static string GetMD5(string key) { HashAlgorithm algorithm = HashAlgorithm.Create("MD5"); byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(key); byte[] inArray = (bytes); string strEncrypt = Convert.ToBase64String(inArray); return strEncrypt; } /// <summary> /// 使用私钥加密客户注册码[注册码+GUID码] /// </summary> /// <param name="key">客户注册码[注册码+GUID码]</param> /// <param name="keyContainerName">密钥容器名称</param> /// <param name="keyPath">私钥文件地址</param> /// <returns>加密后的注册码</returns> public static string EncryptKey(string key,string keyContainerName, string keyPath) { CspParameters cspParameter = new CspParameters(); StreamReader sr = new StreamReader(keyPath); cspParameter.KeyContainerName = keyContainerName; string strKey = sr.ReadLine(); string strEncrypt = string.Empty; byte[] byteKeys = Convert.FromBase64String(GetMD5(key)); RSACryptoServiceProvider provider = new RSACryptoServiceProvider(cspParameter); provider.FromXmlString(strKey); RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(provider); formatter.SetHashAlgorithm("MD5"); byte[] byteEncrypt = formatter.CreateSignature(byteKeys); strEncrypt = Convert.ToBase64String(byteEncrypt); return strEncrypt; } /// <summary> /// 使用公钥解密客户注册码验证 /// </summary> /// <param name="publicKey">公钥</param> /// <param name="key">授权文件信息</param> /// <param name="computeInfo">电脑硬件信息</param> public static bool Decrypt(string publicKey,string key,string computeInfo) { try { CspParameters cspParameter = new CspParameters(); cspParameter.KeyContainerName = "public"; RSACryptoServiceProvider provider = new RSACryptoServiceProvider(cspParameter); provider.FromXmlString(publicKey); RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(provider); deformatter.SetHashAlgorithm("MD5"); //转换授权文件信息字符串 byte[] byteAuthorization = Convert.FromBase64String(key); //转换当前电脑硬件信息 byte[] byteComputeInfo = Convert.FromBase64String(GetMD5(computeInfo)); if (deformatter.VerifySignature(byteAuthorization, byteComputeInfo)) { return true; } else { return false; } } catch (Exception ex) { WriteSystemLog(5, 3, "000000", ex.Message); throw new Exception(ex.Message, ex); } }
执行以上代码之后提示“不正确的散列算法”,调试之后发现问题出在解密那里,到了
if (deformatter.VerifySignature(byteAuthorization, byteComputeInfo))
这里就出现异常,然后我把两个参数调换了一下位置之后就没出错了,但是结果总是false,不知道是哪里的数据出错了,我一步步地调,但是就是找不出来,快崩溃了~~有哪位大虾看出啥问题,帮忙指点一下迷津~~