//////////////////////////////////////////////////////////////////////////////// // Copyright 2019 Google LLC. // // This software is licensed under the terms defined in the Widevine Master // License Agreement. For a copy of this agreement, please contact // widevine-licensing@google.com. //////////////////////////////////////////////////////////////////////////////// // // Description: // Shared private key utilities between RSA and EC. #ifndef COMMON_PRIVATE_KEY_UTIL_H_ #define COMMON_PRIVATE_KEY_UTIL_H_ #include #include "glog/logging.h" #include "openssl/bio.h" namespace widevine { namespace private_key_util { template bool SerializeKey(const Key* key, int (*serialization_func)(BIO*, Key*), std::string* serialized_key) { if (key == nullptr) { LOG(ERROR) << "Key is nullptr."; return false; } if (serialized_key == nullptr) { LOG(ERROR) << "Pointer to hold serialized key is nullptr."; return false; } BIO* bio = BIO_new(BIO_s_mem()); if (bio == nullptr) { LOG(ERROR) << "BIO_new returned nullptr"; return false; } bool success = false; if (serialization_func(bio, const_cast(key)) != 0) { int serialized_size = BIO_pending(bio); serialized_key->assign(serialized_size, 0); if (BIO_read(bio, &(*serialized_key)[0], serialized_size) == serialized_size) { success = true; } else { LOG(ERROR) << "BIO_read failure"; } } else { LOG(ERROR) << "Key serialization failure"; } BIO_free(bio); return success; } template bool DeserializeKey(const std::string& serialized_key, Key* (*deserialization_func)(BIO*, Key**), Key** key) { if (serialized_key.empty()) { LOG(ERROR) << "Serialized key is empty."; return false; } if (key == nullptr) { LOG(ERROR) << "Pointer to hold new key is nullptr."; return false; } BIO* bio = BIO_new_mem_buf(const_cast(serialized_key.data()), serialized_key.size()); if (bio == nullptr) { LOG(ERROR) << "BIO_new_mem_buf returned nullptr"; return false; } *key = deserialization_func(bio, nullptr); BIO_free(bio); if (*key == nullptr) { LOG(ERROR) << "Key deserialization failure"; } return *key != nullptr; } } // namespace private_key_util } // namespace widevine #endif // COMMON_PRIVATE_KEY_UTIL_H_