本文整理汇总了C++中CryptoBuffer类的典型用法代码示例。如果您正苦于以下问题:C++ CryptoBuffer类的具体用法?C++ CryptoBuffer怎么用?C++ CryptoBuffer使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CryptoBuffer类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: IncrementCounter
void AES_CTR_Cipher_BCrypt::IncrementCounter(CryptoBuffer& buffer)
{
assert(buffer.GetLength() == BlockSizeBytes);
int32_t ctr = 0;
for (size_t i = BlockSizeBytes - 5; i < BlockSizeBytes; ++i)
{
ctr <<= 8;
ctr |= buffer[i];
}
ctr += 1;
for (size_t i = BlockSizeBytes - 1; i > BlockSizeBytes - 5; --i)
{
buffer[i] = ctr & 0x000000FF;
ctr >>= 8;
}
}
示例2: AssembleClientData
static nsresult
AssembleClientData(const nsAString& aOrigin, const nsAString& aTyp,
const nsAString& aChallenge, CryptoBuffer& aClientData)
{
ClientData clientDataObject;
clientDataObject.mTyp.Construct(aTyp); // "Typ" from the U2F specification
clientDataObject.mChallenge.Construct(aChallenge);
clientDataObject.mOrigin.Construct(aOrigin);
nsAutoString json;
if (NS_WARN_IF(!clientDataObject.ToJSON(json))) {
return NS_ERROR_FAILURE;
}
if (NS_WARN_IF(!aClientData.Assign(NS_ConvertUTF16toUTF8(json)))) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
示例3: arena
UniqueSECKEYPublicKey
CryptoKey::PublicECKeyFromRaw(CryptoBuffer& aKeyData,
const nsString& aNamedCurve,
const nsNSSShutDownPreventionLock& /*proofOfLock*/)
{
UniquePLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
if (!arena) {
return nullptr;
}
SECItem rawItem = { siBuffer, nullptr, 0 };
if (!aKeyData.ToSECItem(arena.get(), &rawItem)) {
return nullptr;
}
uint32_t flen;
if (aNamedCurve.EqualsLiteral(WEBCRYPTO_NAMED_CURVE_P256)) {
flen = 32; // bytes
} else if (aNamedCurve.EqualsLiteral(WEBCRYPTO_NAMED_CURVE_P384)) {
flen = 48; // bytes
} else if (aNamedCurve.EqualsLiteral(WEBCRYPTO_NAMED_CURVE_P521)) {
flen = 66; // bytes
} else {
return nullptr;
}
// Check length of uncompressed point coordinates. There are 2 field elements
// and a leading point form octet (which must EC_POINT_FORM_UNCOMPRESSED).
if (rawItem.len != (2 * flen + 1)) {
return nullptr;
}
// No support for compressed points.
if (rawItem.data[0] != EC_POINT_FORM_UNCOMPRESSED) {
return nullptr;
}
return CreateECPublicKey(&rawItem, aNamedCurve);
}
示例4: ReturnError
NS_IMETHODIMP
U2FSignTask::Run()
{
nsNSSShutDownPreventionLock locker;
if (isAlreadyShutDown()) {
ReturnError(ErrorCode::OTHER_ERROR);
return NS_ERROR_FAILURE;
}
// Search the requests for one a token can fulfill
for (size_t i = 0; i < mRegisteredKeys.Length(); i += 1) {
RegisteredKey request(mRegisteredKeys[i]);
// Check for required attributes
if (!(request.mVersion.WasPassed() &&
request.mKeyHandle.WasPassed())) {
continue;
}
// Do not permit an individual RegisteredKey to assert a different AppID
if (request.mAppId.WasPassed() && mAppId != request.mAppId.Value()) {
continue;
}
// Assemble a clientData object
CryptoBuffer clientData;
nsresult rv = AssembleClientData(mOrigin, kGetAssertion, mChallenge,
clientData);
if (NS_WARN_IF(NS_FAILED(rv))) {
ReturnError(ErrorCode::OTHER_ERROR);
return NS_ERROR_FAILURE;
}
// Hash the AppID and the ClientData into the AppParam and ChallengeParam
SECStatus srv;
nsCString cAppId = NS_ConvertUTF16toUTF8(mAppId);
CryptoBuffer appParam;
CryptoBuffer challengeParam;
if (!appParam.SetLength(SHA256_LENGTH, fallible) ||
!challengeParam.SetLength(SHA256_LENGTH, fallible)) {
ReturnError(ErrorCode::OTHER_ERROR);
return NS_ERROR_FAILURE;
}
srv = PK11_HashBuf(SEC_OID_SHA256, appParam.Elements(),
reinterpret_cast<const uint8_t*>(cAppId.BeginReading()),
cAppId.Length());
if (srv != SECSuccess) {
ReturnError(ErrorCode::OTHER_ERROR);
return NS_ERROR_FAILURE;
}
srv = PK11_HashBuf(SEC_OID_SHA256, challengeParam.Elements(),
clientData.Elements(), clientData.Length());
if (srv != SECSuccess) {
ReturnError(ErrorCode::OTHER_ERROR);
return NS_ERROR_FAILURE;
}
// Decode the key handle
CryptoBuffer keyHandle;
rv = keyHandle.FromJwkBase64(request.mKeyHandle.Value());
if (NS_WARN_IF(NS_FAILED(rv))) {
ReturnError(ErrorCode::OTHER_ERROR);
return NS_ERROR_FAILURE;
}
// Get the signature from the token
CryptoBuffer signatureData;
bool signSuccess = false;
// We ignore mTransports, as it is intended to be used for sorting the
// available devices by preference, but is not an exclusion factor.
for (size_t a = 0; a < mAuthenticators.Length() && !signSuccess; ++a) {
Authenticator token(mAuthenticators[a]);
bool isCompatible = false;
bool isRegistered = false;
rv = token->IsCompatibleVersion(request.mVersion.Value(), &isCompatible);
if (NS_FAILED(rv)) {
ReturnError(ErrorCode::OTHER_ERROR);
return NS_ERROR_FAILURE;
}
if (!isCompatible) {
continue;
}
rv = token->IsRegistered(keyHandle.Elements(), keyHandle.Length(),
&isRegistered);
if (NS_FAILED(rv)) {
ReturnError(ErrorCode::OTHER_ERROR);
return NS_ERROR_FAILURE;
}
if (isCompatible && isRegistered) {
uint8_t* buffer;
uint32_t bufferlen;
nsresult rv = token->Sign(appParam.Elements(), appParam.Length(),
challengeParam.Elements(), challengeParam.Length(),
//.........这里部分代码省略.........
示例5: arena
nsresult
CryptoKey::PublicKeyToSpki(SECKEYPublicKey* aPubKey,
CryptoBuffer& aRetVal,
const nsNSSShutDownPreventionLock& /*proofOfLock*/)
{
ScopedCERTSubjectPublicKeyInfo spki;
// NSS doesn't support exporting DH public keys.
if (aPubKey->keyType == dhKey) {
// Mimic the behavior of SECKEY_CreateSubjectPublicKeyInfo() and create
// a new arena for the SPKI object.
ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
if (!arena) {
return NS_ERROR_DOM_OPERATION_ERR;
}
spki = PORT_ArenaZNew(arena, CERTSubjectPublicKeyInfo);
if (!spki) {
return NS_ERROR_DOM_OPERATION_ERR;
}
// Assign |arena| to |spki| and null the variable afterwards so that the
// arena created above that holds the SPKI object is free'd when |spki|
// goes out of scope, not when |arena| does.
spki->arena = arena.forget();
nsresult rv = PublicDhKeyToSpki(aPubKey, spki);
NS_ENSURE_SUCCESS(rv, rv);
} else {
spki = SECKEY_CreateSubjectPublicKeyInfo(aPubKey);
if (!spki) {
return NS_ERROR_DOM_OPERATION_ERR;
}
}
// Per WebCrypto spec we must export ECDH SPKIs with the algorithm OID
// id-ecDH (1.3.132.112) and DH SPKIs with OID dhKeyAgreement
// (1.2.840.113549.1.3.1). NSS doesn't know about these OIDs and there is
// no way to specify the algorithm to use when exporting a public key.
if (aPubKey->keyType == ecKey || aPubKey->keyType == dhKey) {
const SECItem* oidData = nullptr;
if (aPubKey->keyType == ecKey) {
oidData = &SEC_OID_DATA_EC_DH;
} else if (aPubKey->keyType == dhKey) {
oidData = &SEC_OID_DATA_DH_KEY_AGREEMENT;
} else {
MOZ_ASSERT(false);
}
SECStatus rv = SECITEM_CopyItem(spki->arena, &spki->algorithm.algorithm,
oidData);
if (rv != SECSuccess) {
return NS_ERROR_DOM_OPERATION_ERR;
}
}
const SEC_ASN1Template* tpl = SEC_ASN1_GET(CERT_SubjectPublicKeyInfoTemplate);
ScopedSECItem spkiItem(SEC_ASN1EncodeItem(nullptr, nullptr, spki, tpl));
aRetVal.Assign(spkiItem.get());
return NS_OK;
}
示例6: finalBufferSet
/**
* Windows doesn't expose CTR mode. We can however, build it manually from ECB. Here, split each
* buffer into 16 byte chunks, for each complete buffer encrypt the counter and xor it against the unencrypted
* text. Save anything left over for the next run.
*/
CryptoBuffer AES_CTR_Cipher_BCrypt::EncryptWithCtr(const CryptoBuffer& buffer)
{
size_t bytesWritten = 0;
Aws::Vector<ByteBuffer*> finalBufferSet(0);
CryptoBuffer bufferToEncrypt;
if (m_blockOverflow.GetLength() > 0 && &m_blockOverflow != &buffer)
{
bufferToEncrypt = CryptoBuffer({ (ByteBuffer*)&m_blockOverflow, (ByteBuffer*)&buffer });
m_blockOverflow = CryptoBuffer();
}
else
{
bufferToEncrypt = buffer;
}
Aws::Utils::Array<CryptoBuffer> slicedBuffers;
if (bufferToEncrypt.GetLength() > BlockSizeBytes)
{
slicedBuffers = bufferToEncrypt.Slice(BlockSizeBytes);
}
else
{
slicedBuffers = Aws::Utils::Array<CryptoBuffer>(1u);
slicedBuffers[0] = bufferToEncrypt;
}
finalBufferSet = Aws::Vector<ByteBuffer*>(slicedBuffers.GetLength());
InitBuffersToNull(finalBufferSet);
for (size_t i = 0; i < slicedBuffers.GetLength(); ++i)
{
if (slicedBuffers[i].GetLength() == BlockSizeBytes || (m_blockOverflow.GetLength() > 0 && slicedBuffers.GetLength() == 1))
{
ULONG lengthWritten = static_cast<ULONG>(BlockSizeBytes);
CryptoBuffer encryptedText(BlockSizeBytes);
NTSTATUS status = BCryptEncrypt(m_keyHandle, m_workingIv.GetUnderlyingData(), (ULONG)m_workingIv.GetLength(),
nullptr, nullptr, 0, encryptedText.GetUnderlyingData(), (ULONG)encryptedText.GetLength(), &lengthWritten, m_flags);
if (!NT_SUCCESS(status))
{
m_failure = true;
AWS_LOGSTREAM_ERROR(CTR_LOG_TAG, "Failed to compute encrypted output with error code " << status);
CleanupBuffers(finalBufferSet);
return CryptoBuffer();
}
CryptoBuffer* newBuffer = Aws::New<CryptoBuffer>(CTR_LOG_TAG, BlockSizeBytes);
*newBuffer = slicedBuffers[i] ^ encryptedText;
finalBufferSet[i] = newBuffer;
IncrementCounter(m_workingIv);
bytesWritten += static_cast<size_t>(lengthWritten);
}
else
{
m_blockOverflow = slicedBuffers[i];
CryptoBuffer* newBuffer = Aws::New<CryptoBuffer>(CTR_LOG_TAG, 0);
finalBufferSet[i] = newBuffer;
}
}
CryptoBuffer returnBuffer(std::move(finalBufferSet));
CleanupBuffers(finalBufferSet);
return returnBuffer;
}
示例7: MOZ_ASSERT
already_AddRefed<Promise>
WebAuthentication::GetAssertion(const ArrayBufferViewOrArrayBuffer& aChallenge,
const AssertionOptions& aOptions)
{
MOZ_ASSERT(mParent);
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
if (!global) {
return nullptr;
}
// 4.1.2.1 If timeoutSeconds was specified, check if its value lies within a
// reasonable range as defined by the platform and if not, correct it to the
// closest value lying within that range.
double adjustedTimeout = 30.0;
if (aOptions.mTimeoutSeconds.WasPassed()) {
adjustedTimeout = aOptions.mTimeoutSeconds.Value();
adjustedTimeout = std::max(15.0, adjustedTimeout);
adjustedTimeout = std::min(120.0, adjustedTimeout);
}
// 4.1.2.2 Let promise be a new Promise. Return promise and start a timer for
// adjustedTimeout seconds.
RefPtr<AssertionRequest> requestMonitor = new AssertionRequest();
requestMonitor->SetDeadline(TimeDuration::FromSeconds(adjustedTimeout));
ErrorResult rv;
RefPtr<Promise> promise = Promise::Create(global, rv);
nsresult initRv = InitLazily();
if (NS_FAILED(initRv)) {
promise->MaybeReject(initRv);
return promise.forget();
}
if (mOrigin.EqualsLiteral("null")) {
// 4.1.2.3 If callerOrigin is an opaque origin, reject promise with a
// DOMException whose name is "NotAllowedError", and terminate this algorithm
promise->MaybeReject(NS_ERROR_DOM_NOT_ALLOWED_ERR);
return promise.forget();
}
nsCString rpId;
if (!aOptions.mRpId.WasPassed()) {
// 4.1.2.3.a If rpId is not specified, then set rpId to callerOrigin, and
// rpIdHash to the SHA-256 hash of rpId.
rpId.Assign(NS_ConvertUTF16toUTF8(mOrigin));
} else {
// 4.1.2.3.b If rpId is specified, then invoke the procedure used for
// relaxing the same-origin restriction by setting the document.domain
// attribute, using rpId as the given value but without changing the current
// document’s domain. If no errors are thrown, set rpId to the value of host
// as computed by this procedure, and rpIdHash to the SHA-256 hash of rpId.
// Otherwise, reject promise with a DOMException whose name is
// "SecurityError", and terminate this algorithm.
if (NS_FAILED(RelaxSameOrigin(aOptions.mRpId.Value(), rpId))) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
}
CryptoBuffer rpIdHash;
if (!rpIdHash.SetLength(SHA256_LENGTH, fallible)) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
nsresult srv;
nsCOMPtr<nsICryptoHash> hashService =
do_CreateInstance(NS_CRYPTO_HASH_CONTRACTID, &srv);
if (NS_WARN_IF(NS_FAILED(srv))) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
srv = HashCString(hashService, rpId, rpIdHash);
if (NS_WARN_IF(NS_FAILED(srv))) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
// 4.1.2.4 If extensions was specified, process any extensions supported by
// this client platform, to produce the extension data that needs to be sent
// to the authenticator. If an error is encountered while processing an
// extension, skip that extension and do not produce any extension data for
// it. Call the result of this processing clientExtensions.
// TODO
// 4.1.2.5 Use assertionChallenge, callerOrigin and rpId, along with the token
// binding key associated with callerOrigin (if any), to create a ClientData
// structure representing this request. Choose a hash algorithm for hashAlg
// and compute the clientDataJSON and clientDataHash.
CryptoBuffer challenge;
if (!challenge.Assign(aChallenge)) {
promise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
return promise.forget();
}
//.........这里部分代码省略.........
示例8: MOZ_LOG
// NOTE: This method represents a theoretical way to use a U2F-compliant token
// to produce the result of the WebAuthn GetAssertion method. The exact mapping
// of U2F data fields to WebAuthn data fields is still a matter of ongoing
// discussion, and this should not be taken as anything but a point-in- time
// possibility.
void
WebAuthentication::U2FAuthGetAssertion(const RefPtr<AssertionRequest>& aRequest,
const Authenticator& aToken, CryptoBuffer& aRpIdHash,
const nsACString& aClientData, CryptoBuffer& aClientDataHash,
nsTArray<CryptoBuffer>& aAllowList,
const WebAuthnExtensions& aExtensions)
{
MOZ_LOG(gWebauthLog, LogLevel::Debug, ("U2FAuthGetAssertion"));
// 4.1.2.7.e Add an entry to issuedRequests, corresponding to this request.
aRequest->AddActiveToken(__func__);
// 4.1.2.8 While issuedRequests is not empty, perform the following actions
// depending upon the adjustedTimeout timer and responses from the
// authenticators:
// 4.1.2.8.a If the timer for adjustedTimeout expires, then for each entry
// in issuedRequests invoke the authenticatorCancel operation on that
// authenticator and remove its entry from the list.
for (CryptoBuffer& allowedCredential : aAllowList) {
bool isRegistered = false;
nsresult rv = aToken->IsRegistered(allowedCredential.Elements(),
allowedCredential.Length(),
&isRegistered);
// 4.1.2.8.b If any authenticator returns a status indicating that the user
// cancelled the operation, delete that authenticator’s entry from
// issuedRequests. For each remaining entry in issuedRequests invoke the
// authenticatorCancel operation on that authenticator, and remove its entry
// from the list.
// 4.1.2.8.c If any authenticator returns an error status, delete the
// corresponding entry from issuedRequests.
if (NS_WARN_IF(NS_FAILED(rv))) {
aRequest->SetFailure(rv);
return;
}
if (!isRegistered) {
continue;
}
// Sign
uint8_t* buffer;
uint32_t bufferlen;
rv = aToken->Sign(aRpIdHash.Elements(), aRpIdHash.Length(),
aClientDataHash.Elements(), aClientDataHash.Length(),
allowedCredential.Elements(), allowedCredential.Length(),
&buffer, &bufferlen);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRequest->SetFailure(rv);
return;
}
MOZ_ASSERT(buffer);
CryptoBuffer signatureData;
if (NS_WARN_IF(!signatureData.Assign(buffer, bufferlen))) {
free(buffer);
aRequest->SetFailure(NS_ERROR_OUT_OF_MEMORY);
return;
}
free(buffer);
// 4.1.2.8.d If any authenticator returns success:
// 4.1.2.8.d.1 Remove this authenticator’s entry from issuedRequests.
// 4.1.2.8.d.2 Create a new WebAuthnAssertion object named value and
// populate its fields with the values returned from the authenticator as
// well as the clientDataJSON computed earlier.
CryptoBuffer clientDataBuf;
if (!clientDataBuf.Assign(aClientData)) {
aRequest->SetFailure(NS_ERROR_OUT_OF_MEMORY);
return;
}
CryptoBuffer authenticatorDataBuf;
rv = U2FAssembleAuthenticatorData(authenticatorDataBuf, aRpIdHash,
signatureData);
if (NS_WARN_IF(NS_FAILED(rv))) {
aRequest->SetFailure(rv);
return;
}
RefPtr<ScopedCredential> credential = new ScopedCredential(this);
credential->SetType(ScopedCredentialType::ScopedCred);
credential->SetId(allowedCredential);
AssertionPtr assertion = new WebAuthnAssertion(this);
assertion->SetCredential(credential);
assertion->SetClientData(clientDataBuf);
assertion->SetAuthenticatorData(authenticatorDataBuf);
assertion->SetSignature(signatureData);
//.........这里部分代码省略.........
示例9: U2FDecomposeRegistrationResponse
static nsresult
U2FDecomposeRegistrationResponse(const CryptoBuffer& aResponse,
/* out */ CryptoBuffer& aPubKeyBuf,
/* out */ CryptoBuffer& aKeyHandleBuf,
/* out */ CryptoBuffer& aAttestationCertBuf,
/* out */ CryptoBuffer& aSignatureBuf)
{
// U2F v1.1 Format via
// http://fidoalliance.org/specs/fido-u2f-v1.1-id-20160915/fido-u2f-raw-message-formats-v1.1-id-20160915.html
//
// Bytes Value
// 1 0x05
// 65 public key
// 1 key handle length
// * key handle
// ASN.1 attestation certificate
// * attestation signature
pkix::Input u2fResponse;
u2fResponse.Init(aResponse.Elements(), aResponse.Length());
pkix::Reader input(u2fResponse);
uint8_t b;
if (input.Read(b) != pkix::Success) {
return NS_ERROR_DOM_UNKNOWN_ERR;
}
if (b != 0x05) {
return NS_ERROR_DOM_UNKNOWN_ERR;
}
nsresult rv = ReadToCryptoBuffer(input, aPubKeyBuf, 65);
if (NS_FAILED(rv)) {
return rv;
}
uint8_t handleLen;
if (input.Read(handleLen) != pkix::Success) {
return NS_ERROR_DOM_UNKNOWN_ERR;
}
rv = ReadToCryptoBuffer(input, aKeyHandleBuf, handleLen);
if (NS_FAILED(rv)) {
return rv;
}
// We have to parse the ASN.1 SEQUENCE on the outside to determine the cert's
// length.
pkix::Input cert;
if (pkix::der::ExpectTagAndGetValue(input, pkix::der::SEQUENCE, cert)
!= pkix::Success) {
return NS_ERROR_DOM_UNKNOWN_ERR;
}
pkix::Reader certInput(cert);
rv = ReadToCryptoBuffer(certInput, aAttestationCertBuf, cert.GetLength());
if (NS_FAILED(rv)) {
return rv;
}
// The remainder of u2fResponse is the signature
pkix::Input u2fSig;
input.SkipToEnd(u2fSig);
pkix::Reader sigInput(u2fSig);
rv = ReadToCryptoBuffer(sigInput, aSignatureBuf, u2fSig.GetLength());
if (NS_FAILED(rv)) {
return rv;
}
return NS_OK;
}