AWS SDK for C++  0.14.3
AWS SDK for C++
SecureRandom.h
Go to the documentation of this file.
1 /*
2 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15 #pragma once
16 #include <type_traits>
17 
18 namespace Aws
19 {
20  namespace Utils
21  {
22  namespace Crypto
23  {
31  {
32  public:
34  {
35  }
36 
37  virtual ~SecureRandomBytes() = default;
38 
42  virtual void GetBytes(unsigned char* buffer, size_t bufferSize) = 0;
43 
47  operator bool() const { return !m_failure; }
48 
49  protected:
50  bool m_failure;
51  };
52 
56  template <typename DataType = uint64_t>
58  {
59  public:
66  SecureRandom(const std::shared_ptr<SecureRandomBytes>& entropySource) : m_entropy(entropySource)
67  { static_assert(std::is_unsigned<DataType>::value, "Type DataType must be integral"); }
68 
69  virtual ~SecureRandom() = default;
70 
71  virtual void Reset() {}
72 
76  virtual DataType operator()()
77  {
78  DataType value(0);
79  unsigned char buffer[sizeof(DataType)];
80  m_entropy->GetBytes(buffer, sizeof(DataType));
81 
82  assert(*m_entropy);
83  if(*m_entropy)
84  {
85  for (size_t i = 0; i < sizeof(DataType); ++i)
86  {
87  value <<= 8;
88  value |= buffer[i];
89 
90  }
91  }
92 
93  return value;
94  }
95 
96  operator bool() const { return *m_entropy; }
97 
98  private:
99  std::shared_ptr<SecureRandomBytes> m_entropy;
100  };
101 
103  {
104  public:
108  virtual std::shared_ptr<SecureRandomBytes> CreateImplementation() const = 0;
109 
114  virtual void InitStaticState() {}
115 
120  virtual void CleanupStaticState() {}
121  };
122  }
123  }
124 }
virtual DataType operator()()
Definition: SecureRandom.h:76
virtual void GetBytes(unsigned char *buffer, size_t bufferSize)=0
SecureRandom(const std::shared_ptr< SecureRandomBytes > &entropySource)
Definition: SecureRandom.h:66
JSON (JavaScript Object Notation).