1 /*
2 * Copyright 2019 Google LLC
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
17 #include "fcp/base/random_token.h"
18
19 #include <string.h>
20
21 #include <string>
22
23 #include "absl/strings/escaping.h"
24 #include "fcp/base/monitoring.h"
25 #include "openssl/rand.h"
26
27 namespace fcp {
28
Generate()29 RandomToken RandomToken::Generate() {
30 uint64_t words[2];
31 static_assert(sizeof(words) == kRandomTokenSizeInBytes,
32 "Should match the token size");
33 int r = RAND_bytes(reinterpret_cast<unsigned char*>(words),
34 kRandomTokenSizeInBytes);
35 FCP_CHECK(r == 1);
36 return RandomToken(words[0], words[1]);
37 }
38
FromBytes(absl::Span<char const> bytes)39 RandomToken RandomToken::FromBytes(absl::Span<char const> bytes) {
40 FCP_CHECK(bytes.size() == kRandomTokenSizeInBytes);
41
42 uint64_t words[2];
43 static_assert(sizeof(words) == kRandomTokenSizeInBytes,
44 "Should match the token size");
45 memcpy(reinterpret_cast<char*>(words), bytes.data(), kRandomTokenSizeInBytes);
46 return RandomToken(words[0], words[1]);
47 }
48
ToBytes() const49 std::array<char, kRandomTokenSizeInBytes> RandomToken::ToBytes() const {
50 std::array<char, kRandomTokenSizeInBytes> bytes;
51 memcpy(bytes.data(), reinterpret_cast<char const*>(words_),
52 kRandomTokenSizeInBytes);
53 return bytes;
54 }
55
ToString() const56 std::string RandomToken::ToString() const {
57 return std::string(reinterpret_cast<char const*>(words_),
58 kRandomTokenSizeInBytes);
59 }
60
ToPrintableString() const61 std::string RandomToken::ToPrintableString() const {
62 return absl::BytesToHexString(absl::string_view(
63 reinterpret_cast<char const*>(words_), kRandomTokenSizeInBytes));
64 }
65
66 } // namespace fcp
67