无法解密第二台计算机上的数据

我有两个应用程序,服务器和客户端,一个从一台机器运行,另一个从第二台机器运行,服务器使用WebSocket连接传递数据,数据在发送到客户端之前被加密,数据使其成为客户端应用程序正确,但我正在尝试使用相同的安全方法和密钥解密它,但我不会工作,它只在两个应用程序从同一台计算机运行时解密它。 有没有人知道它们从同一台机器运行时为什么会起作用,而不是从单独的机器运行它们时呢?

服务器和客户端应用程序都使用相同的安全方法。

using System.Security.Cryptography; // ENCRYPT static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("MY SECRET KEY HERE"); public static string EncryptString(System.Security.SecureString input) { byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect( System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)), entropy, System.Security.Cryptography.DataProtectionScope.CurrentUser); return Convert.ToBase64String(encryptedData); } public static SecureString DecryptString(string encryptedData) { try { byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect( Convert.FromBase64String(encryptedData), entropy, System.Security.Cryptography.DataProtectionScope.CurrentUser); return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData)); } catch { return new SecureString(); } } public static SecureString ToSecureString(string input) { SecureString secure = new SecureString(); foreach (char c in input) { secure.AppendChar(c); } secure.MakeReadOnly(); return secure; } public static string ToInsecureString(SecureString input) { string returnValue = string.Empty; IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input); try { returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr); } finally { System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr); } return returnValue; } // ENCRYPT ENDS 

要加密我使用的服务器上的数据:

 string encryptedMessage = EncryptString(ToSecureString("Data to Encrypt Here")); 

要解密客户端上的数据我使用

 SecureString data1 = DecryptString(dataEncryptedReceived); IntPtr stringPointerData1 = Marshal.SecureStringToBSTR(data1); string normalStringData1 = Marshal.PtrToStringBSTR(stringPointerData1); Marshal.ZeroFreeBSTR(stringPointerData1); 

同样,只有当我同时使用来自同一台计算机的服务器和客户端应用程序时,这一切都能正常工作,但我尝试将它们分开使用,一台机器上的服务器和另一台机器上的客户端,即使客户端接收到它也不会解密数据加密数据成功。

请帮忙!

谢谢。

您正在使用System.Security.Cryptography.ProtectedData类,该类在底层使用Data Protection API(DPAPI) 。 DPAPI加密密钥在每台计算机上始终是唯一的,因此当您加密计算机A上的数据时,您正在使用密钥A,当您尝试解密计算机B上的数据时,您使用的是密钥B. DPAPI仅提供对称密码的接口,因此在为了成功解密数据,您需要使用完全相同的密钥进行加密和解密。

我相信您应该更改您的代码以使用不同的加密算法,即AES(由System.Security.Cryptography.AesManaged类实现),这将允许您在两台不同的计算机之间共享密钥。

ProtectUnprotect方法仅调用DPAPIDPAPI仅在启用了漫游配置文件的情况下才能在计算机上运行,​​并且仅在某些情况下才能使用。

相反,使用自己管理的会话密钥算法( AES , 其他…… ),或者更好:使用TLS作为WebSocket( wss:// )或Socket传输( SslStream )。 滚动你自己的加密只是在寻找麻烦。