Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  * Copyright (c) 2016, Intel Corporation
0004  * Authors: Salvatore Benedetto <salvatore.benedetto@intel.com>
0005  */
0006 #include <linux/kernel.h>
0007 #include <linux/export.h>
0008 #include <linux/err.h>
0009 #include <linux/string.h>
0010 #include <crypto/ecdh.h>
0011 #include <crypto/kpp.h>
0012 
0013 #define ECDH_KPP_SECRET_MIN_SIZE (sizeof(struct kpp_secret) + sizeof(short))
0014 
0015 static inline u8 *ecdh_pack_data(void *dst, const void *src, size_t sz)
0016 {
0017     memcpy(dst, src, sz);
0018     return dst + sz;
0019 }
0020 
0021 static inline const u8 *ecdh_unpack_data(void *dst, const void *src, size_t sz)
0022 {
0023     memcpy(dst, src, sz);
0024     return src + sz;
0025 }
0026 
0027 unsigned int crypto_ecdh_key_len(const struct ecdh *params)
0028 {
0029     return ECDH_KPP_SECRET_MIN_SIZE + params->key_size;
0030 }
0031 EXPORT_SYMBOL_GPL(crypto_ecdh_key_len);
0032 
0033 int crypto_ecdh_encode_key(char *buf, unsigned int len,
0034                const struct ecdh *params)
0035 {
0036     u8 *ptr = buf;
0037     struct kpp_secret secret = {
0038         .type = CRYPTO_KPP_SECRET_TYPE_ECDH,
0039         .len = len
0040     };
0041 
0042     if (unlikely(!buf))
0043         return -EINVAL;
0044 
0045     if (len != crypto_ecdh_key_len(params))
0046         return -EINVAL;
0047 
0048     ptr = ecdh_pack_data(ptr, &secret, sizeof(secret));
0049     ptr = ecdh_pack_data(ptr, &params->key_size, sizeof(params->key_size));
0050     ecdh_pack_data(ptr, params->key, params->key_size);
0051 
0052     return 0;
0053 }
0054 EXPORT_SYMBOL_GPL(crypto_ecdh_encode_key);
0055 
0056 int crypto_ecdh_decode_key(const char *buf, unsigned int len,
0057                struct ecdh *params)
0058 {
0059     const u8 *ptr = buf;
0060     struct kpp_secret secret;
0061 
0062     if (unlikely(!buf || len < ECDH_KPP_SECRET_MIN_SIZE))
0063         return -EINVAL;
0064 
0065     ptr = ecdh_unpack_data(&secret, ptr, sizeof(secret));
0066     if (secret.type != CRYPTO_KPP_SECRET_TYPE_ECDH)
0067         return -EINVAL;
0068 
0069     if (unlikely(len < secret.len))
0070         return -EINVAL;
0071 
0072     ptr = ecdh_unpack_data(&params->key_size, ptr, sizeof(params->key_size));
0073     if (secret.len != crypto_ecdh_key_len(params))
0074         return -EINVAL;
0075 
0076     /* Don't allocate memory. Set pointer to data
0077      * within the given buffer
0078      */
0079     params->key = (void *)ptr;
0080 
0081     return 0;
0082 }
0083 EXPORT_SYMBOL_GPL(crypto_ecdh_decode_key);