在客户端上加密的最佳做法

本文关键字:最佳 加密 客户端 | 更新日期: 2023-09-27 18:32:45

我目前正在使用允许"加密"选项的Web API。

我可以将我的帐户设置为具有"共享密钥",并且使用此密钥,我应该在提交到服务器之前加密客户端上的所有数据。

他们网站上的详细信息:

加密算法:DES

区块模式:欧洲央行

填充:PKCS7 或 PKCS5(它们是可互换的)

我认为这个意义上的"共享密钥"是一种对称算法 - 用于解密/加密的相同密钥,尽管我可能错了。

我想知道在客户端处理此方案的最佳实践是什么?

如果我的应用程序的逻辑应该使用此密钥来加密数据,那么如何防止黑客入侵?

请注意,我的应用程序是用 C# 编写的,这意味着它实际上可以免费反编译。

在客户端上加密的最佳做法

除非您的密钥被泄露,否则您的数据传输是安全的——任何窃听您的客户端-服务器连接的人都无法解密您的数据,除非他们拥有您的密钥。

您的主要挑战在于密钥在客户端和服务器上本地的安全存储。为此,我建议研究通过.NET中的ProtectedData类公开的Windows Data Protection API(DPAPI)。

如果shared key的意思是public key那么你很可能使用一种称为非对称加密的算法。这样您就可以安全地被黑客入侵,因为公钥不能用于解密数据。

如果它是对称的,那么一切都取决于密钥的安全性。您可以将其与程序分开存储(以便用户可以将其安全地存储在闪存驱动器上)。因此,每个用户都必须拥有自己的密钥,不可能对所有用户使用一个对称密钥。

通过这种方式,客户端将使用不同的密钥加密数据,服务器将使用不同的密钥解密。这称为非对称加密/解密。

.NET Framework 提供用于非对称加密的 RSACryptoServiceProvider 和 DSACryptoServiceProvider 类。当您使用默认构造函数创建新实例时,这些类会创建公钥/私钥对。非对称密钥可以存储以在多个会话中使用,也可以仅为一个会话生成。虽然公钥可以普遍可用,但私钥应受到严密保护。

For example [VB.NET]: 
Dim cspParam as CspParameters = new CspParameters()
cspParam.Flags = CspProviderFlags.UseMachineKeyStore
Dim RSA As System.Security.Cryptography.RSACryptoServiceProvider
           = New System.Security.Cryptography.RSACryptoServiceProvider(cspParam)
The key information from the cspParam object above can be saved via:
Dim publicKey as String = RSA.ToXmlString(False) ' gets the public key
Dim privateKey as String = RSA.ToXmlString(True) ' gets the private key
The above methods enable you to convert the public and / or private keys to Xml Strings.
 And of course, as you would guess, there is a corresponding FromXmlString method to get them back. 
 So to encrypt some data with the Public key. The no-parameter constructor is used as we are loading our keys from XML and 
 do not need to create a new cspParams object:
Dim str as String = "HelloThere"
Dim RSA2 As RSACryptoServiceProvider = New RSACryptoServiceProvider()
' ---Load the private key---
RSA2.FromXmlString(privateKey)
Dim EncryptedStrAsByt() As Byte =RSA2.Encrypt(System.Text.Encoding.Unicode.GetBytes(str),False)
Dim EncryptedStrAsString = System.Text.Encoding.Unicode.GetString(EncryptedStrAsByt)
and as a "proof of concept", to DECRYPT the same data, but now using the Public key:
Dim RSA3 As RSACryptoServiceProvider = New RSACryptoServiceProvider(cspParam)
'---Load the Public key---
RSA3.FromXmlString(publicKey)
Dim DecryptedStrAsByt() As Byte =RSA3.Decrypt(System.Text.Encoding.Unicode.GetBytes(EncryptedStrAsString), False)
Dim DecryptedStrAsString = System.Text.Encoding.Unicode.GetString(DecryptedStrAsByt)