nsRandomGenerator.cpp (1205B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 #include "nsRandomGenerator.h" 6 7 #include "ScopedNSSTypes.h" 8 #include "nsNSSComponent.h" 9 #include "pk11pub.h" 10 #include "prerror.h" 11 #include "secerr.h" 12 #include "mozilla/UniquePtrExtensions.h" 13 14 NS_IMPL_ISUPPORTS(nsRandomGenerator, nsIRandomGenerator) 15 16 NS_IMETHODIMP 17 nsRandomGenerator::GenerateRandomBytes(uint32_t aLength, uint8_t** aBuffer) { 18 NS_ENSURE_ARG_POINTER(aBuffer); 19 *aBuffer = nullptr; 20 21 mozilla::UniqueFreePtr<uint8_t> buf( 22 static_cast<uint8_t*>(moz_xmalloc(aLength))); 23 nsresult rv = GenerateRandomBytesInto(buf.get(), aLength); 24 NS_ENSURE_SUCCESS(rv, rv); 25 26 *aBuffer = buf.release(); 27 return NS_OK; 28 } 29 30 NS_IMETHODIMP 31 nsRandomGenerator::GenerateRandomBytesInto(uint8_t* aBuffer, uint32_t aLength) { 32 NS_ENSURE_ARG_POINTER(aBuffer); 33 34 mozilla::UniquePK11SlotInfo slot(PK11_GetInternalSlot()); 35 if (!slot) { 36 return NS_ERROR_FAILURE; 37 } 38 39 SECStatus srv = PK11_GenerateRandomOnSlot(slot.get(), aBuffer, aLength); 40 return srv == SECSuccess ? NS_OK : NS_ERROR_FAILURE; 41 }