Example #1
0
int main() {
    // The secret key for hashing
    const char key[] = "012345678";

    // The data that we're going to hash
    char data[] = "hello world";

    // Be careful of the length of string with the choosen hash engine. SHA1 needed 20 characters.
    // Change the length accordingly with your choosen hash engine.
    unsigned char* result;
    unsigned int len = 20;

    result = (unsigned char*)malloc(sizeof(char) * len);

    HMAC_CTX ctx;
    HMAC_CTX_init(&ctx);

    // Using sha1 hash engine here.
    // You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etc
    HMAC_Init_ex(&ctx, key, strlen(key), EVP_sha1(), NULL);
    HMAC_Update(&ctx, (unsigned char*)&data, strlen(data));
    HMAC_Final(&ctx, result, &len);
    HMAC_CTX_cleanup(&ctx);

    printf("HMAC digest: ");

    for (int i = 0; i != len; i++)
        printf("%02x", (unsigned int)result[i]);

    printf("\n");

    free(result);

    return 0;
}
Example #2
0
//These functions should be replaced with VHMS API calls
int te_digest_init(EVP_MD_CTX *ctx) {
    struct te_hmac_sha1_digest_ctx *c = ctx->md_data;
    printf("Digest init. Current key: %s\n", c->key);
    HMAC_CTX_init(&c->hctx);
    HMAC_Init_ex(&c->hctx, c->key, c->key_ln, EVP_sha1(), 0);
    return 1;
}
Example #3
0
HMACCTX hmac_init(const void *key, int len, enum ssh_hmac_e type) {
  HMACCTX ctx = NULL;

  ctx = malloc(sizeof(*ctx));
  if (ctx == NULL) {
    return NULL;
  }

#ifndef OLD_CRYPTO
  HMAC_CTX_init(ctx); // openssl 0.9.7 requires it.
#endif

  switch(type) {
    case SSH_HMAC_SHA1:
      HMAC_Init(ctx, key, len, EVP_sha1());
      break;
    case SSH_HMAC_MD5:
      HMAC_Init(ctx, key, len, EVP_md5());
      break;
    default:
      SAFE_FREE(ctx);
      ctx = NULL;
  }

  return ctx;
}
Example #4
0
extern "C" HMAC_CTX* CryptoNative_HmacCreate(const uint8_t* key, int32_t keyLen, const EVP_MD* md)
{
    assert(key != nullptr || keyLen == 0);
    assert(keyLen >= 0);
    assert(md != nullptr);

    std::unique_ptr<HMAC_CTX> ctx(new (std::nothrow) HMAC_CTX);
    if (ctx == nullptr)
    {
        // Allocation failed
        return nullptr;
    }

    // NOTE: We can't pass nullptr as empty key since HMAC_Init_ex will interpret
    // that as request to reuse the "existing" key.
    uint8_t _;
    if (keyLen == 0)
        key = &_;

    HMAC_CTX_init(ctx.get());
    int ret = HMAC_Init_ex(ctx.get(), key, keyLen, md, nullptr);

    if (!ret)
    {
        return nullptr;
    }

    return ctx.release();
}
Example #5
0
int winpr_HMAC_Init(WINPR_HMAC_CTX* ctx, int md, const BYTE* key, size_t keylen)
{
#if defined(WITH_OPENSSL)
	const EVP_MD* evp = winpr_openssl_get_evp_md(md);

	if (!evp)
		return -1;

	HMAC_CTX_init((HMAC_CTX*) ctx);

#if (OPENSSL_VERSION_NUMBER < 0x10000000L)
	HMAC_Init_ex((HMAC_CTX*) ctx, key, keylen, evp, NULL);
#else
	if (HMAC_Init_ex((HMAC_CTX*) ctx, key, keylen, evp, NULL) != 1)
		return -1;
#endif

#elif defined(WITH_MBEDTLS)
	const mbedtls_md_info_t* md_info;
	mbedtls_md_type_t md_type = winpr_mbedtls_get_md_type(md);
	md_info = mbedtls_md_info_from_type(md_type);

	if (!md_info)
		return -1;

	mbedtls_md_init((mbedtls_md_context_t*) ctx);

	if (mbedtls_md_setup((mbedtls_md_context_t*) ctx, md_info, 1) != 0)
		return -1;

	if (mbedtls_md_hmac_starts((mbedtls_md_context_t*) ctx, key, keylen) != 0)
		return -1;
#endif
	return 0;
}
// Signing functions
bool OSSLEVPMacAlgorithm::signInit(const SymmetricKey* key)
{
	// Call the superclass initialiser
	if (!MacAlgorithm::signInit(key))
	{
		return false;
	}

	// Initialize the context
	HMAC_CTX_init(&curCTX);

	// Initialize EVP signing
	if (!HMAC_Init(&curCTX, key->getKeyBits().const_byte_str(), key->getKeyBits().size(), getEVPHash()))
	{
		ERROR_MSG("HMAC_Init failed");

		HMAC_CTX_cleanup(&curCTX);

		ByteString dummy;
		MacAlgorithm::signFinal(dummy);

		return false;
	}

	return true;
}
Example #7
0
static int hmac_fdigest(lua_State *L)
{
  HMAC_CTX c;
  unsigned char digest[EVP_MAX_MD_SIZE];
  size_t written = 0;
  unsigned int i;
  char *hex;
  const char *t = luaL_checkstring(L, 1);
  const char *s = luaL_checkstring(L, 2);
  const char *k = luaL_checkstring(L, 3);
  const EVP_MD *type = EVP_get_digestbyname(t);

  if (type == NULL) {
    luaL_argerror(L, 1, "invalid digest type");
    return 0;
  }

  HMAC_CTX_init(&c);
  HMAC_Init_ex(&c, k, lua_strlen(L, 3), type, NULL);
  HMAC_Update(&c, (unsigned char *)s, lua_strlen(L, 2));
  HMAC_Final(&c, digest, &written);

  if (lua_toboolean(L, 4))
    lua_pushlstring(L, (char *)digest, written);
  else
  {
    hex = calloc(sizeof(char), written*2 + 1);
    for (i = 0; i < written; i++)
      sprintf(hex + 2*i, "%02x", digest[i]);
    lua_pushlstring(L, hex, written*2);
    free(hex);
  }

  return 1;
}
Example #8
0
static krb5_error_code
calculate_reply_hash(krb5_context context,
		     krb5_keyblock *key,
		     Kx509Response *rep)
{
    krb5_error_code ret;
    HMAC_CTX ctx;

    HMAC_CTX_init(&ctx);

    HMAC_Init_ex(&ctx, key->keyvalue.data, key->keyvalue.length,
		 EVP_sha1(), NULL);
    ret = krb5_data_alloc(rep->hash, HMAC_size(&ctx));
    if (ret) {
	HMAC_CTX_cleanup(&ctx);
	krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
	return ENOMEM;
    }

    HMAC_Update(&ctx, version_2_0, sizeof(version_2_0));
    if (rep->error_code) {
	int32_t t = *rep->error_code;
	do {
	    unsigned char p = (t & 0xff);
	    HMAC_Update(&ctx, &p, 1);
	    t >>= 8;
	} while (t);
    }
Example #9
0
WINPR_HMAC_CTX* winpr_HMAC_New(void)
{
	WINPR_HMAC_CTX* ctx = NULL;

#if defined(WITH_OPENSSL)
	HMAC_CTX* hmac = NULL;
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
	if (!(hmac = (HMAC_CTX*) calloc(1, sizeof(HMAC_CTX))))
		return NULL;
	HMAC_CTX_init(hmac);
#else
	if (!(hmac = HMAC_CTX_new()))
		return NULL;
#endif
	ctx = (WINPR_HMAC_CTX*) hmac;

#elif defined(WITH_MBEDTLS)
	mbedtls_md_context_t* hmac;
	if (!(hmac = (mbedtls_md_context_t*) calloc(1, sizeof(mbedtls_md_context_t))))
		return NULL;

	mbedtls_md_init(hmac);

	ctx = (WINPR_HMAC_CTX*) hmac;
#endif

	return ctx;
}
Example #10
0
static void doFile(FILE *fp)
{
  HMAC_CTX ctx;
  unsigned char digest[EVP_MAX_MD_SIZE];
  unsigned int i = 0, dlen = (unsigned int)sizeof(digest);
  size_t rd = 0;
  const char key[] = "etaonrishdlcupfm";
  unsigned char buf[4096];

  /* Initialise context */
  HMAC_CTX_init(&ctx);
  /* Set digest type and key in context */
  HMAC_Init_ex(&ctx, key, strlen(key), EVP_sha1(), NULL);
  /* Process input stream */
  do {
    rd = fread(buf,sizeof(char),sizeof(buf),fp);
    if(ferror(fp) || ((rd < sizeof(buf)) && !feof(fp))) exit(3);
    if(!HMAC_Update(&ctx, buf, (unsigned int)rd)) exit(4);
  } while(!feof(fp));

  /* Generate digest */
  if(!HMAC_Final(&ctx, digest, &dlen)) exit(5);
  HMAC_CTX_cleanup(&ctx);

  /* Display digest in hex */
  for(i = 0; i < dlen; i++) printf("%02x", digest[i]);
  printf("\n");
  return;
}
Example #11
0
HmacHash::HmacHash()
{
    uint8 temp[SEED_KEY_SIZE] = { 0x38, 0xA7, 0x83, 0x15, 0xF8, 0x92, 0x25, 0x30, 0x71, 0x98, 0x67, 0xB1, 0x8C, 0x4, 0xE2, 0xAA };
    memcpy(&m_key, &temp, SEED_KEY_SIZE);
    HMAC_CTX_init(&m_ctx);
    HMAC_Init_ex(&m_ctx, &m_key, SEED_KEY_SIZE, EVP_sha1(), NULL);
}
Example #12
0
static krb5_error_code
verify_req_hash(krb5_context context,
		const Kx509Request *req,
		krb5_keyblock *key)
{
    unsigned char digest[SHA_DIGEST_LENGTH];
    HMAC_CTX ctx;

    if (req->pk_hash.length != sizeof(digest)) {
	krb5_set_error_message(context, KRB5KDC_ERR_PREAUTH_FAILED,
			       "pk-hash have wrong length: %lu",
			       (unsigned long)req->pk_hash.length);
	return KRB5KDC_ERR_PREAUTH_FAILED;
    }

    HMAC_CTX_init(&ctx);
    HMAC_Init_ex(&ctx,
		 key->keyvalue.data, key->keyvalue.length,
		 EVP_sha1(), NULL);
    if (sizeof(digest) != HMAC_size(&ctx))
	krb5_abortx(context, "runtime error, hmac buffer wrong size in kx509");
    HMAC_Update(&ctx, version_2_0, sizeof(version_2_0));
    HMAC_Update(&ctx, req->pk_key.data, req->pk_key.length);
    HMAC_Final(&ctx, digest, 0);
    HMAC_CTX_cleanup(&ctx);

    if (memcmp(req->pk_hash.data, digest, sizeof(digest)) != 0) {
	krb5_set_error_message(context, KRB5KDC_ERR_PREAUTH_FAILED,
			       "pk-hash is not correct");
	return KRB5KDC_ERR_PREAUTH_FAILED;
    }
    return 0;
}
Example #13
0
static int rtmp_handshake_make_digest(const uint8_t* key, size_t len, const uint8_t* ptr, size_t ptrlen, const uint8_t* digest, uint8_t* dst)
{
	static HMAC_CTX        *hmac;
	unsigned int            digestlen;

	if (hmac == NULL) {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
		static HMAC_CTX  shmac;
		hmac = &shmac;
		HMAC_CTX_init(hmac);
#else
		hmac = HMAC_CTX_new();
#endif
	}

	HMAC_Init_ex(hmac, key, len, EVP_sha256(), NULL);
	if (digest)
	{
		assert(digest + SHA256_DIGEST_LENGTH <= ptr + ptrlen);
		HMAC_Update(hmac, ptr, digest - ptr);
		if (digest + SHA256_DIGEST_LENGTH < ptr + ptrlen)
			HMAC_Update(hmac, digest + SHA256_DIGEST_LENGTH, ptrlen - (digest - ptr) - SHA256_DIGEST_LENGTH);
	}
	else
	{
		HMAC_Update(hmac, ptr, ptrlen);
	}
	HMAC_Final(hmac, dst, &digestlen);
	assert(digestlen == SHA256_DIGEST_LENGTH);
	return 0;
}
Example #14
0
static void
check_hmac(void)
{
    unsigned char buf[4] = { 0, 0, 0, 0 };
    char hmackey[] = "hello-world";
    size_t hmackey_size = sizeof(hmackey);
    unsigned int hmaclen;
    unsigned char hmac[EVP_MAX_MD_SIZE];
    HMAC_CTX c;

    char answer[20] = "\x2c\xfa\x32\xb7\x2b\x8a\xf6\xdf\xcf\xda"
	              "\x6f\xd1\x52\x4d\x54\x58\x73\x0f\xf3\x24";

    HMAC_CTX_init(&c);
    HMAC_Init_ex(&c, hmackey, hmackey_size, EVP_sha1(), NULL);
    HMAC_Update(&c, buf, sizeof(buf));
    HMAC_Final(&c, hmac, &hmaclen);
    HMAC_CTX_cleanup(&c);

    if (hmaclen != 20)
	errx(1, "hmaclen = %d\n", (int)hmaclen);

    if (ct_memcmp(hmac, answer, hmaclen) != 0)
	errx(1, "wrong answer\n");
}
Example #15
0
static HMAC_CTX *HMAC_CTX_new(void)
{
    HMAC_CTX *ctx = OPENSSL_malloc(sizeof(HMAC_CTX));
    if (ctx != NULL)
        HMAC_CTX_init(ctx);
    return ctx;
}
Example #16
0
static void
insert_message_authenticator(struct rad_handle *h, int resp)
{
#ifdef WITH_SSL
	u_char md[EVP_MAX_MD_SIZE];
	u_int md_len;
	const struct rad_server *srvp;
	HMAC_CTX ctx;
	srvp = &h->servers[h->srv];

	if (h->authentic_pos != 0) {
		HMAC_CTX_init(&ctx);
		HMAC_Init(&ctx, srvp->secret, strlen(srvp->secret), EVP_md5());
		HMAC_Update(&ctx, &h->out[POS_CODE], POS_AUTH - POS_CODE);
		if (resp)
		    HMAC_Update(&ctx, &h->in[POS_AUTH], LEN_AUTH);
		else
		    HMAC_Update(&ctx, &h->out[POS_AUTH], LEN_AUTH);
		HMAC_Update(&ctx, &h->out[POS_ATTRS],
		    h->out_len - POS_ATTRS);
		HMAC_Final(&ctx, md, &md_len);
		HMAC_CTX_cleanup(&ctx);
		HMAC_cleanup(&ctx);
		memcpy(&h->out[h->authentic_pos + 2], md, md_len);
	}
#endif
}
//ignore
unsigned char *HMACRSA(const EVP_MD *evp_md, const void *key, int key_len,const unsigned char *d, size_t n, unsigned char *md,unsigned int *md_len)
{
    HMAC_CTX c;
    static unsigned char m[EVP_MAX_MD_SIZE];
    //TODO: get/set rsa engine struct
    const char *engine_id = "rsa";
    ENGINE_load_builtin_engines();
    ENGINE *e = ENGINE_by_id(engine_id);//ENGINE_;
    if(!e)
      fprintf(stderr,"Engine not available\n");

    ENGINE_init(e);
    if (md == NULL)
        md = m;
    HMAC_CTX_init(&c);

    if (!HMAC_Init_ex(&c, key, key_len, evp_md, NULL))
        goto err;
    if (!HMAC_Update(&c, d, n))
        goto err;
    if (!HMAC_Final(&c, md, md_len))
        goto err;
    HMAC_CTX_cleanup(&c);
    ENGINE_free(e);
    return md;
 err:
    HMAC_CTX_cleanup(&c);
    ENGINE_free(e);
    return NULL;
}
Example #18
0
void HMAC_Init(HMAC_CTX *ctx, const void *key, int len,
	       const EVP_MD *md)
	{
	if(key && md)
	    HMAC_CTX_init(ctx);
	HMAC_Init_ex(ctx,key,len,md, NULL);
	}
Example #19
0
unsigned char *
EncodeHMACSHA256(
    unsigned char* key,
    int keylen,
    const char* data,
    int datalen)
{
    unsigned char *hmachash = malloc(32);
    const unsigned char *datatohash = (unsigned char *)data;
    unsigned char tk[SHA256_DIGEST_LENGTH];

    // Initialise HMACh
    HMAC_CTX HMAC;
    unsigned int hmaclength = 32;
    memset(hmachash, 0, hmaclength);

    if (keylen > 64 ) {
	SHA256(key, keylen, tk);
	key    = tk;
	keylen = SHA256_DIGEST_LENGTH;
    }

    // Digest the key and message using SHA256
    HMAC_CTX_init(&HMAC);
    HMAC_Init_ex(&HMAC, key, keylen, EVP_sha256(),NULL);
    HMAC_Update(&HMAC, datatohash, datalen);
    HMAC_Final(&HMAC, hmachash, &hmaclength);
    HMAC_CTX_cleanup(&HMAC);

    return hmachash;
}
Example #20
0
char* Qiniu_Mac_SignToken(Qiniu_Mac* self, char* policy_str)
{
	char* token;
	char* encoded_digest;
	char digest[EVP_MAX_MD_SIZE + 1];
	unsigned int dgtlen = sizeof(digest);
	HMAC_CTX ctx;
	Qiniu_Mac mac;

	char* encoded_policy_str = Qiniu_String_Encode(policy_str);

	if (self) {
		mac = *self;
	} else {
		mac.accessKey = QINIU_ACCESS_KEY;
		mac.secretKey = QINIU_SECRET_KEY;
	}

	HMAC_CTX_init(&ctx);
	HMAC_Init_ex(&ctx, mac.secretKey, strlen(mac.secretKey), EVP_sha1(), NULL);
	HMAC_Update(&ctx, encoded_policy_str, strlen(encoded_policy_str));
	HMAC_Final(&ctx, digest, &dgtlen);
	HMAC_CTX_cleanup(&ctx);

	encoded_digest = Qiniu_Memory_Encode(digest, dgtlen);
	token = Qiniu_String_Concat(mac.accessKey, ":", encoded_digest, ":", encoded_policy_str, NULL);
	free(encoded_policy_str);
	free(encoded_digest);

	return token;
}
Example #21
0
int
mac_init(struct sshmac *mac)
{
	if (mac->key == NULL)
		return SSH_ERR_INVALID_ARGUMENT;
	switch (mac->type) {
	case SSH_EVP:
		if (mac->evp_md == NULL)
			return SSH_ERR_INVALID_ARGUMENT;
		HMAC_CTX_init(&mac->evp_ctx);
		if (HMAC_Init(&mac->evp_ctx, mac->key, mac->key_len,
		    mac->evp_md) != 1) {
			HMAC_CTX_cleanup(&mac->evp_ctx);
			return SSH_ERR_LIBCRYPTO_ERROR;
		}
		return 0;
	case SSH_UMAC:
		if ((mac->umac_ctx = umac_new(mac->key)) == NULL)
			return SSH_ERR_ALLOC_FAIL;
		return 0;
	case SSH_UMAC128:
		mac->umac_ctx = umac128_new(mac->key);
		return 0;
	default:
		return SSH_ERR_INVALID_ARGUMENT;
	}
}
Example #22
0
char* QBox_MakeUpToken(const QBox_AuthPolicy* auth)
{
	char* uptoken;
	char* policy_str;
	char* encoded_digest;
	char* encoded_policy_str;
	char digest[EVP_MAX_MD_SIZE + 1];
	unsigned int dgtlen = sizeof(digest);

	HMAC_CTX ctx;

	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();

	policy_str = QBox_AuthPolicy_json(auth);
	encoded_policy_str = QBox_String_Encode(policy_str);
	free(policy_str);

	bzero(digest, sizeof(digest));

	HMAC_CTX_init(&ctx);
	HMAC_Init_ex(&ctx, QBOX_SECRET_KEY, strlen(QBOX_SECRET_KEY), EVP_sha1(), NULL);
	HMAC_Update(&ctx, encoded_policy_str, strlen(encoded_policy_str));
	HMAC_Final(&ctx, digest, &dgtlen);
	HMAC_CTX_cleanup(&ctx);

	encoded_digest = QBox_Memory_Encode(digest, dgtlen);
	uptoken = QBox_String_Concat(QBOX_ACCESS_KEY, ":", encoded_digest, ":", encoded_policy_str, NULL);
	free(encoded_policy_str);
	free(encoded_digest);

	return uptoken;
}
Example #23
0
static ngx_int_t
ngx_rtmp_make_digest(ngx_str_t *key, ngx_buf_t *src,
        u_char *skip, u_char *dst, ngx_log_t *log)
{
    static HMAC_CTX         hmac;
    static unsigned         hmac_initialized;
    unsigned int            len;

    if (!hmac_initialized) {
        HMAC_CTX_init(&hmac);
        hmac_initialized = 1;
    }

    HMAC_Init_ex(&hmac, key->data, key->len, EVP_sha256(), NULL);

    if (skip && src->pos <= skip && skip <= src->last) {
        if (skip != src->pos) {
            HMAC_Update(&hmac, src->pos, skip - src->pos);
        }
        if (src->last != skip + NGX_RTMP_HANDSHAKE_KEYLEN) {
            HMAC_Update(&hmac, skip + NGX_RTMP_HANDSHAKE_KEYLEN,
                    src->last - skip - NGX_RTMP_HANDSHAKE_KEYLEN);
        }
    } else {
        HMAC_Update(&hmac, src->pos, src->last - src->pos);
    }

    HMAC_Final(&hmac, dst, &len);

    return NGX_OK;
}
Example #24
0
selene_error_t *sln_hmac_openssl_create(selene_t *s, sln_hmac_e type,
                                        const char *key, size_t klen,
                                        sln_hmac_t **p_hmac) {
  sln_hmac_t *h = sln_alloc(s, sizeof(sln_hmac_t));
  HMAC_CTX *hctx = sln_alloc(s, sizeof(HMAC_CTX));
  const EVP_MD *mt = NULL;

  h->s = s;
  h->type = type;
  h->baton = hctx;

  switch (h->type) {
    case SLN_HMAC_MD5: {
      mt = EVP_md5();
      break;
    }
    case SLN_HMAC_SHA1: {
      mt = EVP_sha1();
      break;
    }
  }

  HMAC_CTX_init(hctx);
  HMAC_Init_ex(hctx, key, klen, mt, NULL);

  *p_hmac = h;

  return SELENE_SUCCESS;
}
Example #25
0
 char *api_key_ssl(char *data,char *result_hex)
{
    // The secret key for hashing

    unsigned char result[67];
    unsigned int len = 67;
    strcpy(data, read_luci_conf("api_key"));
    strcat(data,nonce); DEBUG_printf("api_key_ssl--------------  %s\n",nonce);

    HMAC_CTX ctx;
    HMAC_CTX_init(&ctx);
    HMAC_Init_ex(&ctx, read_luci_conf("api_security"), strlen(read_luci_conf("api_security")), EVP_sha256(), NULL);
    HMAC_Update(&ctx, (unsigned char*)data, strlen(data));
    HMAC_Final(&ctx, result, &len);
    HMAC_CTX_cleanup(&ctx);
    int i;
    char b[2];
    strcpy(result_hex,"signature=");
    for ( i = 0; i != len; i++)
    {
        //DEBUG_printf("%02x", (unsigned int)result[i]);
	sprintf(b,"%02x",(unsigned int)result[i]);
	strcat(result_hex,b);
    }
    strcat(result_hex,",");
	//DEBUG_printf("result_hex=  %s\n",result_hex);
return result_hex;
}
Example #26
0
static ECIES_HMAC_TYPE makeHMAC (const ECIES_HMAC_KEY_TYPE& secret, Blob const& data)
{
    HMAC_CTX ctx;
    HMAC_CTX_init (&ctx);

    if (HMAC_Init_ex (&ctx, secret.begin (), ECIES_HMAC_KEY_SIZE, ECIES_HMAC_ALGO, nullptr) != 1)
    {
        HMAC_CTX_cleanup (&ctx);
        throw std::runtime_error ("init hmac");
    }

    if (HMAC_Update (&ctx, & (data.front ()), data.size ()) != 1)
    {
        HMAC_CTX_cleanup (&ctx);
        throw std::runtime_error ("update hmac");
    }

    ECIES_HMAC_TYPE ret;
    unsigned int ml = ECIES_HMAC_SIZE;

    if (HMAC_Final (&ctx, ret.begin (), &ml) != 1)
    {
        HMAC_CTX_cleanup (&ctx);
        throw std::runtime_error ("finalize hmac");
    }

    assert (ml == ECIES_HMAC_SIZE);
    HMAC_CTX_cleanup (&ctx);

    return ret;
}
Example #27
0
void BTCTrader::signRequest ( QString* header, QNetworkRequest* newRequest )
{
    nonce += 1;
    *header = ( header->length() == 0 ) ? "nonce=" + QString::number( nonce ) : "nonce=" + QString::number( nonce ) + "&" + *header;

    QByteArray key = QByteArray::fromBase64( restSign.toStdString().c_str() );
    unsigned char* result;
    unsigned int result_len = 512;
    HMAC_CTX ctx;

    result = (unsigned char*) malloc(sizeof(unsigned char) * result_len);

    ENGINE_load_builtin_engines();
    ENGINE_register_all_complete();

    HMAC_CTX_init(&ctx);
    HMAC_Init_ex(&ctx, key.constData(), key.length(), EVP_sha512(), NULL);
    HMAC_Update(&ctx, (unsigned char*)header->toAscii().constData(), header->length());
    HMAC_Final(&ctx, result, &result_len);
    HMAC_CTX_cleanup(&ctx);

    newRequest->setRawHeader( "Rest-Key", restKey.toStdString().c_str() );
    newRequest->setRawHeader( "Rest-Sign", QByteArray::fromRawData( (char*)result, result_len ).toBase64() );
    newRequest->setRawHeader( "content-type","application/x-www-form-urlencoded" );
    free ( result );
}
static void tls1_P_hash( const EVP_MD *md, const unsigned char *sec,
						int sec_len, unsigned char *seed, int seed_len,
						unsigned char *out, int olen)
{
	int chunk,n;
	unsigned int j;
	HMAC_CTX ctx;
	HMAC_CTX ctx_tmp;
	unsigned char A1[EVP_MAX_MD_SIZE];
	unsigned int A1_len;

	chunk=EVP_MD_size(md);

	HMAC_CTX_init(&ctx);
	HMAC_CTX_init(&ctx_tmp);
	HMAC_Init_ex(&ctx,sec,sec_len,md, NULL);
	HMAC_Init_ex(&ctx_tmp,sec,sec_len,md, NULL);
	HMAC_Update(&ctx,seed,seed_len);
	HMAC_Final(&ctx,A1,&A1_len);

	n=0;
	for (;;)
	{
		HMAC_Init_ex(&ctx,NULL,0,NULL,NULL); /* re-init */
		HMAC_Init_ex(&ctx_tmp,NULL,0,NULL,NULL); /* re-init */
		HMAC_Update(&ctx,A1,A1_len);
		HMAC_Update(&ctx_tmp,A1,A1_len);
		HMAC_Update(&ctx,seed,seed_len);

		if (olen > chunk)
		{
			HMAC_Final(&ctx,out,&j);
			out+=j;
			olen-=j;
			HMAC_Final(&ctx_tmp,A1,&A1_len); /* calc the next A1 value */
		}
		else	/* last one */
		{
			HMAC_Final(&ctx,A1,&A1_len);
			memcpy(out,A1,olen);
			break;
		}
	}
	HMAC_CTX_cleanup(&ctx);
	HMAC_CTX_cleanup(&ctx_tmp);
	OPENSSL_cleanse(A1,sizeof(A1));
}
Example #29
0
/**
@fn int soap_smd_init(struct soap *soap, struct soap_smd_data *data, int alg, const void *key, int keylen)
@brief Initiates a (signed) digest computation.
@param soap context
@param[in,out] data smdevp engine context
@param[in] alg is algorithm to use
@param[in] key is key to use or NULL for digests
@param[in] keylen is length of HMAC key (when provided)
@return SOAP_OK or SOAP_SSL_ERROR
*/
int
soap_smd_init(struct soap *soap, struct soap_smd_data *data, int alg, const void *key, int keylen)
{ static int done = 0;
  int err = 1;
#ifdef WITH_OPENSSL
  /* OpenSSL: make sure we have the digest algorithms, need to call just once */
  if (!done)
  { done = 1;
    OpenSSL_add_all_digests();
    OpenSSL_add_all_algorithms();
  }
#endif
  /* the algorithm to use */
  data->alg = alg;
  /* the key to use */
  data->key = key;
  /* allocate and init the OpenSSL HMAC or EVP_MD context */
  if ((alg & (SOAP_SMD_PASSTHRU-1)) == SOAP_SMD_HMAC_SHA1)
  { data->ctx = (void*)SOAP_MALLOC(soap, sizeof(HMAC_CTX));
    HMAC_CTX_init((HMAC_CTX*)data->ctx);
  }
  else
  { data->ctx = (void*)SOAP_MALLOC(soap, sizeof(EVP_MD_CTX));
    EVP_MD_CTX_init((EVP_MD_CTX*)data->ctx);
  }
  DBGLOG(TEST, SOAP_MESSAGE(fdebug, "-- SMD Init alg=%d (%p) --\n", alg, data->ctx));
  /* init the digest or signature computations */
  switch (alg & (SOAP_SMD_PASSTHRU-1))
  { case SOAP_SMD_DGST_MD5:
      EVP_DigestInit((EVP_MD_CTX*)data->ctx, EVP_md5());
      break;
    case SOAP_SMD_DGST_SHA1:
      EVP_DigestInit((EVP_MD_CTX*)data->ctx, EVP_sha1());
      break;
    case SOAP_SMD_DGST_SHA256:
      EVP_DigestInit((EVP_MD_CTX*)data->ctx, EVP_sha256());
      break;
    case SOAP_SMD_HMAC_SHA1:
      HMAC_Init((HMAC_CTX*)data->ctx, key, keylen, EVP_sha1());
      break;
    case SOAP_SMD_SIGN_DSA_SHA1:
      err = EVP_SignInit((EVP_MD_CTX*)data->ctx, EVP_dss1());
      break;
    case SOAP_SMD_SIGN_RSA_SHA1:
      err = EVP_SignInit((EVP_MD_CTX*)data->ctx, EVP_sha1());
      break;
    case SOAP_SMD_SIGN_RSA_SHA256:
      err = EVP_SignInit((EVP_MD_CTX*)data->ctx, EVP_sha256());
      break;
    case SOAP_SMD_VRFY_DSA_SHA1:
      err = EVP_VerifyInit((EVP_MD_CTX*)data->ctx, EVP_dss1());
      break;
    case SOAP_SMD_VRFY_RSA_SHA1:
      err = EVP_VerifyInit((EVP_MD_CTX*)data->ctx, EVP_sha1());
      break;
  }
  /* check and return */
  return soap_smd_check(soap, data, err, "soap_smd_init() failed");
}
Example #30
0
int sftp_mac_set_read_key(pool *p, const EVP_MD *hash, const BIGNUM *k,
    const char *h, uint32_t hlen) {
  const unsigned char *id = NULL;
  char *buf, *ptr;
  uint32_t buflen, bufsz, id_len;
  char letter;
  size_t blocksz;
  struct sftp_mac *mac;
  HMAC_CTX *mac_ctx;

  switch_read_mac();

  mac = &(read_macs[read_mac_idx]);
  mac_ctx = &(read_ctxs[read_mac_idx]);

  bufsz = buflen = 1024;
  ptr = buf = sftp_msg_getbuf(p, bufsz);

  /* Need to use SSH2-style format of K for the key. */
  sftp_msg_write_mpint(&buf, &buflen, k);

  id_len = sftp_session_get_id(&id);

  /* HASH(K || H || "E" || session_id) */
  letter = 'E';
  set_mac_key(mac, hash, ptr, (bufsz - buflen), h, hlen, &letter, id, id_len);

#if OPENSSL_VERSION_NUMBER > 0x000907000L
  HMAC_CTX_init(mac_ctx);

# if OPENSSL_VERSION_NUMBER >= 0x10000001L
  if (HMAC_Init_ex(mac_ctx, mac->key, mac->key_len, mac->digest, NULL) != 1) {
    pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION,
      "error initializing HMAC: %s", sftp_crypto_get_errors());
    errno = EPERM;
    return -1;
  }

# else
  HMAC_Init_ex(mac_ctx, mac->key, mac->key_len, mac->digest, NULL);
# endif /* OpenSSL-1.0.0 and later */

#else
  /* Reset the HMAC context. */
  HMAC_Init(mac_ctx, NULL, 0, NULL);
  HMAC_Init(mac_ctx, mac->key, mac->key_len, mac->digest);
#endif

  if (mac->mac_len == 0) {
    blocksz = EVP_MD_size(mac->digest);

  } else {
    blocksz = mac->mac_len;
  }

  pr_memscrub(ptr, bufsz);
  sftp_mac_set_block_size(blocksz);
  return 0;
}