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.
5 #ifndef BASE_CRYPTO_SYMMETRIC_KEY_H_
6 #define BASE_CRYPTO_SYMMETRIC_KEY_H_
11 #include "base/basictypes.h"
14 #include "base/crypto/scoped_nss_types.h"
15 #elif defined(OS_MACOSX)
16 #include <Security/cssmtype.h>
18 #include "base/crypto/scoped_capi_types.h"
23 // Wraps a platform-specific symmetric key and allows it to be held in a
32 virtual ~SymmetricKey();
34 // Generates a random key suitable to be used with |cipher| and of
35 // |key_size_in_bits| bits.
36 // The caller is responsible for deleting the returned SymmetricKey.
37 static SymmetricKey
* GenerateRandomKey(Algorithm algorithm
,
38 size_t key_size_in_bits
);
40 // Derives a key from the supplied password and salt using PBKDF2. The caller
41 // is responsible for deleting the returned SymmetricKey.
42 static SymmetricKey
* DeriveKeyFromPassword(Algorithm algorithm
,
43 const std::string
& password
,
44 const std::string
& salt
,
46 size_t key_size_in_bits
);
48 // Imports a raw key. For this call to be successful, |raw_key| must have been
49 // generated by either GenerateRandomKey or DeriveKeyFromPassword, and
50 // must have been exported with GetRawKey. The caller owns the returned
52 static SymmetricKey
* Import(Algorithm algorithm
, const std::string
& raw_key
);
55 PK11SymKey
* key() const { return key_
.get(); }
56 #elif defined(OS_MACOSX)
57 CSSM_DATA
cssm_data() const;
59 HCRYPTKEY
key() const { return key_
.get(); }
62 // Extracts the raw key from the platform specific data.
63 // Warning: |raw_key| holds the raw key as bytes and thus must be handled
65 bool GetRawKey(std::string
* raw_key
);
69 explicit SymmetricKey(PK11SymKey
* key
);
70 ScopedPK11SymKey key_
;
71 #elif defined(OS_MACOSX)
72 SymmetricKey(const void* key_data
, size_t key_size_in_bits
);
75 SymmetricKey(HCRYPTPROV provider
, HCRYPTKEY key
,
76 const void* key_data
, size_t key_size_in_bytes
);
78 ScopedHCRYPTPROV provider_
;
81 // Contains the raw key, if it is known during initialization and when it
82 // is likely that the associated |provider_| will be unable to export the
83 // |key_|. This is the case of HMAC keys when the key size exceeds 16 bytes
84 // when using the default RSA provider.
85 // TODO(rsleevi): See if KP_EFFECTIVE_KEYLEN is the reason why CryptExportKey
86 // fails with NTE_BAD_KEY/NTE_BAD_LEN
90 DISALLOW_COPY_AND_ASSIGN(SymmetricKey
);
95 #endif // BASE_CRYPTO_SYMMETRIC_KEY_H_