1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "js/ScalarType.h"
9 #include "js/experimental/TypedData.h" // JS_GetArrayBufferViewType
11 #include "nsIRandomGenerator.h"
12 #include "nsReadableUtils.h"
14 #include "mozilla/dom/CryptoBinding.h"
15 #include "mozilla/dom/SubtleCrypto.h"
16 #include "nsServiceManagerUtils.h"
18 namespace mozilla::dom
{
20 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Crypto
)
21 NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
22 NS_INTERFACE_MAP_ENTRY(nsISupports
)
25 NS_IMPL_CYCLE_COLLECTING_ADDREF(Crypto
)
26 NS_IMPL_CYCLE_COLLECTING_RELEASE(Crypto
)
28 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE(Crypto
, mParent
, mSubtle
)
30 Crypto::Crypto(nsIGlobalObject
* aParent
) : mParent(aParent
) {}
32 Crypto::~Crypto() = default;
35 JSObject
* Crypto::WrapObject(JSContext
* aCx
,
36 JS::Handle
<JSObject
*> aGivenProto
) {
37 return Crypto_Binding::Wrap(aCx
, this, aGivenProto
);
40 void Crypto::GetRandomValues(JSContext
* aCx
, const ArrayBufferView
& aArray
,
41 JS::MutableHandle
<JSObject
*> aRetval
,
43 // Throw if the wrong type of ArrayBufferView is passed in
44 // (Part of the Web Crypto API spec)
45 switch (aArray
.Type()) {
46 case js::Scalar::Int8
:
47 case js::Scalar::Uint8
:
48 case js::Scalar::Uint8Clamped
:
49 case js::Scalar::Int16
:
50 case js::Scalar::Uint16
:
51 case js::Scalar::Int32
:
52 case js::Scalar::Uint32
:
53 case js::Scalar::BigInt64
:
54 case js::Scalar::BigUint64
:
57 aRv
.Throw(NS_ERROR_DOM_TYPE_MISMATCH_ERR
);
61 nsCOMPtr
<nsIRandomGenerator
> randomGenerator
=
62 do_GetService("@mozilla.org/security/random-generator;1");
63 if (!randomGenerator
) {
64 aRv
.Throw(NS_ERROR_DOM_OPERATION_ERR
);
68 aArray
.ProcessFixedData([&](const Span
<uint8_t>& aData
) {
69 if (aData
.Length() == 0) {
70 NS_WARNING("ArrayBufferView length is 0, cannot continue");
71 aRetval
.set(aArray
.Obj());
75 if (aData
.Length() > 65536) {
76 aRv
.ThrowQuotaExceededError(
77 "getRandomValues can only generate maximum 65536 bytes");
81 nsresult rv
= randomGenerator
->GenerateRandomBytesInto(aData
.Elements(),
84 aRv
.Throw(NS_ERROR_DOM_OPERATION_ERR
);
88 aRetval
.set(aArray
.Obj());
92 void Crypto::RandomUUID(nsACString
& aRetVal
) {
93 // NSID_LENGTH == 39 == 36 UUID chars + 2 curly braces + 1 NUL byte
94 static_assert(NSID_LENGTH
== 39);
96 nsIDToCString
uuidString(nsID::GenerateUUID());
97 MOZ_ASSERT(strlen(uuidString
.get()) == NSID_LENGTH
- 1);
99 // Omit the curly braces and NUL.
100 aRetVal
= Substring(uuidString
.get() + 1, NSID_LENGTH
- 3);
101 MOZ_ASSERT(aRetVal
.Length() == NSID_LENGTH
- 3);
104 SubtleCrypto
* Crypto::Subtle() {
106 mSubtle
= new SubtleCrypto(GetParentObject());
111 } // namespace mozilla::dom