本文整理汇总了C++中Digest类的典型用法代码示例。如果您正苦于以下问题:C++ Digest类的具体用法?C++ Digest怎么用?C++ Digest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Digest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: SCOPE
TS::TS(const string &url, const Digest &digest, const string &useragent)
{
SCOPE(TS_REQ, req, TS_REQ_new());
TS_REQ_set_version(req.get(), 1);
TS_REQ_set_cert_req(req.get(), 1);
SCOPE(X509_ALGOR, algo, X509_ALGOR_new());
algo->algorithm = OBJ_nid2obj(Digest::toMethod(digest.uri()));
algo->parameter = ASN1_TYPE_new();
algo->parameter->type = V_ASN1_NULL;
SCOPE(TS_MSG_IMPRINT, msg_imprint, TS_MSG_IMPRINT_new());
TS_MSG_IMPRINT_set_algo(msg_imprint.get(), algo.get());
vector<unsigned char> digestdata = digest.result();
TS_MSG_IMPRINT_set_msg(msg_imprint.get(), digestdata.data(), int(digestdata.size()));
TS_REQ_set_msg_imprint(req.get(), msg_imprint.get());
#if 0
if(!policy.empty())
{
SCOPE(ASN1_OBJECT, obj, OBJ_txt2obj(policy.c_str(), 0));
TS_REQ_set_policy_id(req.get(), obj.get());
}
#endif
SCOPE(ASN1_INTEGER, nonce, ASN1_INTEGER_new());
nonce->length = 20;
nonce->data = (unsigned char*)OPENSSL_malloc(nonce->length);
nonce->data[0] = 0;
while(nonce->data[0] == 0) // Make sure that first byte is not 0x00
RAND_bytes(nonce->data, nonce->length);
TS_REQ_set_nonce(req.get(), nonce.get());
int len = i2d_TS_REQ(req.get(), 0);
vector<unsigned char> data(len, 0);
unsigned char *p = data.data();
i2d_TS_REQ(req.get(), &p);
string result = Connect(url, "POST", 0, useragent).exec({
{"Content-Type", "application/timestamp-query"},
{"Accept", "application/timestamp-reply"},
{"Connection", "Close"},
{"Cache-Control", "no-cache"}
}, data).content;
const unsigned char *p2 = (const unsigned char*)result.c_str();
SCOPE(TS_RESP, resp, d2i_TS_RESP(0, &p2, long(result.size())));
if(!resp)
THROW_OPENSSLEXCEPTION("Failed to parse TS response.");
SCOPE(TS_VERIFY_CTX, ctx, TS_VERIFY_CTX_new());
ctx->flags = TS_VFY_NONCE|TS_VFY_VERSION;
ctx->nonce = nonce.release();
if(TS_RESP_verify_response(ctx.get(), resp.get()) != 1)
THROW_OPENSSLEXCEPTION("Failed to verify TS response.");
d.reset(resp->token, function<void(PKCS7*)>(PKCS7_free));
resp->token = nullptr;
}
示例2: merkle_tree_create
zx_status_t merkle_tree_create(const void* data, size_t data_len, void* tree, size_t tree_len,
void* out, size_t out_len) {
zx_status_t rc;
Digest digest;
if ((rc = MerkleTree::Create(data, data_len, tree, tree_len, &digest)) != ZX_OK) {
return rc;
}
return digest.CopyTo(static_cast<uint8_t*>(out), out_len);
}
示例3: if
NS_IMETHODIMP
nsDataSignatureVerifier::VerifySignature(const char* aRSABuf,
uint32_t aRSABufLen,
const char* aPlaintext,
uint32_t aPlaintextLen,
int32_t* aErrorCode,
nsICertificatePrincipal** aPrincipal)
{
if (!aPlaintext || !aPrincipal || !aErrorCode) {
return NS_ERROR_INVALID_ARG;
}
*aErrorCode = VERIFY_ERROR_OTHER;
*aPrincipal = nullptr;
nsNSSShutDownPreventionLock locker;
Digest digest;
nsresult rv = digest.DigestBuf(SEC_OID_SHA1,
reinterpret_cast<const uint8_t*>(aPlaintext),
aPlaintextLen);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
SECItem buffer = {
siBuffer,
reinterpret_cast<uint8_t*>(const_cast<char*>(aRSABuf)),
aRSABufLen
};
VerifyCertificateContext context;
// XXX: pinArg is missing
rv = VerifyCMSDetachedSignatureIncludingCertificate(buffer, digest.get(),
VerifyCertificate,
&context, nullptr);
if (NS_SUCCEEDED(rv)) {
*aErrorCode = VERIFY_OK;
} else if (NS_ERROR_GET_MODULE(rv) == NS_ERROR_MODULE_SECURITY) {
if (rv == GetXPCOMFromNSSError(SEC_ERROR_UNKNOWN_ISSUER)) {
*aErrorCode = VERIFY_ERROR_UNKNOWN_ISSUER;
} else {
*aErrorCode = VERIFY_ERROR_OTHER;
}
rv = NS_OK;
}
if (rv == NS_OK) {
context.principal.forget(aPrincipal);
}
return rv;
}
示例4: digestToHex
std::string DigestEngine::digestToHex(const Digest& bytes)
{
static const char digits[] = "0123456789abcdef";
std::string result;
result.reserve(bytes.size()*2);
for (Digest::const_iterator it = bytes.begin(); it != bytes.end(); ++it)
{
unsigned char c = *it;
result += digits[(c >> 4) & 0xF];
result += digits[c & 0xF];
}
return result;
}
示例5: RootCABinNumber
// Perform a hash of the provided cert, then search in the RootHashes.inc data
// structure for a matching bin number.
int32_t
RootCABinNumber(const SECItem* cert)
{
Digest digest;
// Compute SHA256 hash of the certificate
nsresult rv = digest.DigestBuf(SEC_OID_SHA256, cert->data, cert->len);
if (NS_WARN_IF(NS_FAILED(rv))) {
return ROOT_CERTIFICATE_HASH_FAILURE;
}
// Compare against list of stored hashes
size_t idx;
MOZ_LOG(gPublicKeyPinningTelemetryLog, LogLevel::Debug,
("pkpinTelem: First bytes %02x %02x %02x %02x\n",
digest.get().data[0], digest.get().data[1], digest.get().data[2], digest.get().data[3]));
if (mozilla::BinarySearchIf(ROOT_TABLE, 0, ArrayLength(ROOT_TABLE),
BinaryHashSearchArrayComparator(static_cast<uint8_t*>(digest.get().data),
digest.get().len),
&idx)) {
MOZ_LOG(gPublicKeyPinningTelemetryLog, LogLevel::Debug,
("pkpinTelem: Telemetry index was %" PRIuSIZE ", bin is %d\n",
idx, ROOT_TABLE[idx].binNumber));
return (int32_t) ROOT_TABLE[idx].binNumber;
}
// Didn't match.
return ROOT_CERTIFICATE_UNKNOWN;
}
示例6: RootCABinNumber
// Perform a hash of the provided cert, then search in the RootHashes.inc data
// structure for a matching bin number.
int32_t
RootCABinNumber(const SECItem* cert)
{
Digest digest;
// Compute SHA256 hash of the certificate
nsresult rv = digest.DigestBuf(SEC_OID_SHA256, cert->data, cert->len);
if (NS_WARN_IF(NS_FAILED(rv))) {
return HASH_FAILURE;
}
// Compare against list of stored hashes
size_t idx;
PR_LOG(PublicKeyPinningTelemetryLog(), PR_LOG_DEBUG,
("pkpinTelem: First bytes %02hx %02hx %02hx %02hx\n",
digest.get().data[0], digest.get().data[1], digest.get().data[2], digest.get().data[3]));
if (mozilla::BinarySearchIf(ROOT_TABLE, 0, ArrayLength(ROOT_TABLE),
BinaryHashSearchArrayComparator(
reinterpret_cast<const uint8_t*>(digest.get().data), digest.get().len),
&idx)) {
PR_LOG(PublicKeyPinningTelemetryLog(), PR_LOG_DEBUG,
("pkpinTelem: Telemetry index was %lu, bin is %d\n",
idx, ROOT_TABLE[idx].binNumber));
return (int32_t) ROOT_TABLE[idx].binNumber;
}
// Didn't match.
return UNKNOWN_ROOT;
}
示例7: GetBase64HashSPKI
/**
Computes in the location specified by base64Out the SHA256 digest
of the DER Encoded subject Public Key Info for the given cert
*/
static nsresult
GetBase64HashSPKI(const CERTCertificate* cert, nsACString& hashSPKIDigest)
{
hashSPKIDigest.Truncate();
Digest digest;
nsresult rv = digest.DigestBuf(SEC_OID_SHA256, cert->derPublicKey.data,
cert->derPublicKey.len);
if (NS_FAILED(rv)) {
return rv;
}
return Base64Encode(nsDependentCSubstring(
reinterpret_cast<const char*>(digest.get().data),
digest.get().len),
hashSPKIDigest);
}
示例8: merkle_tree_create_final
zx_status_t merkle_tree_create_final(merkle_tree_t* mt, void* tree, void* out, size_t out_len) {
// Must have a wrapper object.
if (!mt) {
return ZX_ERR_INVALID_ARGS;
}
// Take possession of the wrapper object. That way, we'll clean up
// automatically.
fbl::unique_ptr<merkle_tree_t> mt_uniq(mt);
// Call the C++ function.
zx_status_t rc;
Digest digest;
if ((rc = mt_uniq->obj.CreateFinal(tree, &digest)) != ZX_OK) {
return rc;
}
return digest.CopyTo(static_cast<uint8_t*>(out), out_len);
}
示例9: notarize
Bool SignerReal::notarize( PublicKey pubkey, Signature signature, Digest hash, Monitor& monitor )
{
if (!check_interface(monitor)) return false;
eprovider::TheKey thepubkey = creator.getCreatureCurrentTheKey(pubkey);
Size hashsize;
RECOVER_CALL(hashsize = iface->getMaxHashSize(thepubkey, error));
Padder curpad = padder;
if (pubkey.getPadder(Monitor()))
{
curpad = pubkey.getPadder(monitor);
} else if (signature.getPadder(Monitor()))
{
curpad = signature.getPadder(monitor);
} else {
//TODO: find default padder
}
if (curpad.ok() && hashsize.bits()) hash = curpad.pad(hash, hashsize, monitor); if (!monitor) return Bool();
Data hashblock = hash.asData();
Image signimage = signature.encode(monitor);
Snapshot signblock = signimage.snapshot();
Bool result;
RECOVER_CALL( (result = iface->notarizeHash(session,hashblock.get(), hashblock.size(), signblock.get(), signblock.size(), signblock.encid(), thepubkey, error)) );
return result;
}
示例10: sign
Signature SignerReal::sign( PrivateKey privkey, Digest hash, Monitor& monitor )
{
if (!check_interface(monitor)) return Signature();
Parameters params = privkey.getAlgParams(acSign, Monitor());
if (params) setAlgParams(params,monitor);
Padder curpad = padder;
if (privkey.getPadder(Monitor()))
{
curpad = privkey.getPadder(monitor);
} else {
//TODO: find default padder
}
Error error;
if (random)
{
IRef<eprovider::ProviderInterface> randomer = creator.getCreatureCurrentInterface(random);
if (randomer) iface->setRandom(session, randomer.cast<eprovider::RandomGenerator>().get(), error);
}
eprovider::TheKey thekey = creator.getCreatureCurrentTheKey(privkey);
Size hashsize = iface->getMaxHashSize(thekey, error);
if (curpad.ok() && hashsize.bits()) hash = curpad.pad(hash, hashsize, monitor); if (!monitor) return Signature();
Data hashblock = hash.asData();
eprovider::Block binsign;
RECOVER_CALL( (binsign = iface->signHash(session, hashblock.get(), hashblock.size(), thekey, error)) );
Snapshot snapshot = creator.createSnapshot(binsign.get(), binsign.size(), binsign.encid(), iface->getKeyId(kcSignature));
return snapshot.reviveSignature(monitor);
}
示例11:
void Session::Impl::SetDigest(const Digest& auth) {
auto curl = curl_->handle;
if (curl) {
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_easy_setopt(curl, CURLOPT_USERPWD, auth.GetAuthString());
}
}
示例12: verify
void TS::verify(const Digest &digest)
{
if(!d)
THROW_OPENSSLEXCEPTION("Failed to verify TS response.");
vector<unsigned char> data = digest.result();
SCOPE(TS_VERIFY_CTX, ctx, TS_VERIFY_CTX_new());
ctx->flags = TS_VFY_IMPRINT|TS_VFY_VERSION|TS_VFY_SIGNATURE;
ctx->imprint = data.data();
ctx->imprint_len = (unsigned int)data.size();
ctx->store = X509_STORE_new();
X509CertStore::instance()->activate(cert().issuerName("C"));
for(const X509Cert &i: X509CertStore::instance()->certs())
X509_STORE_add_cert(ctx->store, i.handle());
OpenSSLException(); // Clear errors
SCOPE(X509_STORE_CTX, csc, X509_STORE_CTX_new());
if (!csc)
THROW_OPENSSLEXCEPTION("Failed to create X509_STORE_CTX");
if(!X509_STORE_CTX_init(csc.get(), ctx->store, 0, 0))
THROW_OPENSSLEXCEPTION("Failed to init X509_STORE_CTX");
X509_STORE_set_verify_cb_func(ctx->store, [](int ok, X509_STORE_CTX *ctx) -> int {
switch(X509_STORE_CTX_get_error(ctx))
{
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
case X509_V_ERR_CERT_UNTRUSTED:
{
const vector<X509Cert> &list = X509CertStore::instance()->certs();
if(find(list.begin(), list.end(), X509Cert(ctx->current_cert)) != list.end())
return 1;
return ok;
}
default: return ok;
}
});
int err = TS_RESP_verify_token(ctx.get(), d.get());
//Avoid CRYPTO_free
ctx->imprint = nullptr;
ctx->imprint_len = 0;
if(err != 1)
{
long err = ERR_get_error();
if(ERR_GET_LIB(err) == 47 && ERR_GET_REASON(err) == TS_R_CERTIFICATE_VERIFY_ERROR)
{
Exception e(EXCEPTION_PARAMS("Certificate status: unknown"));
e.setCode( Exception::CertificateUnknown );
throw e;
}
THROW_OPENSSLEXCEPTION("Failed to verify TS response.");
}
}
示例13: GetBase64SHA256SPKI
/**
Computes in the location specified by base64Out the SHA256 digest
of the DER Encoded subject Public Key Info for the given cert
*/
static SECStatus
GetBase64SHA256SPKI(const CERTCertificate* cert,
nsACString& aSha256SPKIDigest){
aSha256SPKIDigest.Truncate();
Digest digest;
nsresult rv = digest.DigestBuf(SEC_OID_SHA256, cert->derPublicKey.data,
cert->derPublicKey.len);
if (NS_WARN_IF(NS_FAILED(rv))) {
return SECFailure;
}
rv = Base64Encode(nsDependentCSubstring(
reinterpret_cast<const char*>(digest.get().data),
digest.get().len),
aSha256SPKIDigest);
if (NS_WARN_IF(NS_FAILED(rv))) {
return SECFailure;
}
return SECSuccess;
}
示例14: DEBUG
/**
* Adds signing certificate to the signature XML. The DER encoded X.509 certificate is added to
* Signature->KeyInfo->X509Data->X509Certificate. Certificate info is also added to
* Signature->Object->QualifyingProperties->SignedProperties->SignedSignatureProperties->SigningCertificate.
*
* @param cert certificate that is used for signing the signature XML.
*/
void SignatureBES::setSigningCertificate(const X509Cert& x509)
{
DEBUG("SignatureBES::setSigningCertificate()");
// Signature->KeyInfo->X509Data->X509Certificate
// BASE64 encoding of a DER-encoded X.509 certificate = PEM encoded.
X509DataType x509Data;
x509Data.x509Certificate().push_back(toBase64(x509));
KeyInfoType keyInfo;
keyInfo.x509Data().push_back(x509Data);
signature->keyInfo(keyInfo);
// Signature->Object->QualifyingProperties->SignedProperties->SignedSignatureProperties->SigningCertificate
// Calculate digest of the X.509 certificate.
Digest digest;
digest.update(x509);
CertIDListType signingCertificate;
signingCertificate.cert().push_back(CertIDType(
DigestAlgAndValueType(DigestMethodType(digest.uri()), toBase64(digest.result())),
X509IssuerSerialType(x509.issuerName(), x509.serial())));
getSignedSignatureProperties().signingCertificate(signingCertificate);
}
示例15: MOZ_ASSERT
// Called on the worker thread.
bool
BackgroundFileSaver::CheckCompletion()
{
nsresult rv;
MOZ_ASSERT(!mAsyncCopyContext,
"Should not be copying when checking completion conditions.");
bool failed = true;
{
MutexAutoLock lock(mLock);
if (mComplete) {
return true;
}
// If an error occurred, we don't need to do the checks in this code block,
// and the operation can be completed immediately with a failure code.
if (NS_SUCCEEDED(mStatus)) {
failed = false;
// We did not incur in an error, so we must determine if we can stop now.
// If the Finish method has not been called, we can just continue now.
if (!mFinishRequested) {
return false;
}
// We can only stop when all the operations requested by the control
// thread have been processed. First, we check whether we have processed
// the first SetTarget call, if any. Then, we check whether we have
// processed any rename requested by subsequent SetTarget calls.
if ((mInitialTarget && !mActualTarget) ||
(mRenamedTarget && mRenamedTarget != mActualTarget)) {
return false;
}
// If we still have data to write to the output file, allow the copy
// operation to resume. The Available getter may return an error if one
// of the pipe's streams has been already closed.
uint64_t available;
rv = mPipeInputStream->Available(&available);
if (NS_SUCCEEDED(rv) && available != 0) {
return false;
}
}
mComplete = true;
}
// Ensure we notify completion now that the operation finished.
// Do a best-effort attempt to remove the file if required.
if (failed && mActualTarget && !mActualTargetKeepPartial) {
(void)mActualTarget->Remove(false);
}
// Finish computing the hash
if (!failed && mDigestContext) {
nsNSSShutDownPreventionLock lock;
if (!isAlreadyShutDown()) {
Digest d;
rv = d.End(SEC_OID_SHA256, mDigestContext);
if (NS_SUCCEEDED(rv)) {
MutexAutoLock lock(mLock);
mSha256 = nsDependentCSubstring(char_ptr_cast(d.get().data),
d.get().len);
}
}
}
// Compute the signature of the binary. ExtractSignatureInfo doesn't do
// anything on non-Windows platforms except return an empty nsIArray.
if (!failed && mActualTarget) {
nsString filePath;
mActualTarget->GetTarget(filePath);
nsresult rv = ExtractSignatureInfo(filePath);
if (NS_FAILED(rv)) {
LOG(("Unable to extract signature information [this = %p].", this));
} else {
LOG(("Signature extraction success! [this = %p]", this));
}
}
// Post an event to notify that the operation completed.
if (NS_FAILED(mControlThread->Dispatch(NewRunnableMethod(this,
&BackgroundFileSaver::NotifySaveComplete),
NS_DISPATCH_NORMAL))) {
NS_WARNING("Unable to post completion event to the control thread.");
}
return true;
}