如何使用我自己的密钥使用 ECDiffieHellmanCng 加密数据
How can I use my own Key to encrypt data using ECDiffieHellmanCng
我的任务是在 .Net 中使用椭圆曲线密码术加密数据(特定于客户端),我尝试使用 Microsoft 的示例,但它似乎每次都生成自己的密钥。
我需要为此过程使用我自己的密钥,例如创建密码 "S3curEChaNNel_01?" 并将其转换为字节然后用作密钥,但我找不到执行此操作的方法。
Using alice As New ECDiffieHellmanCng()
Dim abData() As Byte
Dim Str = txtKey.Text 'custom password
abData = System.Text.Encoding.Default.GetBytes(Str)
Str = System.Text.Encoding.Default.GetString(abData)
Dim bobPublicKey() As Byte
Dim bobKey() As Byte
Dim bob As New ECDiffieHellmanCng()
bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash
bob.HashAlgorithm = CngAlgorithm.Sha256
bobPublicKey = bob.PublicKey.ToByteArray()
bob.HmacKey = abData
bobKey = bob.DeriveKeyMaterial(CngKey.Create(CngAlgorithm.Sha256))
'at this line i get an exception, "The requested operation is not supported."
'Dim aliceKey As Byte() = alice.DeriveKeyMaterial(CngKey.Create(CngAlgorithm.Sha256))
Dim encryptedMessage As Byte() = Nothing
Dim iv As Byte() = Nothing
txtOutput.Text = ByteArrayToString(Encrypt(bobKey, txtPlainStr.Text, encryptedMessage, iv))
End Using
您正在将两种不同的东西混合在一起。
当您想要自己的密码时,您使用此类密码发送加密数据的人必须知道密码才能解密。但是你不能发送密码,因为MITM可以捕获它。
这就是您使用 Diffie - Hellman 的原因。
基本上,Diffie - Hellman 只输出一个数字,但是这个数字不能用作加密密钥,因为它太弱了。
现在这里是 KDF(密钥派生函数)的用武之地。
例如 PBKDF2。它以password和salt为参数,输出派生密钥,用于加密和解密你要发送的数据。
所以你把交换的号码作为密码传递给 KDF。
例如,您可以使用 Alice 或 Bob 的 IP 作为盐。
KDF 将在双方生成相同的强密码来加密和解密数据。
希望它有意义。
我的任务是在 .Net 中使用椭圆曲线密码术加密数据(特定于客户端),我尝试使用 Microsoft 的示例,但它似乎每次都生成自己的密钥。
我需要为此过程使用我自己的密钥,例如创建密码 "S3curEChaNNel_01?" 并将其转换为字节然后用作密钥,但我找不到执行此操作的方法。
Using alice As New ECDiffieHellmanCng()
Dim abData() As Byte
Dim Str = txtKey.Text 'custom password
abData = System.Text.Encoding.Default.GetBytes(Str)
Str = System.Text.Encoding.Default.GetString(abData)
Dim bobPublicKey() As Byte
Dim bobKey() As Byte
Dim bob As New ECDiffieHellmanCng()
bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash
bob.HashAlgorithm = CngAlgorithm.Sha256
bobPublicKey = bob.PublicKey.ToByteArray()
bob.HmacKey = abData
bobKey = bob.DeriveKeyMaterial(CngKey.Create(CngAlgorithm.Sha256))
'at this line i get an exception, "The requested operation is not supported."
'Dim aliceKey As Byte() = alice.DeriveKeyMaterial(CngKey.Create(CngAlgorithm.Sha256))
Dim encryptedMessage As Byte() = Nothing
Dim iv As Byte() = Nothing
txtOutput.Text = ByteArrayToString(Encrypt(bobKey, txtPlainStr.Text, encryptedMessage, iv))
End Using
您正在将两种不同的东西混合在一起。
当您想要自己的密码时,您使用此类密码发送加密数据的人必须知道密码才能解密。但是你不能发送密码,因为MITM可以捕获它。
这就是您使用 Diffie - Hellman 的原因。
基本上,Diffie - Hellman 只输出一个数字,但是这个数字不能用作加密密钥,因为它太弱了。
现在这里是 KDF(密钥派生函数)的用武之地。 例如 PBKDF2。它以password和salt为参数,输出派生密钥,用于加密和解密你要发送的数据。
所以你把交换的号码作为密码传递给 KDF。 例如,您可以使用 Alice 或 Bob 的 IP 作为盐。
KDF 将在双方生成相同的强密码来加密和解密数据。
希望它有意义。