Back to home page

LXR

 
 

    


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