Esempio n. 1
0
		void rsa_key::verify(const void* _sign, size_t sign_len, const void* buf, size_t buf_len, int type) const
		{
#if OPENSSL_VERSION_NUMBER >= 0x01000000
			throw_error_if_not(RSA_verify(type, static_cast<const unsigned char*>(buf), static_cast<unsigned int>(buf_len), static_cast<const unsigned char*>(_sign), static_cast<unsigned int>(sign_len), ptr().get()) != 0);
#else
			throw_error_if_not(RSA_verify(type, static_cast<unsigned char*>(const_cast<void*>(buf)), static_cast<unsigned int>(buf_len), static_cast<unsigned char*>(const_cast<void*>(_sign)), static_cast<unsigned int>(sign_len), ptr().get()) != 0);
#endif
		}
Esempio n. 2
0
int
key_verify(struct key *k, u_char *msg, int mlen, u_char *sig, int slen)
{
	switch (k->type) {

	case KEY_RSA:
		if (RSA_verify(NID_sha1, msg, mlen,
		    sig, slen, (RSA *)k->data) <= 0) {
			fprintf(stderr, "RSA verification failed\n");
			return (-1);
		}
		break;

	case KEY_DSA:
		if (DSA_verify(NID_sha1, msg, mlen,
		    sig, slen, (DSA *)k->data) <= 0) {
			fprintf(stderr, "DSA verification failed\n");
			return (-1);
		}
		break;

	default:
		fprintf(stderr, "Unknown key type: %d\n", k->type);
		return (-1);
	}
	return (slen);
}
Esempio n. 3
0
bool UpdateManager::verifyVersionData(const string& data, const ByteVector& signature) {
	int res = -1;

	// Make SHA hash
	SHA_CTX sha_ctx = { 0 };
	uint8_t digest[SHA_DIGEST_LENGTH];

	res = SHA1_Init(&sha_ctx);
	if(res != 1)
		return false;
	res = SHA1_Update(&sha_ctx, data.c_str(), data.size());
	if(res != 1)
		return false;
	res = SHA1_Final(digest, &sha_ctx);
	if(res != 1)
		return false;

	// Extract Key
	const uint8_t* key = UpdateManager::publicKey;
	RSA* rsa = d2i_RSAPublicKey(NULL, &key, sizeof(UpdateManager::publicKey));
	if(rsa) {
		res = RSA_verify(NID_sha1, digest, sizeof(digest), &signature[0], signature.size(), rsa);

		RSA_free(rsa);
		rsa = NULL;
	} else return false;

	return (res == 1); 
}
Esempio n. 4
0
bool SecurityHelper::verifyDataObject(DataObjectRef& dObj, CertificateRef& cert) const
{
	RSA *key;
	
	// Cannot verify without signature
	if (!dObj->getSignature()) {
		HAGGLE_ERR("No signature in data object, cannot verify\n");
		return false;
	}	
	writeErrors("(not this): ");
	
	key = cert->getPubKey();

	if (RSA_verify(NID_sha1, dObj->getId(), sizeof(DataObjectId_t), 
		       const_cast<unsigned char *>(dObj->getSignature()), dObj->getSignatureLength(), key) != 1) {
		char *raw;
		size_t len;
		writeErrors("");
		dObj->getRawMetadataAlloc((unsigned char **)&raw, &len);
		if (raw) {
			HAGGLE_DBG("Signature is invalid:\n%s\n", raw);
			free(raw);
		}
		dObj->setSignatureStatus(DataObject::SIGNATURE_INVALID);

		return false;
	}
	
	HAGGLE_DBG("Signature is valid\n");
	dObj->setSignatureStatus(DataObject::SIGNATURE_VALID);

	return true;
}
Esempio n. 5
0
 bool verify_data( const char* key, uint32_t key_size, uint32_t pe, const sha1& digest, const char* sig )
 {
     RSA* pub = get_pub( key,key_size,pe);
     auto v = RSA_verify( NID_sha1, (const uint8_t*)digest.data(), 20, (uint8_t*)sig, key_size, pub );
     RSA_free(pub);
     return 0 != v;
 }
Esempio n. 6
0
/*
 * Perform the verification step [RFC3447 sec 8.2.2].
 */
