简体   繁体   中英

How to implement Diffie Hellman in .netcore/Linux

ECDiffieHellmanCng -> Platform not supported

ECDiffieHellmanOpenSsl -> PublicKey.ToByteArray() -> Platform not supported

Here's basically the same (unanswered) question from someone else, 7 months ago How do I serialize and deserialize the public key for ECDiffieHellmanOpenSsl on Linux?

I'd like to avoid pulling in 3rd party deps if there's a way to tame the provided classes.

ECDiffieHellmanCng is not supported on Linux.

Linux uses ECDiffieHellmanOpenSsl , but note

The types involved do not translate between platforms

See https://github.com/dotnet/corefx/blob/1841042b99062de13dc80098cede9413be569238/Documentation/architecture/cross-platform-cryptography.md

You can find some examples of how this is used in the test suite, for example

[Fact]
public void VerifyDuplicateKey_ValidHandle()
{
    using (var first = new ECDiffieHellmanOpenSsl())
    using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
    using (ECDiffieHellman second = new ECDiffieHellmanOpenSsl(firstHandle))
    using (ECDiffieHellmanPublicKey firstPublic = first.PublicKey)
    using (ECDiffieHellmanPublicKey secondPublic = second.PublicKey)
    {
        byte[] firstSecond = first.DeriveKeyFromHash(secondPublic, HashAlgorithmName.SHA256);
        byte[] secondFirst = second.DeriveKeyFromHash(firstPublic, HashAlgorithmName.SHA256);
        byte[] firstFirst = first.DeriveKeyFromHash(firstPublic, HashAlgorithmName.SHA256);

        Assert.Equal(firstSecond, secondFirst);
        Assert.Equal(firstFirst, firstSecond);
    }
}

https://github.com/dotnet/corefx/blob/a10890f4ffe0fadf090c922578ba0e606ebdd16c/src/System.Security.Cryptography.OpenSsl/tests/EcDiffieHellmanOpenSslTests.cs

With .NET Core 3.0 you can serialize the value with key.ExportSubjectPublickeyInfo() (and rehydrate one with key.ImportSubjectPublicKeyInfo(bytes, out _) .

If you're staying on 2.1 (LTS) you can use ExportParameters/ImportParameters with custom serialization logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM