diff mbox series

[v2,12/14] crypto: ecc - Implement and use ecc_curve_get_nbytes to get curve's nbytes

Message ID 20240215231414.3857320-13-stefanb@linux.ibm.com
State New
Headers show
Series Add support for NIST P521 to ecdsa and ecdh | expand

Commit Message

Stefan Berger Feb. 15, 2024, 11:14 p.m. UTC
Implement ecc_curve_get_nbytes to get a curve's number of bytes (nbytes).
The number of bytes can be derived from the nbits field of a curve, if
set, otherwise from the ndigits field.

Signed-off-by: Stefan Berger <stefanb@linux.ibm.com>
---
 crypto/ecc.c                  |  6 ++----
 include/crypto/internal/ecc.h | 11 +++++++++++
 2 files changed, 13 insertions(+), 4 deletions(-)
diff mbox series

Patch

diff --git a/crypto/ecc.c b/crypto/ecc.c
index 73fbbfc8d69c..f643719450b8 100644
--- a/crypto/ecc.c
+++ b/crypto/ecc.c
@@ -1478,10 +1478,8 @@  static int __ecc_is_key_valid(const struct ecc_curve *curve,
 int ecc_is_key_valid(unsigned int curve_id, unsigned int ndigits,
 		     const u64 *private_key, unsigned int private_key_len)
 {
-	int nbytes;
 	const struct ecc_curve *curve = ecc_get_curve(curve_id);
-
-	nbytes = ndigits << ECC_DIGITS_TO_BYTES_SHIFT;
+	int nbytes = ecc_curve_get_nbytes(curve);
 
 	if (private_key_len != nbytes)
 		return -EINVAL;
@@ -1506,7 +1504,7 @@  int ecc_gen_privkey(unsigned int curve_id, unsigned int ndigits, u64 *privkey)
 {
 	const struct ecc_curve *curve = ecc_get_curve(curve_id);
 	u64 priv[ECC_MAX_DIGITS];
-	unsigned int nbytes = ndigits << ECC_DIGITS_TO_BYTES_SHIFT;
+	unsigned int nbytes = ecc_curve_get_nbytes(curve);
 	unsigned int nbits = vli_num_bits(curve->n, ndigits);
 	int err;
 
diff --git a/include/crypto/internal/ecc.h b/include/crypto/internal/ecc.h
index 6229aa3f3218..5d485d3221d3 100644
--- a/include/crypto/internal/ecc.h
+++ b/include/crypto/internal/ecc.h
@@ -93,6 +93,17 @@  static inline void ecc_digits_to_bytes(const u64 *in, unsigned int ndigits,
 	memcpy(out, &tmp[o], nbytes);
 }
 
+/**
+ * ecc_curve_get_nbytes() - Get the number of bytes the curve requires
+ * @curve:   The curve
+ */
+static inline unsigned int ecc_curve_get_nbytes(const struct ecc_curve *curve)
+{
+	if (curve->nbits)
+		return DIV_ROUND_UP(curve->nbits, 8);
+	return curve->g.ndigits << ECC_DIGITS_TO_BYTES_SHIFT;
+}
+
 /**
  * ecc_is_key_valid() - Validate a given ECDH private key
  *