blink_key_handle.cc 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/webcrypto/blink_key_handle.h"
  5. #include <utility>
  6. #include "base/check_op.h"
  7. #include "third_party/boringssl/src/include/openssl/evp.h"
  8. namespace webcrypto {
  9. namespace {
  10. class SymKey;
  11. class AsymKey;
  12. // Base class for wrapping OpenSSL keys in a type that can be passed to
  13. // Blink (blink::WebCryptoKeyHandle).
  14. class Key : public blink::WebCryptoKeyHandle {
  15. public:
  16. // Helpers to add some safety to casting.
  17. virtual SymKey* AsSymKey() { return nullptr; }
  18. virtual AsymKey* AsAsymKey() { return nullptr; }
  19. };
  20. class SymKey : public Key {
  21. public:
  22. explicit SymKey(base::span<const uint8_t> raw_key_data)
  23. : raw_key_data_(raw_key_data.begin(), raw_key_data.end()) {}
  24. SymKey(const SymKey&) = delete;
  25. SymKey& operator=(const SymKey&) = delete;
  26. SymKey* AsSymKey() override { return this; }
  27. const std::vector<uint8_t>& raw_key_data() const { return raw_key_data_; }
  28. private:
  29. std::vector<uint8_t> raw_key_data_;
  30. };
  31. class AsymKey : public Key {
  32. public:
  33. // After construction the |pkey| should NOT be mutated.
  34. explicit AsymKey(bssl::UniquePtr<EVP_PKEY> pkey) : pkey_(std::move(pkey)) {}
  35. AsymKey(const AsymKey&) = delete;
  36. AsymKey& operator=(const AsymKey&) = delete;
  37. AsymKey* AsAsymKey() override { return this; }
  38. // The caller should NOT mutate this EVP_PKEY.
  39. EVP_PKEY* pkey() { return pkey_.get(); }
  40. private:
  41. bssl::UniquePtr<EVP_PKEY> pkey_;
  42. };
  43. Key* GetKey(const blink::WebCryptoKey& key) {
  44. return static_cast<Key*>(key.Handle());
  45. }
  46. } // namespace
  47. const std::vector<uint8_t>& GetSymmetricKeyData(
  48. const blink::WebCryptoKey& key) {
  49. DCHECK_EQ(blink::kWebCryptoKeyTypeSecret, key.GetType());
  50. return GetKey(key)->AsSymKey()->raw_key_data();
  51. }
  52. EVP_PKEY* GetEVP_PKEY(const blink::WebCryptoKey& key) {
  53. DCHECK_NE(blink::kWebCryptoKeyTypeSecret, key.GetType());
  54. return GetKey(key)->AsAsymKey()->pkey();
  55. }
  56. blink::WebCryptoKeyHandle* CreateSymmetricKeyHandle(
  57. base::span<const uint8_t> key_bytes) {
  58. return new SymKey(key_bytes);
  59. }
  60. blink::WebCryptoKeyHandle* CreateAsymmetricKeyHandle(
  61. bssl::UniquePtr<EVP_PKEY> pkey) {
  62. return new AsymKey(std::move(pkey));
  63. }
  64. } // namespace webcrypto