1 // Copyright (c) 2012 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.
5 #ifndef CRYPTO_SCOPED_CAPI_TYPES_H_
6 #define CRYPTO_SCOPED_CAPI_TYPES_H_
12 #include "base/logging.h"
13 #include "crypto/wincrypt_shim.h"
17 // Simple destructor for the Free family of CryptoAPI functions, such as
18 // CryptDestroyHash, which take only a single argument to release.
19 template <typename CAPIHandle
, BOOL (WINAPI
*Destroyer
)(CAPIHandle
)>
20 struct CAPIDestroyer
{
21 void operator()(CAPIHandle handle
) const {
23 BOOL ok
= Destroyer(handle
);
29 // Destructor for the Close/Release family of CryptoAPI functions, which take
30 // a second DWORD parameter indicating flags to use when closing or releasing.
31 // This includes functions like CertCloseStore or CryptReleaseContext.
32 template <typename CAPIHandle
, BOOL (WINAPI
*Destroyer
)(CAPIHandle
, DWORD
),
34 struct CAPIDestroyerWithFlags
{
35 void operator()(CAPIHandle handle
) const {
37 BOOL ok
= Destroyer(handle
, flags
);
43 // scoped_ptr-like class for the CryptoAPI cryptography and certificate
44 // handles. Because these handles are defined as integer types, and not
45 // pointers, the existing scoped classes, such as scoped_ptr, are insufficient.
46 // The semantics are the same as scoped_ptr.
47 template <class CAPIHandle
, typename FreeProc
>
48 class ScopedCAPIHandle
{
50 explicit ScopedCAPIHandle(CAPIHandle handle
= NULL
) : handle_(handle
) {}
56 void reset(CAPIHandle handle
= NULL
) {
57 if (handle_
!= handle
) {
64 operator CAPIHandle() const { return handle_
; }
65 CAPIHandle
get() const { return handle_
; }
67 CAPIHandle
* receive() {
68 CHECK(handle_
== NULL
);
72 bool operator==(CAPIHandle handle
) const {
73 return handle_
== handle
;
76 bool operator!=(CAPIHandle handle
) const {
77 return handle_
!= handle
;
80 void swap(ScopedCAPIHandle
& b
) {
81 CAPIHandle tmp
= b
.handle_
;
86 CAPIHandle
release() {
87 CAPIHandle tmp
= handle_
;
95 DISALLOW_COPY_AND_ASSIGN(ScopedCAPIHandle
);
98 template<class CH
, typename FP
> inline
99 bool operator==(CH h
, const ScopedCAPIHandle
<CH
, FP
>& b
) {
103 template<class CH
, typename FP
> inline
104 bool operator!=(CH h
, const ScopedCAPIHandle
<CH
, FP
>& b
) {
108 typedef ScopedCAPIHandle
<
110 CAPIDestroyerWithFlags
<HCRYPTPROV
,
111 CryptReleaseContext
, 0> > ScopedHCRYPTPROV
;
113 typedef ScopedCAPIHandle
<
114 HCRYPTKEY
, CAPIDestroyer
<HCRYPTKEY
, CryptDestroyKey
> > ScopedHCRYPTKEY
;
116 typedef ScopedCAPIHandle
<
117 HCRYPTHASH
, CAPIDestroyer
<HCRYPTHASH
, CryptDestroyHash
> > ScopedHCRYPTHASH
;
119 } // namespace crypto
121 #endif // CRYPTO_SCOPED_CAPI_TYPES_H_