1 // Copyright 2015 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 #include "components/webcrypto/algorithms/secret_key_util.h"
7 #include <openssl/rand.h>
9 #include "base/stl_util.h"
10 #include "components/webcrypto/crypto_data.h"
11 #include "components/webcrypto/generate_key_result.h"
12 #include "components/webcrypto/jwk.h"
13 #include "components/webcrypto/key.h"
14 #include "components/webcrypto/status.h"
15 #include "components/webcrypto/webcrypto_util.h"
16 #include "crypto/openssl_util.h"
20 Status
GenerateWebCryptoSecretKey(const blink::WebCryptoKeyAlgorithm
& algorithm
,
22 blink::WebCryptoKeyUsageMask usages
,
23 unsigned int keylen_bits
,
24 GenerateKeyResult
* result
) {
25 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
27 unsigned int keylen_bytes
= NumBitsToBytes(keylen_bits
);
28 std::vector
<unsigned char> random_bytes(keylen_bytes
, 0);
30 if (keylen_bytes
> 0) {
31 if (!RAND_bytes(vector_as_array(&random_bytes
), keylen_bytes
))
32 return Status::OperationError();
33 TruncateToBitLength(keylen_bits
, &random_bytes
);
36 result
->AssignSecretKey(blink::WebCryptoKey::create(
37 CreateSymmetricKeyHandle(CryptoData(random_bytes
)),
38 blink::WebCryptoKeyTypeSecret
, extractable
, algorithm
, usages
));
40 return Status::Success();
43 Status
CreateWebCryptoSecretKey(const CryptoData
& key_data
,
44 const blink::WebCryptoKeyAlgorithm
& algorithm
,
46 blink::WebCryptoKeyUsageMask usages
,
47 blink::WebCryptoKey
* key
) {
48 *key
= blink::WebCryptoKey::create(CreateSymmetricKeyHandle(key_data
),
49 blink::WebCryptoKeyTypeSecret
, extractable
,
51 return Status::Success();
54 void WriteSecretKeyJwk(const CryptoData
& raw_key_data
,
55 const std::string
& algorithm
,
57 blink::WebCryptoKeyUsageMask usages
,
58 std::vector
<uint8_t>* jwk_key_data
) {
59 JwkWriter
writer(algorithm
, extractable
, usages
, "oct");
60 writer
.SetBytes("k", raw_key_data
);
61 writer
.ToJson(jwk_key_data
);
64 Status
ReadSecretKeyNoExpectedAlgJwk(
65 const CryptoData
& key_data
,
66 bool expected_extractable
,
67 blink::WebCryptoKeyUsageMask expected_usages
,
68 std::vector
<uint8_t>* raw_key_data
,
70 Status status
= jwk
->Init(key_data
, expected_extractable
, expected_usages
,
71 "oct", std::string());
75 std::string jwk_k_value
;
76 status
= jwk
->GetBytes("k", &jwk_k_value
);
79 raw_key_data
->assign(jwk_k_value
.begin(), jwk_k_value
.end());
81 return Status::Success();
84 } // namespace webcrypto