static int RSA_verify_signature(const struct public_key *key,
				const struct public_key_signature *sig)
{
	size_t tsize;
	int ret;

	/* Variables as per RFC3447 sec 8.2.2 */
	const u8 *H = sig->digest;
	u8 *EM = NULL;
	MPI m = NULL;
	size_t k;

	kenter("");

	if (!RSA_ASN1_templates[sig->pkey_hash_algo].data)
		return -ENOTSUPP;

	/* (1) Check the signature size against the public key modulus size */
	k = mpi_get_nbits(key->rsa.n);
	tsize = mpi_get_nbits(sig->rsa.s);

	/* According to RFC 4880 sec 3.2, length of MPI is computed starting
	 * from most significant bit.  So the RFC 3447 sec 8.2.2 size check
	 * must be relaxed to conform with shorter signatures - so we fail here
	 * only if signature length is longer than modulus size.
	 */
	pr_devel("step 1: k=%zu size(S)=%zu\n", k, tsize);
	if (k < tsize) {
		ret = -EBADMSG;
		goto error;
	}

	/* Round up and convert to octets */
	k = (k + 7) / 8;

	/* (2b) Apply the RSAVP1 verification primitive to the public key */
	ret = RSAVP1(key, sig->rsa.s, &m);
	if (ret < 0)
		goto error;

	/* (2c) Convert the message representative (m) to an encoded message
	 *      (EM) of length k octets.
	 *
	 *      NOTE!  The leading zero byte is suppressed by MPI, so we pass a
	 *      pointer to the _preceding_ byte to RSA_verify()!
	 */
	ret = RSA_I2OSP(m, k, &EM);
	if (ret < 0)
		goto error;

	ret = RSA_verify(H, EM - 1, k, sig->digest_size,
			 RSA_ASN1_templates[sig->pkey_hash_algo].data,
			 RSA_ASN1_templates[sig->pkey_hash_algo].size);

error:
	kfree(EM);
	mpi_free(m);
	kleave(" = %d", ret);
	return ret;
}
Esempio n. 7
0
int
ccnet_rpc_verify_message (const char *message,
                          const char *sig_base64,
                          const char *peer_id,
                          GError **error)
{
    unsigned char *sig;
    gsize sig_len;
    CcnetPeer *peer;

    sig = g_base64_decode (sig_base64, &sig_len);

    peer = ccnet_peer_manager_get_peer (session->peer_mgr, peer_id);
    if (!peer) {
        g_warning ("Cannot find peer %s.\n", peer_id);
        return -1;
    }

    if (!RSA_verify (NID_sha1, (const unsigned char *)message, strlen(message),
                     sig, (guint)sig_len, peer->pubkey)) {
        g_object_unref (peer);
        return -1;
    }

    g_object_unref (peer);
    return 0;
}
Esempio n. 8
0
static int
rsa_verify_cb(int fd, void *ud)
{
	struct rsa_verify_cbdata *cbdata = ud;
	char *sha256;
	char errbuf[1024];
	RSA *rsa = NULL;
	int ret;

	sha256 = pkg_checksum_fd(fd, PKG_HASH_TYPE_SHA256_HEX);
	if (sha256 == NULL)
		return (EPKG_FATAL);

	rsa = _load_rsa_public_key_buf(cbdata->key, cbdata->keylen);
	if (rsa == NULL) {
		free(sha256);
		return(EPKG_FATAL);
	}

	ret = RSA_verify(NID_sha1, sha256,
	    pkg_checksum_type_size(PKG_HASH_TYPE_SHA256_HEX), cbdata->sig,
	    cbdata->siglen, rsa);
	free(sha256);
	if (ret == 0) {
		pkg_emit_error("%s: %s", cbdata->key,
		    ERR_error_string(ERR_get_error(), errbuf));
		RSA_free(rsa);
		return (EPKG_FATAL);
	}

	RSA_free(rsa);

	return (EPKG_OK);
}
Esempio n. 9
0
/**
 * Check memory using specified rsa key and signature
 *
 * arguments:
 * (rsa_pubkey, rsa_signature, string)
 *
 * returns:
 * true - if string match rsa signature
 * false - otherwise
 */
