diff mbox series

[RFC,1/3] crypto: ecc - Implement ecc_digits_to_bytes to convert digits to byte array

Message ID 20240612151900.895156-2-stefanb@linux.ibm.com (mailing list archive)
State New
Headers show
Series Introduce ecc_digits_to_bytes and clean up ecdh.c | expand

Commit Message

Stefan Berger June 12, 2024, 3:18 p.m. UTC
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@linux.ibm.com>
---
 crypto/ecc.c                  | 22 ++++++++++++++++++++++
 include/crypto/internal/ecc.h | 13 +++++++++++++
 2 files changed, 35 insertions(+)
diff mbox series

Patch

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
  *