keyblob_utils.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (C) 2012 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <stdint.h>
  17. #include <string.h>
  18. #include <sys/types.h>
  19. #include <unistd.h>
  20. #include <keystore/keystore.h>
  21. /**
  22. * When a key is being migrated from a software keymaster implementation
  23. * to a hardware keymaster implementation, the first 4 bytes of the key_blob
  24. * given to the hardware implementation will be equal to SOFT_KEY_MAGIC.
  25. * The hardware implementation should import these PKCS#8 format keys which
  26. * are encoded like this:
  27. *
  28. * 4-byte SOFT_KEY_MAGIC
  29. *
  30. * 4-byte 32-bit integer big endian for public_key_length. This may be zero
  31. * length which indicates the public key should be derived from the
  32. * private key.
  33. *
  34. * public_key_length bytes of public key (may be empty)
  35. *
  36. * 4-byte 32-bit integer big endian for private_key_length
  37. *
  38. * private_key_length bytes of private key
  39. */
  40. static const uint8_t SOFT_KEY_MAGIC[] = { 'P', 'K', '#', '8' };
  41. size_t get_softkey_header_size() {
  42. return sizeof(SOFT_KEY_MAGIC);
  43. }
  44. uint8_t* add_softkey_header(uint8_t* key_blob, size_t key_blob_length) {
  45. if (key_blob_length < sizeof(SOFT_KEY_MAGIC)) {
  46. return nullptr;
  47. }
  48. memcpy(key_blob, SOFT_KEY_MAGIC, sizeof(SOFT_KEY_MAGIC));
  49. return key_blob + sizeof(SOFT_KEY_MAGIC);
  50. }
  51. bool is_softkey(const uint8_t* key_blob, const size_t key_blob_length) {
  52. if (key_blob_length < sizeof(SOFT_KEY_MAGIC)) {
  53. return false;
  54. }
  55. return !memcmp(key_blob, SOFT_KEY_MAGIC, sizeof(SOFT_KEY_MAGIC));
  56. }