using System; using System.Security.Cryptography; using System.Text; public static class NetworkValideRsa2Sdk { public static string EncryptData(string rawData, string publicKeyPem) { using (var rsa = RSA.Create()) { rsa.ImportFromPem(publicKeyPem.ToCharArray()); int chunkSize = rsa.KeySize / 8 - 11; byte[] source = Encoding.UTF8.GetBytes(rawData); using (var ms = new System.IO.MemoryStream()) { for (int i = 0; i < source.Length; i += chunkSize) { int len = Math.Min(chunkSize, source.Length - i); byte[] chunk = new byte[len]; Buffer.BlockCopy(source, i, chunk, 0, len); byte[] enc = rsa.Encrypt(chunk, RSAEncryptionPadding.Pkcs1); ms.Write(enc, 0, enc.Length); } return Convert.ToBase64String(ms.ToArray()); } } } public static string DecryptMsg(string msg, string publicKeyPem) { using (var rsa = RSA.Create()) { rsa.ImportFromPem(publicKeyPem.ToCharArray()); byte[] source = Convert.FromBase64String(msg); int chunkSize = rsa.KeySize / 8; using (var ms = new System.IO.MemoryStream()) { for (int i = 0; i < source.Length; i += chunkSize) { byte[] chunk = new byte[chunkSize]; Buffer.BlockCopy(source, i, chunk, 0, chunkSize); byte[] dec = rsa.Decrypt(chunk, RSAEncryptionPadding.Pkcs1); ms.Write(dec, 0, dec.Length); } return Encoding.UTF8.GetString(ms.ToArray()); } } } public static string MakeSign(string data, string appKey) { using (var md5 = MD5.Create()) { var bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(data + appKey)); return BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant(); } } }