/// <summary> /// 使用私钥加密字符串 /// </summary> /// <param name="key">需加密的字符</param> /// <param name="keyPath">私钥证书文件地址</param> public string EncryptKey(string key,string keyPath) { X509Certificate2 c2 = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + "bin\\client.cer"); string keyPublic2 = c2.PublicKey.Key.ToXmlString(false); string cypher2 = RSAEncrypt(keyPublic2, key); // 加密 return cypher2; } /// <summary> /// RSA解密 /// </summary> /// <param name="xmlPrivateKey"></param> /// <param name="m_strDecryptString"></param> /// <returns></returns> static string RSADecrypt(string xmlPrivateKey, string m_strDecryptString) { RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); provider.FromXmlString(xmlPrivateKey); byte[] rgb = Convert.FromBase64String(m_strDecryptString); byte[] bytes = provider.Decrypt(rgb, false); return new UnicodeEncoding().GetString(bytes); } /// <summary> /// RSA加密 /// </summary> /// <param name="xmlPublicKey"></param> /// <param name="m_strEncryptString"></param> /// <returns></returns> static string RSAEncrypt(string xmlPublicKey, string m_strEncryptString) { RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); provider.FromXmlString(xmlPublicKey); byte[] bytes = new UnicodeEncoding().GetBytes(m_strEncryptString); return Convert.ToBase64String(provider.Encrypt(bytes, false)); }
时间: 2024-10-22 18:25:31