vb21_common2_tests: Fix test for exponent 3 keys

vb2_public_key_read_keyb cannot be used for VB2.1 public keys
(especially not for 2048 exponent 3 or F4, as their size is the
same so the algorithm cannot be guess).

Instead, do what futility/rwsig does and derive the public key from
the private RSA key.

BRANCH=none
BUG=b:64854892
TEST=make runlongtests

Change-Id: Ie81f40e6076cd0c234012b9af58e39425f8b717c
Signed-off-by: Nicolas Boichat <drinkcat@google.com>
Reviewed-on: https://chromium-review.googlesource.com/628177
Commit-Ready: Nicolas Boichat <drinkcat@chromium.org>
Tested-by: Nicolas Boichat <drinkcat@chromium.org>
Reviewed-by: Randall Spangler <rspangler@chromium.org>
Reviewed-by: Caveh Jalali <caveh@google.com>
diff --git a/tests/vb21_common2_tests.c b/tests/vb21_common2_tests.c
index 7f1aefa..7531b59 100644
--- a/tests/vb21_common2_tests.c
+++ b/tests/vb21_common2_tests.c
@@ -17,6 +17,7 @@
 #include "host_key2.h"
 #include "host_signature2.h"
 #include "test_common.h"
+#include "util_misc.h"
 
 
 static const uint8_t test_data[] = "This is some test data to sign.";
@@ -246,7 +247,10 @@
 
 	struct vb2_private_key *prik = NULL;
 	struct vb21_signature *sig2 = NULL;
-	struct vb2_public_key *pubk = NULL;
+	struct vb2_public_key *pubk;
+	uint8_t *pubk_buf = 0;
+	uint8_t *keyb_data = 0;
+	uint32_t keyb_size;
 	struct vb21_packed_key *key2 = NULL;
 
 	printf("***Testing algorithm: %s\n",
@@ -261,11 +265,26 @@
 	prik->sig_alg = sig_alg;
 	vb2_private_key_set_desc(prik, "private key");
 
-	snprintf(filename, sizeof(filename), "%s/key_%s.keyb",
-		 keys_dir,
-		 vb2_get_crypto_algorithm_file(key_algorithm));
-	TEST_SUCC(vb2_public_key_read_keyb(&pubk, filename),
-		  "Read public key");
+
+	/* Create the public key */
+	TEST_SUCC(vb2_public_key_alloc(&pubk, sig_alg), "Allocate public key");
+	/* Extract the keyb blob */
+	TEST_SUCC(vb_keyb_from_rsa(prik->rsa_private_key,
+				   &keyb_data, &keyb_size),
+		  "Extract public key");
+
+	/*
+	 * Copy the keyb blob to the public key's buffer, because that's
+	 * where vb2_unpack_key_data() and vb2_public_key_pack() expect
+	 * to find it.
+	 */
+	pubk_buf = vb2_public_key_packed_data(pubk);
+	memcpy(pubk_buf, keyb_data, keyb_size);
+
+	/* Fill in the internal struct pointers */
+	TEST_SUCC(vb2_unpack_key_data(pubk, pubk_buf, keyb_size),
+		"unpack public key blob");
+
 	pubk->hash_alg = hash_alg;
 	vb2_public_key_set_desc(pubk, "public key");
 	TEST_SUCC(vb21_public_key_pack(&key2, pubk), "Pack public key");