Implement ecc_digits_to_bytes to convert an array of digits into an nbytes-sized byte array. The first byte in the byte array holds the most significant bits of the large integer. Signed-off-by: Stefan Berger <stefanb@xxxxxxxxxxxxx> --- crypto/ecc.c | 22 ++++++++++++++++++++++ include/crypto/internal/ecc.h | 13 +++++++++++++ 2 files changed, 35 insertions(+) diff --git a/crypto/ecc.c b/crypto/ecc.c index af698f8852fb..1cdb5df3aa5d 100644 --- a/crypto/ecc.c +++ b/crypto/ecc.c @@ -90,6 +90,28 @@ void ecc_digits_from_bytes(const u8 *in, unsigned int nbytes, } EXPORT_SYMBOL(ecc_digits_from_bytes); +void ecc_digits_to_bytes(const u64 *in, unsigned int ndigits, + u8 *out, unsigned int nbytes) +{ + unsigned int o = nbytes & 7; + __be64 msd; + int i; + + if (o) { + msd = cpu_to_be64(in[--ndigits]); + memcpy(out, (u8 *)&msd + sizeof(msd) - o, o); + out += o; + nbytes -= o; + } + + for (i = ndigits - 1; i >= 0 && nbytes > 0; i--) { + put_unaligned_be64(in[i], out); + out += sizeof(u64); + nbytes -= sizeof(u64); + } +} +EXPORT_SYMBOL(ecc_digits_to_bytes); + static u64 *ecc_alloc_digits_space(unsigned int ndigits) { size_t len = ndigits * sizeof(u64); diff --git a/include/crypto/internal/ecc.h b/include/crypto/internal/ecc.h index 0717a53ae732..b18297aaff08 100644 --- a/include/crypto/internal/ecc.h +++ b/include/crypto/internal/ecc.h @@ -70,6 +70,19 @@ static inline void ecc_swap_digits(const void *in, u64 *out, unsigned int ndigit void ecc_digits_from_bytes(const u8 *in, unsigned int nbytes, u64 *out, unsigned int ndigits); +/** + * ecc_digits_to_bytes() - Copy digits into a byte array of size nbytes + * @in: Input digits array + * @ndigits: Number of digits in input digits array + * @out: Output byte array + * @nbytes: Number of bytes to copy into byte array + * + * The first byte in the byte array will have the most significant bits of the + * large integer. + */ +void ecc_digits_to_bytes(const u64 *in, unsigned int ndigits, + u8 *out, unsigned int nbytes); + /** * ecc_is_key_valid() - Validate a given ECDH private key * -- 2.43.0