static gint
lua_rsa_verify_memory (lua_State *L)
{
	RSA *rsa;
	rspamd_fstring_t *signature;
	const gchar *data;
	gchar *data_sig;
	gint ret;

	rsa = lua_check_rsa_pubkey (L, 1);
	signature = lua_check_rsa_sign (L, 2);
	data = luaL_checkstring (L, 3);

	if (rsa != NULL && signature != NULL && data != NULL) {
		data_sig = g_compute_checksum_for_string (G_CHECKSUM_SHA256, data, -1);
		ret = RSA_verify (NID_sha1, data_sig, strlen (data_sig),
				signature->str, signature->len, rsa);
		if (ret == 0) {
			msg_info ("cannot check rsa signature for data: %s",
				ERR_error_string (ERR_get_error (), NULL));
			lua_pushboolean (L, FALSE);
		}
		else {
			lua_pushboolean (L, TRUE);
		}
		g_free (data_sig);
	}
	else {
		lua_pushnil (L);
	}

	return 1;
}
Esempio n. 10
0
int
pkg_repo_verify(const char *path, unsigned char *sig, unsigned int sig_len)
{
	char sha256[SHA256_DIGEST_LENGTH *2 +1];
	char errbuf[1024];
	RSA *rsa = NULL;

	sha256_file(path, sha256);

	SSL_load_error_strings();
	OpenSSL_add_all_algorithms();
	OpenSSL_add_all_ciphers();

	rsa = load_rsa_public_key(pkg_config("PUBKEY"));
	if (rsa == NULL)
		return(EPKG_FATAL);

	if (RSA_verify(NID_sha1, sha256, sizeof(sha256), sig, sig_len, rsa) == 0) {
		pkg_emit_error("%s: %s", pkg_config("PUBKEY"),
					   ERR_error_string(ERR_get_error(), errbuf));
		return (EPKG_FATAL);
	}

	RSA_free(rsa);
	ERR_free_strings();

	return (EPKG_OK);
}
Esempio n. 11
0
static PyObject *verify(RSAObject *self, PyObject *args)
{
    Py_buffer digest, signature;
    int result = 0;
    PyObject *result_obj = NULL;

#if PY_MAJOR_VERSION >= 3
    if (!PyArg_ParseTuple(args, "y*y*:verify", &digest, &signature))
        return NULL;
#else
    if (!PyArg_ParseTuple(args, "s*s*:verify", &digest, &signature))
        return NULL;
#endif

    if (digest.len != SHA_DIGEST_LENGTH)
    {
        PyErr_Format(PyExc_ValueError, "digest should be %i bytes",
                     SHA_DIGEST_LENGTH);
        goto cleanup;
    }

    result = RSA_verify(NID_sha1, digest.buf, digest.len,
                        signature.buf, signature.len, self->rsa);

    result_obj = PyBool_FromLong(result);

cleanup:
    PyBuffer_Release(&digest);
    PyBuffer_Release(&signature);

    return result_obj;
}
Esempio n. 12
0
int RSAVerifyBinary_f(const uint8_t* key_blob,
                      const RSAPublicKey* key,
                      const uint8_t* buf,
                      int len,
                      const uint8_t* sig,
                      int algorithm) {
  RSAPublicKey* verification_key = NULL;
  uint8_t* digest = NULL;
  int key_size;
  int sig_size;
  int success;

  if (algorithm >= kNumAlgorithms)
    return 0;  /* Invalid algorithm. */
  key_size = RSAProcessedKeySize(algorithm);
  sig_size = siglen_map[algorithm] * sizeof(uint32_t);

  if (key_blob && !key)
    verification_key = RSAPublicKeyFromBuf(key_blob, key_size);
  else if (!key_blob && key)
    verification_key = (RSAPublicKey*) key;  /* Supress const warning. */
  else
    return 0; /* Both can't be NULL or non-NULL. */

  digest = DigestBuf(buf, len, algorithm);
  success = RSA_verify(verification_key, sig, sig_size, algorithm, digest);

  Free(digest);
  if (!key)
    RSAPublicKeyFree(verification_key);  /* Only free if we allocated it. */
  return success;
}
Esempio n. 13
0
static int __ast_check_signature_bin(struct ast_key *key, const char *msg, int msglen, const unsigned char *dsig)
{
	unsigned char digest[20];
	int res;

	if (key->ktype != AST_KEY_PUBLIC) {
		/* Okay, so of course you really *can* but for our purposes
		   we're going to say you can't */
		ast_log(LOG_WARNING, "Cannot check message signature with a private key\n");
		return -1;
	}

	/* Calculate digest of message */
	SHA1((unsigned char *)msg, msglen, digest);

	/* Verify signature */
	res = RSA_verify(NID_sha1, digest, sizeof(digest), (unsigned char *)dsig, 128, key->rsa);
	
	if (!res) {
		ast_log(LOG_DEBUG, "Key failed verification: %s\n", key->name);
		return -1;
	}
	/* Pass */
	return 0;
}
Esempio n. 14
0
static bool
rsa_verifydigest(dnssec_key* key, u8* digest, u32 digest_len, u8* signature, u32 signature_len)
{
    zassert(signature_len <= DNSSEC_MAXIMUM_KEY_SIZE_BYTES);

    int err = RSA_verify(key->nid, digest, digest_len, signature, signature_len, key->key.rsa);

    if(err == 0)
    {
        unsigned long ssl_err;

        while((ssl_err = ERR_get_error()) != 0)
        {
            char buffer[128];
            ERR_error_string_n(ssl_err, buffer, sizeof (buffer));

            log_debug("digest verification returned an ssl error %08x %s", ssl_err, buffer);
        }

        ERR_clear_error();

        return FALSE;
    }

    return TRUE;
}
/**
 * Verify the RSA signature on the SignedBlob using the given public key.
 * TODO: Move this general verification code to a more central location.
 * @param signature The Sha256WithRsaSignature.
 * @param signedBlob the SignedBlob with the signed portion to verify.
 * @param publicKeyDer The DER-encoded public key used to verify the signature.
 * @return true if the signature verifies, false if not.
 */
