Allow mkimage -k to use a .pem file when the RSA .key file is absent.
Keep .key precedence so existing key selection is preserved.

Signed-off-by: Ayoub Zaki <[email protected]>
---
Changes in v2:
- Report both attempted filenames when fallback fails.

 lib/rsa/rsa-sign.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)

diff --git a/lib/rsa/rsa-sign.c b/lib/rsa/rsa-sign.c
index 3040b345fdd..777e8920e31 100644
--- a/lib/rsa/rsa-sign.c
+++ b/lib/rsa/rsa-sign.c
@@ -176,10 +176,11 @@ static int rsa_get_pub_key(const char *keydir, const char 
*name,
 }
 
 /**
- * rsa_pem_get_priv_key() - read a private key from a .key file
+ * rsa_pem_get_priv_key() - read a PEM-encoded private key
  *
  * @keydir:    Directory containing the key
- * @name       Name of key file (will have a .key extension)
+ * @name       Name of key file (.key, falling back to .pem if absent)
+ * @keyfile:   Explicit key filename, used if keydir or name is absent
  * @evpp       Returns EVP_PKEY object, or NULL on failure
  * Return: 0 if ok, -ve on error (in which case *evpp will be set to NULL)
  */
@@ -202,6 +203,17 @@ static int rsa_pem_get_priv_key(const char *keydir, const 
char *name,
                return -EINVAL;
 
        f = fopen(path, "r");
+       if (!f && errno == ENOENT && keydir && name) {
+               snprintf(path, sizeof(path), "%s/%s.pem", keydir, name);
+               f = fopen(path, "r");
+               if (!f) {
+                       ret = -errno;
+                       fprintf(stderr,
+                               "Couldn't open RSA private key: '%s/%s.key' or 
'%s': %s\n",
+                               keydir, name, path, strerror(-ret));
+                       return ret;
+               }
+       }
        if (!f) {
                ret = -errno;
                fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
-- 
2.53.0

Reply via email to