代码:
RSAHelper.cs(RSA加密工具类):
using System; using System.Security.Cryptography; using System.Text; namespace Utils { /// <summary> /// RSA加密工具类 /// </summary> public class RSAHelper { /// <summary> /// RSA加密 /// </summary> public static string RSAEncrypt_LongContent(string publicKey, string content) { byte[] bytes = Encoding.UTF8.GetBytes(content); int pageSize = 117; int pageCount = (bytes.Length - 1) / pageSize + 1; StringBuilder result = new StringBuilder(); for (int page = 1; page <= pageCount; page++) { int start = pageSize * (page - 1); byte[] subBytes = page == pageCount ? new byte[bytes.Length - start] : new byte[pageSize]; Array.Copy(bytes, start, subBytes, 0, subBytes.Length); string strEncrypted = RSAEncrypt(publicKey, Encoding.UTF8.GetString(subBytes)); result.Append(strEncrypted); } return result.ToString(); } /// <summary> /// RSA解密 /// </summary> public static string RSADecrypt_LongContent(string privateKey, string content) { int pageSize = 172; int pageCount = (content.Length - 1) / pageSize + 1; StringBuilder result = new StringBuilder(); for (int page = 1; page <= pageCount; page++) { int start = pageSize * (page - 1); string subContent = null; if (page != pageCount) { subContent = content.Substring(start, pageSize); } else { subContent = content.Substring(start, content.Length - start); } string strEncrypted = RSADecrypt(privateKey, subContent); result.Append(strEncrypted); } return result.ToString(); } /// <summary> /// RSA加密 /// </summary> public static string RSAEncrypt(string publicKey, string content) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(publicKey); byte[] cipherBytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(cipherBytes); } /// <summary> /// RSA解密 /// </summary> public static string RSADecrypt(string privateKey, string content) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); byte[] cipherBytes = rsa.Decrypt(Convert.FromBase64String(content), false); return Encoding.UTF8.GetString(cipherBytes); } /// <summary> /// 创建公钥私钥 /// </summary> public static RSAKey CreateKey() { RSAKey rsaKey = new RSAKey(); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsaKey.PublicKey_NET = rsa.ToXmlString(false); // 公钥 rsaKey.PrivateKey_NET = rsa.ToXmlString(true); // 私钥 rsaKey.PublicKey_Java = RSAKeyConvert.RSAPublicKeyDotNet2Java(rsaKey.PublicKey_NET); rsaKey.PrivateKey_Java = RSAKeyConvert.RSAPrivateKeyDotNet2Java(rsaKey.PrivateKey_NET); } return rsaKey; } } public class RSAKey { public string PublicKey_NET { get; set; } public string PrivateKey_NET { get; set; } public string PublicKey_Java { get; set; } public string PrivateKey_Java { get; set; } } }