C# RSA 系统找不到指定的文件
C# RSA解密本机运行没有问题,发布到服务器后显示系统找不到指定文件,原代码:
public static string RsaDecrypt1(string encryptedInput, string privateKey) { if (string.IsNullOrEmpty(encryptedInput)) { return string.Empty; } using (var rsaProvider = new RSACryptoServiceProvider()) { CspParameters RSAParams = new CspParameters(); RSAParams.Flags = CspProviderFlags.UseMachineKeyStore; try { var inputBytes = Convert.FromBase64String(encryptedInput); rsaProvider.FromXmlString(privateKey); int bufferSize = rsaProvider.KeySize / 8; var buffer = new byte[bufferSize]; using (MemoryStream inputStream = new MemoryStream(inputBytes), outputStream = new MemoryStream()) { while (true) { int readSize = inputStream.Read(buffer, 0, bufferSize); if (readSize <= 0) { break; } var temp = new byte[readSize]; Array.Copy(buffer, 0, temp, 0, readSize); var rawBytes = rsaProvider.Decrypt(temp, false); outputStream.Write(rawBytes, 0, rawBytes.Length); } return Encoding.UTF8.GetString(outputStream.ToArray()); } } catch { return null; } } }
将这里修改:
修改为:
CspParameters RSAParams = new CspParameters(); RSAParams.Flags = CspProviderFlags.UseMachineKeyStore; var rsaProvider = new RSACryptoServiceProvider(1024, RSAParams)
修改后完整代码:
public static string RsaDecrypt(string encryptedInput, string privateKey) { if (string.IsNullOrEmpty(encryptedInput)) { return string.Empty; } CspParameters RSAParams = new CspParameters(); RSAParams.Flags = CspProviderFlags.UseMachineKeyStore; using (var rsaProvider = new RSACryptoServiceProvider(1024, RSAParams)) { try { var inputBytes = Convert.FromBase64String(encryptedInput); rsaProvider.FromXmlString(privateKey); int bufferSize = rsaProvider.KeySize / 8; var buffer = new byte[bufferSize]; using (MemoryStream inputStream = new MemoryStream(inputBytes), outputStream = new MemoryStream()) { while (true) { int readSize = inputStream.Read(buffer, 0, bufferSize); if (readSize <= 0) { break; } var temp = new byte[readSize]; Array.Copy(buffer, 0, temp, 0, readSize); var rawBytes = rsaProvider.Decrypt(temp, false); outputStream.Write(rawBytes, 0, rawBytes.Length); } return Encoding.UTF8.GetString(outputStream.ToArray()); } } catch { return null; } } }