diff options
author | Jason A. Donenfeld <Jason@zx2c4.com> | 2019-10-03 16:59:50 +0200 |
---|---|---|
committer | Jason A. Donenfeld <Jason@zx2c4.com> | 2019-10-06 15:10:50 +0200 |
commit | 14c87ed03042d8217eb75fd5326d60d324143696 (patch) | |
tree | c3e17f964340604cab9dfd7ddb9689c4ea07d0b3 /embeddable-dll-service/csharp/Keypair.cs | |
parent | ui: remove unused struct (diff) | |
download | wireguard-windows-14c87ed03042d8217eb75fd5326d60d324143696.tar.xz wireguard-windows-14c87ed03042d8217eb75fd5326d60d324143696.zip |
embeddable-dll-service: add csharp example code
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Diffstat (limited to '')
-rw-r--r-- | embeddable-dll-service/csharp/Keypair.cs | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/embeddable-dll-service/csharp/Keypair.cs b/embeddable-dll-service/csharp/Keypair.cs new file mode 100644 index 00000000..98a00a30 --- /dev/null +++ b/embeddable-dll-service/csharp/Keypair.cs @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: MIT + * + * Copyright (C) 2019 WireGuard LLC. All Rights Reserved. + */ + +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace Tunnel +{ + public class Keypair + { + public readonly string Public; + public readonly string Private; + + private Keypair(string pub, string priv) + { + Public = pub; + Private = priv; + } + + public static Keypair Generate() + { + var algoHandle = new IntPtr(); + var statusCode = Win32.BCryptOpenAlgorithmProvider(ref algoHandle, Win32.BCRYPT_ECDH_ALGORITHM, null, 0); + if (statusCode > 0) + throw new Win32Exception((int)statusCode); + + try + { + var curveType = Win32.BCRYPT_ECC_CURVE_25519 + Char.MinValue; + statusCode = Win32.BCryptSetProperty(algoHandle, Win32.BCRYPT_ECC_CURVE_NAME, curveType, curveType.Length * sizeof(char), 0); + if (statusCode > 0) + throw new Win32Exception((int)statusCode); + var key = new IntPtr(); + statusCode = Win32.BCryptGenerateKeyPair(algoHandle, ref key, 255, 0); + if (statusCode > 0) + throw new Win32Exception((int)statusCode); + try + { + statusCode = Win32.BCryptFinalizeKeyPair(key, 0); + if (statusCode > 0) + throw new Win32Exception((int)statusCode); + + var keyBlob = new Win32.KeyBlob(); + int exportedKeySize = 0; + statusCode = Win32.BCryptExportKey(key, IntPtr.Zero, Win32.BCRYPT_ECCPRIVATE_BLOB, keyBlob, Marshal.SizeOf(typeof(Win32.KeyBlob)), out exportedKeySize); + if (statusCode > 0) + throw new Win32Exception((int)statusCode); + + return new Keypair(Convert.ToBase64String(keyBlob.Public), Convert.ToBase64String(keyBlob.Private)); + } + finally + { + Win32.BCryptDestroyKey(key); + } + } + finally + { + Win32.BCryptCloseAlgorithmProvider(algoHandle, 0); + } + } + } +} |