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)); }
密钥是 是 证书中获取的 xml 最后加密的时候 报 不正确的长度 。
加密的字符串太长了吧,这个加密长度有限制的,可以考虑分段加密试试看。试试这个.
/// <summary> /// RSA的加密函数 string /// </summary> /// <param name="publicKey">公钥</param> /// <param name="plaintext">明文</param> /// <returns></returns> public static string Encrypt(string publicKey, string plaintext) { return Encrypt(publicKey, Encoding.UTF8.GetBytes(plaintext)); } /// <summary> /// RSA的加密函数 string /// </summary> /// <param name="publicKey">公钥</param> /// <param name="plainbytes">明文字节数组</param> /// <returns></returns> public static string Encrypt(string publicKey, byte[] plainbytes) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(Encoding.UTF8.GetString(Convert.FromBase64String(publicKey))); var bufferSize = (rsa.KeySize / 8 - 11); byte[] buffer = new byte[bufferSize];//待加密块 using (MemoryStream msInput = new MemoryStream(plainbytes)) { using (MemoryStream msOutput = new MemoryStream()) { int readLen; while ((readLen = msInput.Read(buffer, 0, bufferSize)) > 0) { byte[] dataToEnc = new byte[readLen]; Array.Copy(buffer, 0, dataToEnc, 0, readLen); byte[] encData = rsa.Encrypt(dataToEnc, false); msOutput.Write(encData, 0, encData.Length); } byte[] result = msOutput.ToArray(); rsa.Clear(); return Convert.ToBase64String(result); } } } } /// <summary> /// RSA的解密函数 stirng /// </summary> /// <param name="privateKey">私钥</param> /// <param name="ciphertext">密文字符串</param> /// <returns></returns> public static string Decrypt(string privateKey, string ciphertext) { return Decrypt(privateKey, Convert.FromBase64String(ciphertext)); } /// <summary> /// RSA的解密函数 byte /// </summary> /// <param name="privateKey">私钥</param> /// <param name="cipherbytes">密文字节数组</param> /// <returns></returns> public static string Decrypt(string privateKey, byte[] cipherbytes) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(Encoding.UTF8.GetString(Convert.FromBase64String(privateKey))); int keySize = rsa.KeySize / 8; byte[] buffer = new byte[keySize]; using (MemoryStream msInput = new MemoryStream(cipherbytes)) { using (MemoryStream msOutput = new MemoryStream()) { int readLen; while ((readLen = msInput.Read(buffer, 0, keySize)) > 0) { byte[] dataToDec = new byte[readLen]; Array.Copy(buffer, 0, dataToDec, 0, readLen); byte[] decData = rsa.Decrypt(dataToDec, false); msOutput.Write(decData, 0, decData.Length); } byte[] result = msOutput.ToArray(); rsa.Clear(); return Encoding.UTF8.GetString(result); } } } }
加密可以了,但是解密的时候报错了,报数据不正确
解决了吗
我也遇见了 一样的问题 加密可以 解密报错