android_keymaster_utils.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * Copyright 2014 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 <keymaster/android_keymaster_utils.h>
  17. #include <keymaster/new>
  18. namespace keymaster {
  19. // Keymaster never manages enormous buffers, so anything particularly large is bad data or the
  20. // result of a bug. We arbitrarily set a 16 MiB limit.
  21. const size_t kMaxDupBufferSize = 16 * 1024 * 1024;
  22. uint8_t* dup_buffer(const void* buf, size_t size) {
  23. if (size >= kMaxDupBufferSize)
  24. return nullptr;
  25. uint8_t* retval = new (std::nothrow) uint8_t[size];
  26. if (retval)
  27. memcpy(retval, buf, size);
  28. return retval;
  29. }
  30. int memcmp_s(const void* p1, const void* p2, size_t length) {
  31. const uint8_t* s1 = static_cast<const uint8_t*>(p1);
  32. const uint8_t* s2 = static_cast<const uint8_t*>(p2);
  33. uint8_t result = 0;
  34. while (length-- > 0)
  35. result |= *s1++ ^ *s2++;
  36. return result == 0 ? 0 : 1;
  37. }
  38. keymaster_error_t EcKeySizeToCurve(uint32_t key_size_bits, keymaster_ec_curve_t* curve) {
  39. switch (key_size_bits) {
  40. default:
  41. return KM_ERROR_UNSUPPORTED_KEY_SIZE;
  42. case 224:
  43. *curve = KM_EC_CURVE_P_224;
  44. break;
  45. case 256:
  46. *curve = KM_EC_CURVE_P_256;
  47. break;
  48. case 384:
  49. *curve = KM_EC_CURVE_P_384;
  50. break;
  51. case 521:
  52. *curve = KM_EC_CURVE_P_521;
  53. break;
  54. }
  55. return KM_ERROR_OK;
  56. }
  57. keymaster_error_t EcCurveToKeySize(keymaster_ec_curve_t curve, uint32_t* key_size_bits) {
  58. switch (curve) {
  59. default:
  60. return KM_ERROR_UNSUPPORTED_EC_CURVE;
  61. case KM_EC_CURVE_P_224:
  62. *key_size_bits = 224;
  63. break;
  64. case KM_EC_CURVE_P_256:
  65. *key_size_bits = 256;
  66. break;
  67. case KM_EC_CURVE_P_384:
  68. *key_size_bits = 384;
  69. break;
  70. case KM_EC_CURVE_P_521:
  71. *key_size_bits = 521;
  72. break;
  73. }
  74. return KM_ERROR_OK;
  75. }
  76. } // namespace keymaster