C# RSA加密-RSACryptoServiceProvider
1.获取公钥和私钥(XML格式)
/// <summary> /// 获取RSA 密钥 /// 下标 0 为 私钥 /// 下标 1 为 公钥 /// </summary> /// <returns></returns> public static string[] GetRSAKey() { RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); string privatekey = provider.ToXmlString(true); string publickey = provider.ToXmlString(false); return new string[] { privatekey, publickey }; }
2.公钥加密
/// <summary> /// RSA 加密 /// </summary> /// <param name="plainText">加密内容</param> /// <returns></returns> public string RSAEncrypt(string plainText) { byte[] buffer = Encoding.UTF8.GetBytes(plainText); RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); provider.FromXmlString(PublicKeyRsa); byte[] output = provider.Encrypt(buffer, false); return Convert.ToBase64String(output); }
3.私钥解密
/// <summary> /// RSA 解密 /// </summary> /// <param name="encryptedText"></param> /// <returns></returns> public string RSADecrypt(string encryptedText) { byte[] buffer = Convert.FromBase64String(encryptedText); RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); provider.FromXmlString(PrivateKeyRsa); byte[] output = provider.Decrypt(buffer, false); return Encoding.UTF8.GetString(output); }
4.前端使用后端的公钥加密
前端使用jsencrypt库来进行RSA加密,jsencrypt库支持的密钥是Pkcs8格式,后端需要将公钥格式XML转为Pkcs8格式
后端需安装NuGet包XC.RSAUtil 进行数据格式转换
//私钥XML格式转Pkcs8格式 RsaKeyConvert.PrivateKeyXmlToPkcs8(PrivateKeyRsa); //公钥XML格式转Pkcs8格式 RsaKeyConvert.PublicKeyXmlToPem(PublicKeyRsa);
前端加密
/** * 信息加密 * @param key 公钥(后端获取) * @param str 加密数据 * @returns */ encryptInfo(key, str) { let encrypt = new JSEncrypt({}); encrypt.setPublicKey(key); return encrypt.encrypt(str); }