openssl_util.h revision 4a5e2dc747d50c653511c68ccb2cfbfb740bd5a7
1// Copyright (c) 2010 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
5#ifndef BASE_OPENSSL_UTIL_H_
6#define BASE_OPENSSL_UTIL_H_
7#pragma once
8
9#include "base/basictypes.h"
10#include "base/tracked.h"
11
12namespace base {
13
14// A helper class that takes care of destroying OpenSSL objects when it goes out
15// of scope.
16template <typename T, void (*destructor)(T*)>
17class ScopedOpenSSL {
18 public:
19  explicit ScopedOpenSSL(T* ptr_) : ptr_(ptr_) { }
20  ~ScopedOpenSSL() { if (ptr_) (*destructor)(ptr_); }
21
22  T* get() const { return ptr_; }
23
24 private:
25  T* ptr_;
26};
27
28// Provides a buffer of at least MIN_SIZE bytes, for use when calling OpenSSL's
29// SHA256, HMAC, etc functions, adapting the buffer sizing rules to meet those
30// of the our base wrapper APIs.
31// This allows the library to write directly to the caller's buffer if it is of
32// sufficient size, but if not it will write to temporary |min_sized_buffer_|
33// of required size and then its content is automatically copied out on
34// destruction, with truncation as appropriate.
35template<int MIN_SIZE>
36class ScopedOpenSSLSafeSizeBuffer {
37 public:
38  ScopedOpenSSLSafeSizeBuffer(unsigned char* output, size_t output_len)
39      : output_(output),
40        output_len_(output_len) {
41  }
42
43  ~ScopedOpenSSLSafeSizeBuffer() {
44    if (output_len_ < MIN_SIZE) {
45      // Copy the temporary buffer out, truncating as needed.
46      memcpy(output_, min_sized_buffer_, output_len_);
47    }
48    // else... any writing already happened directly into |output_|.
49  }
50
51  unsigned char* safe_buffer() {
52    return output_len_ < MIN_SIZE ? min_sized_buffer_ : output_;
53  }
54
55 private:
56  // Pointer to the caller's data area and it's associated size, where data
57  // written via safe_buffer() will [eventually] end up.
58  unsigned char* output_;
59  size_t output_len_;
60
61  // Temporary buffer writen into in the case where the caller's
62  // buffer is not of sufficient size.
63  unsigned char min_sized_buffer_[MIN_SIZE];
64
65  DISALLOW_COPY_AND_ASSIGN(ScopedOpenSSLSafeSizeBuffer);
66};
67
68// Initialize OpenSSL if it isn't already initialized. This must be called
69// before any other OpenSSL functions.
70// This function is thread-safe, and OpenSSL will only ever be initialized once.
71// OpenSSL will be properly shut down on program exit.
72void EnsureOpenSSLInit();
73
74// Drains the OpenSSL ERR_get_error stack. On a debug build the error codes
75// are send to VLOG(1), on a release build they are disregarded.
76void ClearOpenSSLERRStack();
77
78}  // namespace base
79
80#endif  // BASE_OPENSSL_UTIL_H_
81