static bool
verifySha256WithRsaSignature
  (const Sha256WithRsaSignature* signature, const SignedBlob& signedBlob,
   const Blob& publicKeyDer)
{
  // Set signedPortionDigest to the digest of the signed portion of the wire encoding.
  uint8_t signedPortionDigest[SHA256_DIGEST_LENGTH];
  // wireEncode returns the cached encoding if available.
  ndn_digestSha256
    (signedBlob.signedBuf(), signedBlob.signedSize(), signedPortionDigest);

  // Verify the signedPortionDigest.
  // Use a temporary pointer since d2i updates it.
  const uint8_t *derPointer = publicKeyDer.buf();
  RSA *rsaPublicKey = d2i_RSA_PUBKEY(NULL, &derPointer, publicKeyDer.size());
  if (!rsaPublicKey)
    throw UnrecognizedKeyFormatException("Error decoding public key in d2i_RSAPublicKey");
  int success = RSA_verify
    (NID_sha256, signedPortionDigest, sizeof(signedPortionDigest), (uint8_t *)signature->getSignature().buf(),
     signature->getSignature().size(), rsaPublicKey);
  // Free the public key before checking for success.
  RSA_free(rsaPublicKey);

  // RSA_verify returns 1 for a valid signature.
  return (success == 1);
}
Esempio n. 16
0
static bool
rsa_verify_hash(struct xbps_repo *repo, xbps_data_t pubkey,
		unsigned char *sig, unsigned int siglen,
		unsigned char *sha256)
{
	BIO *bio;
	RSA *rsa;
	int rv;

	ERR_load_crypto_strings();
	SSL_load_error_strings();

	bio = BIO_new_mem_buf(__UNCONST(xbps_data_data_nocopy(pubkey)),
			xbps_data_size(pubkey));
	assert(bio);

	rsa = PEM_read_bio_RSA_PUBKEY(bio, NULL, NULL, NULL);
	if (rsa == NULL) {
		xbps_dbg_printf(repo->xhp, "`%s' error reading public key: %s\n",
		    repo->uri, ERR_error_string(ERR_get_error(), NULL));
		return false;
	}

	rv = RSA_verify(NID_sha1, sha256, SHA256_DIGEST_LENGTH, sig, siglen, rsa);
	RSA_free(rsa);
	BIO_free(bio);
	ERR_free_strings();

	return rv ? true : false;
}
static isc_result_t
opensslrsa_verify(dst_context_t *dctx, const isc_region_t *sig) {
	dst_key_t *key = dctx->key;
	RSA *rsa = key->opaque;
	/* note: ISC_SHA1_DIGESTLENGTH > ISC_MD5_DIGESTLENGTH */
	unsigned char digest[ISC_SHA1_DIGESTLENGTH];
	int status = 0;
	int type;
	unsigned int digestlen;

	REQUIRE(dctx->key->key_alg == DST_ALG_RSAMD5 ||
		dctx->key->key_alg == DST_ALG_RSASHA1);

	if (dctx->key->key_alg == DST_ALG_RSAMD5) {
		isc_md5_t *md5ctx = dctx->opaque;
		isc_md5_final(md5ctx, digest);
		type = NID_md5;
		digestlen = ISC_MD5_DIGESTLENGTH;
	} else {
		isc_sha1_t *sha1ctx = dctx->opaque;
		isc_sha1_final(sha1ctx, digest);
		type = NID_sha1;
		digestlen = ISC_SHA1_DIGESTLENGTH;
	}

	if (sig->length < (unsigned int) RSA_size(rsa))
		return (DST_R_VERIFYFAILURE);

	status = RSA_verify(type, digest, digestlen, sig->base,
			    RSA_size(rsa), rsa);
	if (status == 0)
		return (dst__openssl_toresult(DST_R_VERIFYFAILURE));

	return (ISC_R_SUCCESS);
}
Esempio n. 18
0
static int
rsa_verify_cb(int fd, void *ud)
{
	struct rsa_verify_cbdata *cbdata = ud;
	char sha256[SHA256_DIGEST_LENGTH *2 +1];
	char errbuf[1024];
	RSA *rsa = NULL;
	int ret;

	if (sha256_fd(fd, sha256) != EPKG_OK)
		return (EPKG_FATAL);

	rsa = _load_rsa_public_key_buf(cbdata->key, cbdata->keylen);
	if (rsa == NULL)
		return(EPKG_FATAL);

	ret = RSA_verify(NID_sha1, sha256, sizeof(sha256), cbdata->sig,
			cbdata->siglen, rsa);
	if (ret == 0) {
		pkg_emit_error("%s: %s", cbdata->key,
				ERR_error_string(ERR_get_error(), errbuf));
		RSA_free(rsa);
		return (EPKG_FATAL);
	}

	RSA_free(rsa);

	return (EPKG_OK);
}
Esempio n. 19
0
		bool VerifyRSASignature(std::string pubKey, std::string signature, void* data, size_t dataSize)
		{
			BIO* pubKeyBuff = BIO_new_mem_buf((void*)pubKey.c_str(), pubKey.length());
			if (!pubKeyBuff)
				return false;

			RSA* rsa = PEM_read_bio_RSA_PUBKEY(pubKeyBuff, 0, 0, 0);
			if (!rsa)
				return false;

			unsigned char hash[SHA256_DIGEST_LENGTH];
			SHA256_CTX sha;
			SHA256_Init(&sha);
			SHA256_Update(&sha, data, dataSize);
			SHA256_Final(hash, &sha);

			size_t length = 0;
			if (Utils::String::Base64DecodeBinary((char*)signature.c_str(), NULL, &length) != 1 || length == 0)
				return false;

			unsigned char* sigBuf = (unsigned char*)malloc(length);
			if (Utils::String::Base64DecodeBinary((char*)signature.c_str(), sigBuf, &length) != 0)
				return false;

			int retVal = RSA_verify(NID_sha256, (unsigned char*)hash, SHA256_DIGEST_LENGTH, sigBuf, length, rsa);
			free(sigBuf);
			RSA_free(rsa);
			BIO_free_all(pubKeyBuff);

			return retVal == 1;
		}
