From a9df634c474033b29640f57454d1b73fc5f1a070 Mon Sep 17 00:00:00 2001
From: Denis Pynkin <denis.pynkin@collabora.com>
Date: Sun, 17 Nov 2019 20:02:13 +0300
Subject: [PATCH] tests/libtest: add functions for ed25519 tests

Add functions for keys generation to be used in signing-related tests:
- gen_ed25519_keys initializing variables ED25519PUBLIC, ED25519SEED and
  ED25519SECRET with appropriate base64-encoded keys
- gen_ed25519_random_public print a random base64 public key (used in
  tests with wrong keys)

Signed-off-by: Denis Pynkin <denis.pynkin@collabora.com>
---
 tests/libtest.sh | 35 +++++++++++++++++++++++++++++++----
 1 file changed, 31 insertions(+), 4 deletions(-)

diff --git a/tests/libtest.sh b/tests/libtest.sh
index 58a9fd9b..c473fd82 100755
--- a/tests/libtest.sh
+++ b/tests/libtest.sh
@@ -673,6 +673,12 @@ which_gpg () {
     echo ${gpg}
 }
 
+libtest_cleanup_gpg () {
+    local gpg_homedir=${1:-${test_tmpdir}/gpghome}
+    gpg-connect-agent --homedir "${gpg_homedir}" killagent /bye || true
+}
+libtest_exit_cmds+=(libtest_cleanup_gpg)
+
 has_libsodium () {
     local ret
     ${CMD_PREFIX} ostree --version > version.txt
@@ -682,12 +688,33 @@ has_libsodium () {
     return ${ret}
 }
 
+# Keys for ed25519 signing tests
+ED25519PUBLIC=
+ED25519SEED=
+ED25519SECRET=
 
-libtest_cleanup_gpg () {
-    local gpg_homedir=${1:-${test_tmpdir}/gpghome}
-    gpg-connect-agent --homedir "${gpg_homedir}" killagent /bye || true
+gen_ed25519_keys ()
+{
+  # Generate private key in PEM format
+  pemfile="$(mktemp -p ${test_tmpdir} ed25519_XXXXXX.pem)"
+  openssl genpkey -algorithm ed25519 -outform PEM -out "${pemfile}"
+
+  # Based on: http://openssl.6102.n7.nabble.com/ed25519-key-generation-td73907.html
+  # Extract the private and public parts from generated key.
+  ED25519PUBLIC="$(openssl pkey -outform DER -pubout -in ${pemfile} | tail -c 32 | base64)"
+  ED25519SEED="$(openssl pkey -outform DER -in ${pemfile} | tail -c 32 | base64)"
+  # Secret key is concantination of SEED and PUBLIC
+  ED25519SECRET="$(echo ${ED25519SEED}${ED25519PUBLIC} | base64 -d | base64 -w 0)"
+
+  echo "Generated ed25519 keys:"
+  echo "public: ${ED25519PUBLIC}"
+  echo "  seed: ${ED25519SEED}"
+}
+
+gen_ed25519_random_public()
+{
+  openssl genpkey -algorithm ED25519 | openssl pkey -outform DER | tail -c 32 | base64
 }
-libtest_exit_cmds+=(libtest_cleanup_gpg)
 
 is_bare_user_only_repo () {
   grep -q 'mode=bare-user-only' $1/config