1 // Copyright 2018 Google Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 /////////////////////////////////////////////////////////////////////////////// 16 17 #include "tink/util/keyset_util.h" 18 19 #include <cstdint> 20 #include <random> 21 22 #include "proto/tink.pb.h" 23 24 namespace crypto { 25 namespace tink { 26 27 namespace { 28 29 using google::crypto::tink::Keyset; 30 NewKeyId()31uint32_t NewKeyId() { 32 std::random_device rd; 33 std::minstd_rand0 gen(rd()); 34 std::uniform_int_distribution<uint32_t> dist; 35 return dist(gen); 36 } 37 38 } // namespace 39 GenerateUnusedKeyId(const Keyset & keyset)40uint32_t GenerateUnusedKeyId(const Keyset& keyset) { 41 while (true) { 42 uint32_t key_id = NewKeyId(); 43 bool already_exists = false; 44 for (auto& key : keyset.key()) { 45 if (key.key_id() == key_id) { 46 already_exists = true; 47 break; 48 } 49 } 50 if (!already_exists) return key_id; 51 } 52 } 53 54 } // namespace tink 55 } // namespace crypto 56