Esempio n. 20
0
SEXP PKI_verify_RSA(SEXP what, SEXP sMD, SEXP sKey, SEXP sig) {
    int md = asInteger(sMD);
    EVP_PKEY *key;
    RSA *rsa;
    if (md != PKI_MD5 && md != PKI_SHA1)
	Rf_error("unsupported hash type");
    if (TYPEOF(what) != RAWSXP ||
	(md == PKI_MD5 && LENGTH(what) != MD5_DIGEST_LENGTH) ||
	(md == PKI_SHA1 && LENGTH(what) != SHA_DIGEST_LENGTH))
	Rf_error("invalid hash");
    if (!inherits(sKey, "public.key"))
	Rf_error("key must be RSA public key");
    key = (EVP_PKEY*) R_ExternalPtrAddr(sKey);
    if (!key)
	Rf_error("NULL key");
    if (EVP_PKEY_type(key->type) != EVP_PKEY_RSA)
	Rf_error("key must be RSA public key");
    rsa = EVP_PKEY_get1_RSA(key);
    if (!rsa)
	Rf_error("%s", ERR_error_string(ERR_get_error(), NULL));
    return
	ScalarLogical( /* FIXME: sig is not const in RSA_verify - that is odd so in theory in may modify sig ... */
		      (RSA_verify((md == PKI_MD5) ? NID_md5 : NID_sha1,
				  (const unsigned char*) RAW(what), LENGTH(what),
				  (unsigned char *) RAW(sig), LENGTH(sig), rsa) == 1)
		      ? TRUE : FALSE);
}
Esempio n. 21
0
static int verify_table(const uint8_t *signature, size_t signature_size,
        const char *table, uint32_t table_length)
{
    RSA *key;
    uint8_t hash_buf[SHA256_DIGEST_LENGTH];
    int retval = -1;

    // Hash the table
    SHA256((uint8_t*)table, table_length, hash_buf);

    // Now get the public key from the keyfile
    key = load_key(VERITY_TABLE_RSA_KEY);
    if (!key) {
        LERROR << "Couldn't load verity keys";
        goto out;
    }

    // verify the result
    if (!RSA_verify(NID_sha256, hash_buf, sizeof(hash_buf), signature,
                    signature_size, key)) {
        LERROR << "Couldn't verify table";
        goto out;
    }

    retval = 0;

out:
    RSA_free(key);
    return retval;
}
Esempio n. 22
0
int rsautl_verify(const char *pubKey, const char *inFile, const char *inSig)
{
	int ret = SourceSec_PubKeyNotFound;

	FILE *fpPubKey = fopen(pubKey, "rt");
	if(!fpPubKey)
		return ret;

	// Set file as public key source (must be in PEM format)
	RSA *rsa_pub = PEM_read_RSA_PUBKEY(fpPubKey, NULL, NULL, NULL);

	// Try to open signature file
	FILE *fpSigFile = fopen(inSig, "rb");
	if(!fpSigFile)
	{
		fclose(fpPubKey);
		return SourceSec_SigNotFound;
	}

	// Calculate hash of input file
	unsigned char hash[SHA256_DIGEST_LENGTH];
	calc_sha256(inFile, hash);

	// Get size of signature file
	fseek(fpSigFile, 0L, SEEK_END);
	size_t lenSig = ftell(fpSigFile);
	fseek(fpSigFile, 0L, SEEK_SET);

	// Signature size is suspiciously high, cancel process
	if(lenSig > 1024)
	{
		fclose(fpPubKey);
		fclose(fpSigFile);
		return SourceSec_SigTooBig;
	}

	// Read content into memory
	unsigned char *signature = (unsigned char*)malloc(lenSig);
	size_t rv = fread(signature, sizeof(unsigned char), lenSig, fpSigFile);

	// Check if full content was loaded
	if(rv != lenSig)
	{
		fclose(fpPubKey);
		fclose(fpSigFile);
		return SourceSec_SigIncomplete;
	}

	// Verify signature integrity
	ret = RSA_verify(NID_sha256, hash, SHA256_DIGEST_LENGTH, 
		(const unsigned char*)signature, lenSig, rsa_pub);

	// Free resources
	fclose(fpPubKey);
	fclose(fpSigFile);
	free(signature);

	return ret;
}
Esempio n. 23
0
bool ServerCertificate::verify( const QByteArray& data, const QByteArray& signature ) const
{
    if ( !isValid() )
        return false;
    QByteArray hash = QCryptographicHash::hash( data, QCryptographicHash::Sha1 );
    int verified = RSA_verify(NID_sha1, (const unsigned char*) hash.constData(), hash.length(), (unsigned char*)signature.constData(), signature.length(), m_publicKey);
    return verified;
}
Esempio n. 24
0
static void
bench_openssl_rsa_verify (void *p)
{
  const struct openssl_rsa_ctx *ctx = p;
  if (! RSA_verify (NID_sha1, ctx->digest, SHA1_DIGEST_SIZE,
		    ctx->ref, ctx->siglen, ctx->key))
    die ("OpenSSL RSA_verify failed.\n");    
}
/*
ToDo: problems with RSA_PKCS1_OAEP_PADDING -> find solution
*/
OpcUa_StatusCode OpcUa_P_OpenSSL_RSA_Public_Verify(
    OpcUa_CryptoProvider* a_pProvider,
    OpcUa_ByteString      a_data,
    OpcUa_Key*            a_publicKey,
    OpcUa_Int16           a_padding,
    OpcUa_ByteString*     a_pSignature)
{
    EVP_PKEY*       pPublicKey      = OpcUa_Null;
    OpcUa_Int32     keySize         = 0;
    const unsigned char *pData;

    OpcUa_InitializeStatus(OpcUa_Module_P_OpenSSL, "RSA_Public_Verify");

    OpcUa_ReferenceParameter(a_pProvider);
    OpcUa_ReferenceParameter(a_padding);

    OpcUa_ReturnErrorIfArgumentNull(a_data.Data);
    OpcUa_ReturnErrorIfArgumentNull(a_publicKey);
    OpcUa_ReturnErrorIfArgumentNull(a_publicKey->Key.Data);
    OpcUa_ReturnErrorIfArgumentNull(a_pSignature);

    if(a_publicKey->Type != OpcUa_Crypto_KeyType_Rsa_Public)
    {
        OpcUa_GotoErrorWithStatus(OpcUa_BadInvalidArgument);
    }

    pData = a_publicKey->Key.Data;
    pPublicKey = d2i_PublicKey(EVP_PKEY_RSA,OpcUa_Null, &pData, a_publicKey->Key.Length);

    if(pPublicKey == OpcUa_Null)
    {
        OpcUa_GotoErrorWithStatus(OpcUa_BadInvalidArgument);
    }

    keySize = RSA_size(pPublicKey->pkey.rsa);

    if((a_pSignature->Length%keySize) != 0)
    {
        OpcUa_GotoErrorWithStatus(OpcUa_Bad);
    }

    if (RSA_verify(NID_sha1, a_data.Data, a_data.Length, a_pSignature->Data, a_pSignature->Length, pPublicKey->pkey.rsa) != 1)
    {
        OpcUa_GotoErrorWithStatus(OpcUa_Bad);
    }

    EVP_PKEY_free(pPublicKey);

OpcUa_ReturnStatusCode;
OpcUa_BeginErrorHandling;

    if (pPublicKey != OpcUa_Null)
    {
        EVP_PKEY_free(pPublicKey);
    }

OpcUa_FinishErrorHandling;
}
Esempio n. 26
0
/***************************************************************************** 
    Function      : Verify Digital Signature(RSA) <Binary>
    Return        : int
	************************************************ Yuji Yamawaki 02.02.07 *****/
