Add support for upgrading key types

Old key types were not distinguished by the keystore itself. This change
takes some of the reserved fields in the old format and changes it to a
version number and key type.

Change-Id: I45bd4cdce042617641fe7bd742bbe26da6024996
diff --git a/softkeymaster/keymaster_openssl.cpp b/softkeymaster/keymaster_openssl.cpp
index 7be00ea..fb5b9d0 100644
--- a/softkeymaster/keymaster_openssl.cpp
+++ b/softkeymaster/keymaster_openssl.cpp
@@ -17,6 +17,8 @@
 #include <string.h>
 #include <stdint.h>
 
+#include <keystore.h>
+
 #include <hardware/hardware.h>
 #include <hardware/keymaster.h>
 
@@ -101,7 +103,8 @@
     }
 
     /* int type + int size + private key data + int size + public key data */
-    *keyBlobLength = sizeof(int) + sizeof(int) + privateLen + sizeof(int) + publicLen;
+    *keyBlobLength = get_softkey_header_size() + sizeof(int) + sizeof(int) + privateLen
+            + sizeof(int) + publicLen;
 
     UniquePtr<unsigned char[]> derData(new unsigned char[*keyBlobLength]);
     if (derData.get() == NULL) {
@@ -110,6 +113,9 @@
     }
     unsigned char* p = derData.get();
 
+    /* Write the magic value for software keys. */
+    p = add_softkey_header(p, *keyBlobLength);
+
     /* Write key type to allocated buffer */
     for (int i = sizeof(int) - 1; i >= 0; i--) {
         *p++ = (type >> (8*i)) & 0xFF;
@@ -150,12 +156,19 @@
     }
 
     // Should be large enough for:
-    // int32 type, int32 pubLen, char* pub, int32 privLen, char* priv
-    if (keyBlobLength < (sizeof(int) + sizeof(int) + 1 + sizeof(int) + 1)) {
+    // int32 magic, int32 type, int32 pubLen, char* pub, int32 privLen, char* priv
+    if (keyBlobLength < (get_softkey_header_size() + sizeof(int) + sizeof(int) + 1
+            + sizeof(int) + 1)) {
         ALOGE("key blob appears to be truncated");
         return NULL;
     }
 
+    if (!is_softkey(p, keyBlobLength)) {
+        ALOGE("cannot read key; it was not made by this keymaster");
+        return NULL;
+    }
+    p += get_softkey_header_size();
+
     int type = 0;
     for (size_t i = 0; i < sizeof(int); i++) {
         type = (type << 8) | *p++;
@@ -467,6 +480,8 @@
     dev->common.module = (struct hw_module_t*) module;
     dev->common.close = openssl_close;
 
+    dev->flags = KEYMASTER_SOFTWARE_ONLY;
+
     dev->generate_keypair = openssl_generate_keypair;
     dev->import_keypair = openssl_import_keypair;
     dev->get_keypair_public = openssl_get_keypair_public;