已解决
密码学Python
无法解密第二台计算机上的数据10
我有两个应用程序,服务器和客户端,一个从一台机器运行,另一个从第二台机器运行,服务器使用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);
同样,只有当我同时使用来自同一台计算机的服务器和客户端应用程序时,这一切都能正常工作,但我尝试将它们分开使用,一台机器上的服务器和另一台机器上的客户端,即使客户端接收到它也不会解密数据加密数据成功。
派大星
2019.07.22
4268
收藏