int
openSOAPSecVerifyRSASignBin
(int                  iType,          /* (i)  Hash Type(OPENSOAP_HA_*) */
 unsigned char*       szIn,           /* (i)  Signature */
 unsigned long        ulInSize,       /* (i)  Signature Size */
 const unsigned char* szData,         /* (i)  Original Data */
 unsigned long        ulDataSize,     /* (i)  Original Data Size */
 FILE*                fpPubKey)       /* (i)  RSA Public Key File Stream */
{
    RSA*  pRsa = NULL;
    unsigned char* szHash = NULL;
    unsigned long  ulLenHash;
    int            nRet = OPENSOAP_NO_ERROR;
    int            iRes;
    fpos_t         fposKey;
    /* Check Arguments */
    if (szIn == NULL || ulInSize == 0 || szData == NULL || ulDataSize == 0 ||
        fpPubKey == NULL) {
        return OPENSOAP_PARAMETER_BADVALUE;
    }
    /* Backup Stream's Position */
    if (fgetpos(fpPubKey, &fposKey) != 0) {
        nRet = OPENSOAP_IO_READ_ERROR;
        goto FuncEnd;
    }
    /* Hash Original Data */
    nRet = openSOAPSecMakeHash(iType, szData, ulDataSize,
                               &ulLenHash, &szHash);
    if (OPENSOAP_FAILED(nRet)) {
        goto FuncEnd;
    }
    /* Generate RSA from Public key */
    if (PEM_read_RSAPublicKey(fpPubKey, &pRsa, NULL, NULL) == NULL) {
        nRet = OPENSOAP_SEC_SIGNVERIFY_ERROR;
        goto FuncEnd;
    }
    /* Recover File Position */
    if (fsetpos(fpPubKey, &fposKey) != 0) {
        nRet = OPENSOAP_IO_READ_ERROR;
        goto FuncEnd;
    }
    /* Verify Signature */
    iRes = RSA_verify(convType(iType),
                      szHash,
                      ulLenHash,
                      szIn,
                      (int)ulInSize,
                      pRsa);
    if (iRes != 1) {
        nRet = OPENSOAP_SEC_SIGNVERIFY_ERROR;
    }
 FuncEnd:
    if (szHash != NULL)
        free(szHash);
    /* Terminate */
    RSA_free(pRsa);
    return nRet;
}
Esempio n. 27
0
bool InstallChecker::verifyPackage( const QString &filePath, bool )
{
	QProcess proc;
	proc.start( "hdiutil", QStringList() << "verify" << filePath );
	proc.waitForFinished();
	if( proc.exitCode() )
		return false;

	QString path = mountPackage( filePath );
	if( path.isEmpty() )
		return false;

	xar_t xar = xar_open( path.toUtf8().constData(), 0 );
	if( !xar )
		return false;

	QSslCertificate cert;
	xar_signature_t sig = xar_signature_first( xar );
	int32_t count = xar_signature_get_x509certificate_count( sig );
	for( int32_t i = 0; i < count; ++i )
	{
		uint32_t size = 0;
		const uint8_t *data = 0;
		if( xar_signature_get_x509certificate_data( sig, i, &data, &size ) )
			continue;
		QSslCertificate c( QByteArray( (const char*)data, size ), QSsl::Der );
#if QT_VERSION >= 0x050000
		QString cn = c.subjectInfo( QSslCertificate::CommonName ).value(0);
#else
		QString cn = c.subjectInfo( QSslCertificate::CommonName );
#endif
		if( cn == "Estonian Informatics Centre" ||
			cn == "Developer ID Installer: Riigi Infosüsteemi Amet" )
			cert = c;
	}

	if( cert.isNull() )
	{
		xar_close( xar );
		return false;
	}

	uint8_t *data = 0, *signature = 0;
	uint32_t dataSize = 0, signatureSize = 0;
	off_t offset = 0;
	if( xar_signature_copy_signed_data( sig, &data, &dataSize, &signature, &signatureSize, &offset ) )
	{
		xar_close( xar );
		return false;
	}

	int result = RSA_verify( NID_sha1, data, dataSize, signature, signatureSize, (RSA*)cert.publicKey().handle() );
	xar_close( xar );
	free( data );
	free( signature );

	return result;
}
/**
  Verifies the RSA-SSA signature with EMSA-PKCS1-v1_5 encoding scheme defined in
  RSA PKCS#1.

  If RsaContext is NULL, then return FALSE.
  If MessageHash is NULL, then return FALSE.
  If Signature is NULL, then return FALSE.
  If HashSize is not equal to the size of MD5, SHA-1 or SHA-256 digest, then return FALSE.

  @param[in]  RsaContext   Pointer to RSA context for signature verification.
  @param[in]  MessageHash  Pointer to octet message hash to be checked.
  @param[in]  HashSize     Size of the message hash in bytes.
  @param[in]  Signature    Pointer to RSA PKCS1-v1_5 signature to be verified.
  @param[in]  SigSize      Size of signature in bytes.

  @retval  TRUE   Valid signature encoded in PKCS1-v1_5.
  @retval  FALSE  Invalid signature or invalid RSA context.

**/
BOOLEAN
EFIAPI
RsaPkcs1Verify (
  IN  VOID         *RsaContext,
  IN  CONST UINT8  *MessageHash,
  IN  UINTN        HashSize,
  IN  CONST UINT8  *Signature,
  IN  UINTN        SigSize
  )
{
  INT32    DigestType;
  UINT8    *SigBuf;

  //
  // Check input parameters.
  //
  if (RsaContext == NULL || MessageHash == NULL || Signature == NULL) {
    return FALSE;
  }

  if (SigSize > INT_MAX || SigSize == 0) {
    return FALSE;
  }

  //
  // Determine the message digest algorithm according to digest size.
  //   Only MD5, SHA-1 or SHA-256 algorithm is supported.
  //
  switch (HashSize) {
  case MD5_DIGEST_SIZE:
    DigestType = NID_md5;
    break;

  case SHA1_DIGEST_SIZE:
    DigestType = NID_sha1;
    break;

  case SHA256_DIGEST_SIZE:
    DigestType = NID_sha256;
    break;

  default:
    return FALSE;
  }

  SigBuf = (UINT8 *) Signature;
  return (BOOLEAN) RSA_verify (
                     DigestType,
                     MessageHash,
                     (UINT32) HashSize,
                     SigBuf,
                     (UINT32) SigSize,
                     (RSA *) RsaContext
                     );
}
Esempio n. 29
0
/**
 * Check memory using specified rsa key and signature
 *
 * arguments:
 * (rsa_pubkey, rsa_signature, string)
 *
 * returns:
 * true - if string match rsa signature
 * false - otherwise
 */
