我有两个应用程序,服务器和客户端,一个在一台机器上运行,另一个从第二台机器上运行,服务器使用 WebSocket 连接传递数据,数据在发送到客户端之前被加密,数据使其成为客户端应用程序正确,但我正在尝试使用相同的安全方法和 key 对其进行解密,但我无法工作,它仅在两个应用程序从同一台计算机上运行时才对其进行解密。有没有人知道为什么当它们在同一台机器上运行时它可以工作,而从不同的机器上运行它们时却没有?
服务器和客户端应用程序都使用相同的安全方法。
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 加密 key 在每台计算机上始终是唯一的,因此当您在计算机 A 上加密数据时,您使用的是 key A,而当您尝试解密计算机 B 上的数据时,您使用的是 key B。DPAPI 仅按顺序提供到 symmetric cipher 的接口(interface)要成功解密数据,您需要使用完全相同的 key 进行加密和解密。
我相信您应该更改代码以使用不同的加密算法,即 AES(由 System.Security.Cryptography.AesManaged 类实现),这将允许您在两台不同的机器之间共享 key 。
关于c# - 无法在第二台计算机上解密数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23124000/