2 * Copyright (c) 2020 Doc.ai and/or its affiliates.
3 * Copyright (c) 2005-2011 Jouni Malinen <j@w1.fi>.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <wireguard/wireguard_key.h>
18 #include <openssl/evp.h>
21 curve25519_gen_shared (u8 shared_key[CURVE25519_KEY_SIZE],
22 const u8 secret_key[CURVE25519_KEY_SIZE],
23 const u8 basepoint[CURVE25519_KEY_SIZE])
30 EVP_PKEY *peerkey = NULL;
32 EVP_PKEY_new_raw_private_key (EVP_PKEY_X25519, NULL, secret_key,
37 ctx = EVP_PKEY_CTX_new (pkey, NULL);
38 if (EVP_PKEY_derive_init (ctx) <= 0)
45 EVP_PKEY_new_raw_public_key (EVP_PKEY_X25519, NULL, basepoint,
47 if (EVP_PKEY_derive_set_peer (ctx, peerkey) <= 0)
53 key_len = CURVE25519_KEY_SIZE;
54 if (EVP_PKEY_derive (ctx, shared_key, &key_len) <= 0)
60 EVP_PKEY_CTX_free (ctx);
62 EVP_PKEY_free (peerkey);
67 curve25519_gen_public (u8 public_key[CURVE25519_KEY_SIZE],
68 const u8 secret_key[CURVE25519_KEY_SIZE])
72 EVP_PKEY_new_raw_private_key (EVP_PKEY_X25519, NULL, secret_key,
74 pub_len = CURVE25519_KEY_SIZE;
75 if (!EVP_PKEY_get_raw_public_key (pkey, public_key, &pub_len))
85 curve25519_gen_secret (u8 secret_key[CURVE25519_KEY_SIZE])
88 EVP_PKEY *pkey = NULL;
89 EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id (EVP_PKEY_X25519, NULL);
90 EVP_PKEY_keygen_init (pctx);
91 EVP_PKEY_keygen (pctx, &pkey);
92 EVP_PKEY_CTX_free (pctx);
94 secret_len = CURVE25519_KEY_SIZE;
95 if (!EVP_PKEY_get_raw_private_key (pkey, secret_key, &secret_len))
100 EVP_PKEY_free (pkey);
105 key_to_base64 (const u8 * src, size_t src_len, u8 * out)
107 if (!EVP_EncodeBlock (out, src, src_len))
113 key_from_base64 (const u8 * src, size_t src_len, u8 * out)
115 if (EVP_DecodeBlock (out, src, src_len - 1) <= 0)
121 * fd.io coding-style-patch-verification: ON
124 * eval: (c-set-style "gnu")