static gint
lua_rsa_verify_file (lua_State *L)
{
	RSA *rsa;
	rspamd_fstring_t *signature;
	const gchar *filename;
	gchar *data = NULL, *data_sig;
	gint ret, fd;
	struct stat st;

	rsa = lua_check_rsa_pubkey (L, 1);
	signature = lua_check_rsa_sign (L, 2);
	filename = luaL_checkstring (L, 3);

	if (rsa != NULL && signature != NULL && filename != NULL) {
		fd = open (filename, O_RDONLY);
		if (fd == -1) {
			msg_err ("cannot open file %s: %s", filename, strerror (errno));
			lua_pushnil (L);
		}
		else {
			if (fstat (fd, &st) == -1 ||
				(data =
				mmap (NULL, st.st_size, PROT_READ, MAP_SHARED, fd,
				0)) == MAP_FAILED) {
				msg_err ("cannot mmap file %s: %s", filename, strerror (errno));
				lua_pushnil (L);
			}
			else {
				data_sig = g_compute_checksum_for_data (G_CHECKSUM_SHA256,
						data,
						st.st_size);
				ret = RSA_verify (NID_sha1, data_sig, strlen (data_sig),
						signature->str, signature->len, rsa);
				if (ret == 0) {
					msg_info ("cannot check rsa signature for file: %s, %s",
						filename, ERR_error_string (ERR_get_error (), NULL));
					lua_pushboolean (L, FALSE);
				}
				else {
					lua_pushboolean (L, TRUE);
				}
				g_free (data_sig);
				munmap (data, st.st_size);
			}
			close (fd);
		}
	}
	else {
		lua_pushnil (L);
	}

	return 1;
}
Esempio n. 30
-1
int
verify(char* public_key_path, unsigned char *msg, int msg_len,
       unsigned char *sig, unsigned int sig_len)
{
    //Load public key
    FILE *fp = fopen(public_key_path, "r");
    if(!fp) {
        printf("Could not find public key\n");
        return 0;
    }

    RSA *rsa = (RSA *) PEM_read_RSA_PUBKEY(fp, NULL, NULL, NULL);
    if(!rsa) return 0;
    fclose(fp);

    //Compute Hash
    unsigned char md[SHA256_DIGEST_LENGTH];
    sha(msg, msg_len, md);

    //Verify signature
    int verified = RSA_verify(NID_sha256, md, SHA256_DIGEST_LENGTH, (unsigned char*)sig, (unsigned int)sig_len, rsa);
    if(!verified){
        printf("Error: %ul\n", (unsigned int)ERR_get_error());
    }
    RSA_free(rsa);
    return verified;
}