示例#1
1
int main(int argc, char *argv[]) {
    if(argc != 2) {
        printf("Usage: ./test_app <file_name>\n");
        return -1;
    }

    ENGINE *e = load_engine(ENGINE_MODULE, "test_engine");
    if(e == 0) {
        printf("Unable to load engine\n");
        return -1;
    }
    ENGINE_ctrl_cmd_string(e, "username", "user", 0);
    ENGINE_ctrl_cmd_string(e, "password", "password", 0);
    ENGINE_init(e);
    
    HMAC_CTX ctx;
    HMAC_CTX_init(&ctx);
    HMAC_Init_ex(&ctx, "test_key\0", 9, EVP_sha1(), e);

    FILE *f = fopen(argv[1], "r");
    char buf[BUF_SIZE];
    while(!feof(f)) {
        size_t ln = fread(buf, sizeof(char), BUF_SIZE, f);
        if(ln == 0) continue;
        HMAC_Update(&ctx, buf, ln);
    }
    fclose(f);
    
    unsigned int siglen;
    unsigned char md[20];
    HMAC_Final(&ctx, md, &siglen);
    ENGINE_finish(e);

    printf("HMAC-SHA1: ");
    for(size_t i = 0; i < siglen; i++) printf("%02x", md[i]);
    printf("\n");

    return 0;
}
示例#2
0
		void init(RC4_KEY* rc4, const unsigned char* session_key, const unsigned char* peer_key)
		{
			HMAC_CTX hmac_ctx;
			HMAC_CTX_init(&hmac_ctx);
			HMAC_Init_ex(&hmac_ctx, (void*)peer_key, peer_key_size, EVP_sha1(), NULL);

			HMAC_Update(&hmac_ctx, session_key, session_key_size);

			unsigned char rc4_keystring[SHA_DIGEST_LENGTH];
			unsigned int rc4_keystring_size = SHA_DIGEST_LENGTH;
			
			HMAC_Final(&hmac_ctx, rc4_keystring, &rc4_keystring_size);
			
			HMAC_CTX_cleanup(&hmac_ctx);

			RC4_set_key(rc4, rc4_keystring_size, rc4_keystring);
			
			const unsigned char rc4_key_init[rc4_init_size] = { 0x00 };
			unsigned char rc4_key_init_output[rc4_init_size];

			RC4(rc4, sizeof(rc4_key_init), rc4_key_init, rc4_key_init_output);
		}
示例#3
0
int
dsa_init(struct iked_dsa *dsa, const void *buf, size_t len)
{
	int	 ret;

	if (dsa->dsa_hmac) {
		if (!HMAC_Init_ex(dsa->dsa_ctx, ibuf_data(dsa->dsa_keydata),
		    ibuf_length(dsa->dsa_keydata), dsa->dsa_priv, NULL))
			return (-1);
		return (0);
	}

	if (dsa->dsa_sign)
		ret = EVP_SignInit_ex(dsa->dsa_ctx, dsa->dsa_priv, NULL);
	else {
		if ((ret = _dsa_verify_init(dsa, buf, len)) != 0)
			return (ret);
		ret = EVP_VerifyInit_ex(dsa->dsa_ctx, dsa->dsa_priv, NULL);
	}

	return (ret ? 0 : -1);
}
示例#4
0
int cmeHMACInit (HMAC_CTX **ctx, ENGINE *engine, EVP_MD *digest, const char *key, int keyLen)
{
    int result;

    *ctx=(HMAC_CTX *)malloc(sizeof(HMAC_CTX));
    HMAC_CTX_init(*ctx);   //Initialize HMAC context.
    result= HMAC_Init_ex(*ctx,key,keyLen,digest,engine);
    if (result==0)  //1= success, 0=failure
    {
#ifdef ERROR_LOG
        fprintf(stderr,"CaumeDSE Error: cmeHMACInit(), HMAC_Init_ex() failure!\n");
#endif
        return (1);
    }
    else
    {
#ifdef DEBUG
        fprintf(stdout,"CaumeDSE Debug: cmeHMACInit(), HMAC_Init_ex() success.\n");
#endif
        return (0);
    }
示例#5
0
static int aead_tls_init(EVP_AEAD_CTX *ctx, const uint8_t *key, size_t key_len,
                         size_t tag_len, enum evp_aead_direction_t dir,
                         const EVP_CIPHER *cipher, const EVP_MD *md,
                         char implicit_iv) {
  if (tag_len != EVP_AEAD_DEFAULT_TAG_LENGTH &&
      tag_len != EVP_MD_size(md)) {
    OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_TAG_SIZE);
    return 0;
  }

  if (key_len != EVP_AEAD_key_length(ctx->aead)) {
    OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_KEY_LENGTH);
    return 0;
  }

  size_t mac_key_len = EVP_MD_size(md);
  size_t enc_key_len = EVP_CIPHER_key_length(cipher);
  assert(mac_key_len + enc_key_len +
         (implicit_iv ? EVP_CIPHER_iv_length(cipher) : 0) == key_len);

  AEAD_TLS_CTX *tls_ctx = (AEAD_TLS_CTX *)&ctx->state;
  EVP_CIPHER_CTX_init(&tls_ctx->cipher_ctx);
  HMAC_CTX_init(&tls_ctx->hmac_ctx);
  assert(mac_key_len <= EVP_MAX_MD_SIZE);
  OPENSSL_memcpy(tls_ctx->mac_key, key, mac_key_len);
  tls_ctx->mac_key_len = (uint8_t)mac_key_len;
  tls_ctx->implicit_iv = implicit_iv;

  if (!EVP_CipherInit_ex(&tls_ctx->cipher_ctx, cipher, NULL, &key[mac_key_len],
                         implicit_iv ? &key[mac_key_len + enc_key_len] : NULL,
                         dir == evp_aead_seal) ||
      !HMAC_Init_ex(&tls_ctx->hmac_ctx, key, mac_key_len, md, NULL)) {
    aead_tls_cleanup(ctx);
    return 0;
  }
  EVP_CIPHER_CTX_set_padding(&tls_ctx->cipher_ctx, 0);

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

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

  s = luaL_checkstring(L, 2);
  k = luaL_checkstring(L, 3);


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

  if (lua_toboolean(L, 4))
    lua_pushlstring(L, (char *)digest, written);
  else {
    hex = (char*)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;
}
static int calculate_auth_data(const struct iovec *iov, int iovlen,
			       const struct in6_addr *coa,
			       const struct in6_addr *cn,
			       const uint8_t *key, uint8_t *digest)
{
	uint8_t buf[HMAC_SHA1_HASH_LEN];
	int i;

#ifdef HAVE_LIBCRYPTO
	unsigned int len = HMAC_SHA1_HASH_LEN;
	HMAC_CTX ctx;
	const EVP_MD *evp_md = EVP_sha1();

	HMAC_CTX_init(&ctx);
	HMAC_Init_ex(&ctx, key, HMAC_SHA1_KEY_SIZE, evp_md, NULL);

	HMAC_Update(&ctx, (uint8_t *)coa, sizeof(*coa));
	HMAC_Update(&ctx, (uint8_t *)cn, sizeof(*coa));
	for (i = 0; i < iovlen; i++) {
		HMAC_Update(&ctx, (uint8_t *)iov[i].iov_base, iov[i].iov_len);
	}
	HMAC_Final(&ctx, buf, &len);
	HMAC_CTX_cleanup(&ctx);
#else
	HMAC_SHA1_CTX ctx;

	HMAC_SHA1_init(&ctx, key, HMAC_SHA1_KEY_SIZE);
	HMAC_SHA1_update(&ctx, (uint8_t *)coa, sizeof(*coa));
	HMAC_SHA1_update(&ctx, (uint8_t *)cn, sizeof(*coa));
	for (i = 0; i < iovlen; i++) {
		HMAC_SHA1_update(&ctx, (uint8_t *)iov[i].iov_base,
				 iov[i].iov_len);
	}
	HMAC_SHA1_final(&ctx, buf);
#endif
	memcpy(digest, buf, MIPV6_DIGEST_LEN);
	return 0;
}
示例#8
0
/*
 * \brief Initializes the passed hmac to use the passed key and digest algorithm
 */
int PKI_HMAC_init(PKI_HMAC *hmac, unsigned char *key, size_t key_size, PKI_DIGEST_ALG *digest, HSM *hsm)
{
	if (!hmac) return PKI_ERROR(PKI_ERR_PARAM_NULL, NULL);

	// Free the memory if another key was used
	if (hmac->key) PKI_MEM_free(hmac->key);
	hmac->key = NULL;

	if (hmac->value) PKI_MEM_free(hmac->value);
	hmac->value = NULL;

	// Generate the new PKI_MEM to hold the key data
	hmac->key = PKI_MEM_new_data(key_size, key);
	if (!hmac->key || !hmac->key->data || hmac->key->size <= 0)
	{
		hmac->initialized = 0;
		return PKI_ERROR(PKI_ERR_MEMORY_ALLOC, NULL);
	}

	// Sets the algoritm
	hmac->digestAlg = digest ? digest : PKI_DIGEST_ALG_SHA1;

	// Checks if HSM implementation was asked by the developer
	if (hsm)
	{
		PKI_ERROR(PKI_ERR_GENERAL, "Code to support HMAC on HSMs not implemented, yet.");
		hmac->initialized = 0;
		return PKI_ERR;
	}

	// Initializes the Context
	HMAC_Init_ex(&hmac->ctx, (const void *) key, (int) key_size, hmac->digestAlg, NULL);

	// Sets the initialization flag
	hmac->initialized = 1;

	return PKI_OK;
}
示例#9
0
/**
  Initializes user-supplied memory pointed by HmacMd5Context as HMAC-MD5 context for
  subsequent use.

  If HmacMd5Context is NULL, then return FALSE.

  @param[out]  HmacMd5Context  Pointer to HMAC-MD5 context being initialized.
  @param[in]   Key             Pointer to the user-supplied key.
  @param[in]   KeySize         Key size in bytes.

  @retval TRUE   HMAC-MD5 context initialization succeeded.
  @retval FALSE  HMAC-MD5 context initialization failed.

**/
BOOLEAN
EFIAPI
HmacMd5Init (
  OUT  VOID         *HmacMd5Context,
  IN   CONST UINT8  *Key,
  IN   UINTN        KeySize
  )
{
  //
  // Check input parameters.
  //
  if (HmacMd5Context == NULL || KeySize > INT_MAX) {
    return FALSE;
  }

  //
  // OpenSSL HMAC-MD5 Context Initialization
  //
  HMAC_CTX_init (HmacMd5Context);
  HMAC_Init_ex (HmacMd5Context, Key, (UINT32) KeySize, EVP_md5(), NULL);

  return TRUE;
}
示例#10
0
static int hmac_fnew(lua_State *L)
{
  HANDLER_HMAC *c = hmac_pnew(L);
  const char *s = luaL_checkstring(L, 1);
  size_t k_len;
  const char *k = luaL_checklstring(L, 2, &k_len);
  DIGEST_TYPE type = DIGEST_BY_NAME(s);
 
  if (IS_DIGEST_INVALID(type)) {
    luaL_argerror(L, 1, "invalid digest type");
    return 0;
  }

#if CRYPTO_OPENSSL
  HMAC_CTX_init(c);
  HMAC_Init_ex(c, k, k_len, type, NULL);
#elif CRYPTO_GCRYPT
  gcry_md_open(c, type, GCRY_MD_FLAG_HMAC);
  gcry_md_setkey(*c, k, k_len);
#endif
  
  return 1;
}
示例#11
0
/** Calculate HMAC using OpenSSL's MD5 implementation
 *
 * @param digest Caller digest to be filled in.
 * @param in Pointer to data stream.
 * @param inlen length of data stream.
 * @param key Pointer to authentication key.
 * @param key_len Length of authentication key.
 *
 */
void fr_hmac_md5(uint8_t digest[MD5_DIGEST_LENGTH], uint8_t const *in, size_t inlen,
		 uint8_t const *key, size_t key_len)
{
	HMAC_CTX *ctx;

	if (unlikely(!md5_hmac_ctx)) {
		ctx = HMAC_CTX_new();
		if (unlikely(!ctx)) return;
		fr_thread_local_set_destructor(md5_hmac_ctx, _hmac_md5_ctx_free_on_exit, ctx);
	} else {
		ctx = md5_hmac_ctx;
	}

#ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
	/* Since MD5 is not allowed by FIPS, explicitly allow it. */
	HMAC_CTX_set_flags(ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
#endif /* EVP_MD_CTX_FLAG_NON_FIPS_ALLOW */

	HMAC_Init_ex(ctx, key, key_len, EVP_md5(), NULL);
	HMAC_Update(ctx, in, inlen);
	HMAC_Final(ctx, digest, NULL);
	HMAC_CTX_reset(ctx);
}
示例#12
0
char* CryptoHandler::hmac_sha512(char* datain, char* keyin, const bool& base64)
{
	unsigned char* key = (unsigned char*) keyin;
	unsigned char* data = (unsigned char*) datain;
	unsigned char* result;
	unsigned int result_len = 64;

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

	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();

	HMAC_CTX_init(&ctx);
	HMAC_Init_ex(&ctx, key, strlen(keyin), EVP_sha512(), NULL);
	HMAC_Update(&ctx, data, strlen(datain));
	HMAC_Final(&ctx, result, &result_len);
	HMAC_CTX_cleanup(&ctx);

	if(base64)
		return base64encode(result,result_len);
	return (char*)result;
}
示例#13
0
/**
  Initializes user-supplied memory pointed by HmacSha1Context as HMAC-SHA1 context for
  subsequent use.

  If HmacSha1Context is NULL, then return FALSE.

  @param[out]  HmacSha1Context  Pointer to HMAC-SHA1 context being initialized.
  @param[in]   Key              Pointer to the user-supplied key.
  @param[in]   KeySize          Key size in bytes.

  @retval TRUE   HMAC-SHA1 context initialization succeeded.
  @retval FALSE  HMAC-SHA1 context initialization failed.

**/
BOOLEAN
EFIAPI
HmacSha1Init (
  OUT  VOID         *HmacSha1Context,
  IN   CONST UINT8  *Key,
  IN   UINTN        KeySize
  )
{
  //
  // Check input parameters.
  //
  if (HmacSha1Context == NULL) {
    return FALSE;
  }

  //
  // OpenSSL HMAC-SHA1 Context Initialization
  //
  HMAC_CTX_init (HmacSha1Context);
  HMAC_Init_ex (HmacSha1Context, Key, (UINT32) KeySize, EVP_sha1(), NULL);

  return TRUE;
}
示例#14
0
文件: mac.c 项目: msftguy/openssh-sc
int
mac_init(Mac *mac)
{
	if (mac->key == NULL)
		fatal("mac_init: no key");
	switch (mac->type) {
	case SSH_EVP:
		if (mac->evp_md == NULL)
			return -1;
	#ifdef HAVE_HMAC_CTX_INIT
		HMAC_CTX_init(&mac->evp_ctx);
		HMAC_Init_ex(&mac->evp_ctx, mac->key, mac->key_len, mac->evp_md, NULL);
	#else
		HMAC_Init(&mac->evp_ctx, mac->key, mac->key_len, mac->evp_md);
	#endif
		return 0;
	case SSH_UMAC:
		mac->umac_ctx = umac_new(mac->key);
		return 0;
	default:
		return -1;
	}
}
示例#15
0
文件: hmac.c 项目: AndreV84/openssl
unsigned char *HMAC(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 = NULL;
    static unsigned char m[EVP_MAX_MD_SIZE];

    if (md == NULL)
        md = m;
    if ((c = HMAC_CTX_new()) == NULL)
        goto err;
    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_free(c);
    return md;
err:
    HMAC_CTX_free(c);
    return NULL;
}
示例#16
0
文件: hmac512.cpp 项目: nunb/btceQ
extern "C" K qHMAC512(K data, K key)
{
    unsigned int SHA512_DIGEST_LENGTH=64;
    unsigned char md[SHA512_DIGEST_LENGTH];
    unsigned char result[SHA512_DIGEST_LENGTH];
    unsigned int len=0;


    K ret = ktn(KG,SHA512_DIGEST_LENGTH);

    HMAC_CTX ctx;
    HMAC_CTX_init(&ctx);

    HMAC_Init_ex(&ctx, key->s, strlen(key->s), EVP_sha512(), NULL);
    HMAC_Update(&ctx, (unsigned char*)(data->s), strlen(data->s));
    HMAC_Final(&ctx, result, &len);
    HMAC_CTX_cleanup(&ctx);


    for(int i=0; i < len ; i++)
        kG(ret)[i]=result[i];

    return (ret);
}
示例#17
0
static void writeChunk(FileVaultInfo* info) {
	unsigned char buffer[info->blockSize];
	unsigned char buffer2[info->blockSize];
	unsigned char msgDigest[FILEVAULT_MSGDGST_LENGTH];
	uint32_t msgDigestLen;
	uint32_t myChunk;

	myChunk = info->curChunk;

	FLIPENDIAN(myChunk);
	HMAC_Init_ex(&(info->hmacCTX), NULL, 0, NULL, NULL);
	HMAC_Update(&(info->hmacCTX), (unsigned char *) &myChunk, sizeof(uint32_t));
	HMAC_Final(&(info->hmacCTX), msgDigest, &msgDigestLen);

	AES_cbc_encrypt(info->chunk, buffer, info->blockSize, &(info->aesEncKey), msgDigest, AES_ENCRYPT);

	info->file->seek(info->file, (info->curChunk * info->blockSize) + info->dataOffset);
	info->file->read(info->file, buffer2, info->blockSize);

	info->file->seek(info->file, (info->curChunk * info->blockSize) + info->dataOffset);
	info->file->write(info->file, buffer, info->blockSize);

	info->dirty = FALSE;
}
示例#18
0
static int
srp_init_hmac(
    HMAC_CTX *phctx,
    unsigned char *key,
    int key_len)
{
    int sts = 0;
    HMAC_CTX hctx;
    unsigned char md[40] = {0};
    unsigned int mdlen = 0;

    memset(&hctx, 0, sizeof(hctx));
    HMAC_CTX_init(&hctx);
    sts = HMAC_Init_ex(&hctx, key, key_len, EVP_sha1(), NULL);
    if (sts == 0)
    {
        return sts;
    }
    HMAC_Update(&hctx, "", 0);
    HMAC_Final(&hctx, md, &mdlen);

    *phctx = hctx;
    return 0;
}
void hash(char data[]) {
    // The secret key for hashing
    const char key[] = "12345678";
 
    // 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);
 
}
示例#20
0
/* Generate a MAC */
int PKCS12_gen_mac(PKCS12 *p12, const char *pass, int passlen,
       unsigned char *mac, unsigned int *maclen)
{
  const EVP_MD *md_type;
  HMAC_CTX hmac;
  unsigned char key[PKCS12_MAC_KEY_LENGTH], *salt;
  int saltlen, iter;

  if (!PKCS7_type_is_data(p12->authsafes))
    {
    PKCS12err(PKCS12_F_PKCS12_GEN_MAC,PKCS12_R_CONTENT_TYPE_NOT_DATA);
    return 0;
    }

  salt = p12->mac->salt->data;
  saltlen = p12->mac->salt->length;
  if (!p12->mac->iter) iter = 1;
  else iter = ASN1_INTEGER_get (p12->mac->iter);
      if(!(md_type =
     EVP_get_digestbyobj (p12->mac->dinfo->algor->algorithm))) {
    PKCS12err(PKCS12_F_PKCS12_GEN_MAC,PKCS12_R_UNKNOWN_DIGEST_ALGORITHM);
    return 0;
  }
  if(!PKCS12_key_gen (pass, passlen, salt, saltlen, PKCS12_MAC_ID, iter,
         PKCS12_MAC_KEY_LENGTH, key, md_type)) {
    PKCS12err(PKCS12_F_PKCS12_GEN_MAC,PKCS12_R_KEY_GEN_ERROR);
    return 0;
  }
  HMAC_CTX_init(&hmac);
  HMAC_Init_ex(&hmac, key, PKCS12_MAC_KEY_LENGTH, md_type, NULL);
      HMAC_Update(&hmac, p12->authsafes->d.data->data,
           p12->authsafes->d.data->length);
      HMAC_Final(&hmac, mac, maclen);
      HMAC_CTX_cleanup(&hmac);
  return 1;
}
示例#21
0
void
hmac_ctx_reset (HMAC_CTX *ctx)
{
  HMAC_Init_ex (ctx, NULL, 0, NULL, NULL);
}
示例#22
0
/* seed1 through seed5 are virtually concatenated */
static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
			int sec_len,
			const void *seed1, int seed1_len,
			const void *seed2, int seed2_len,
			const void *seed3, int seed3_len,
			const void *seed4, int seed4_len,
			const void *seed5, int seed5_len,
			unsigned char *out, int olen)
	{
	int chunk;
	unsigned int j;
	HMAC_CTX ctx;
	HMAC_CTX ctx_tmp;
	unsigned char A1[EVP_MAX_MD_SIZE];
	unsigned int A1_len;
	int ret = 0;
	
	chunk=EVP_MD_size(md);
	TINYCLR_SSL_ASSERT(chunk >= 0);

	HMAC_CTX_init(&ctx);
	HMAC_CTX_init(&ctx_tmp);
	if (!HMAC_Init_ex(&ctx,sec,sec_len,md, NULL))
		goto err;
	if (!HMAC_Init_ex(&ctx_tmp,sec,sec_len,md, NULL))
		goto err;
	if (seed1 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed1,seed1_len))
		goto err;
	if (seed2 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed2,seed2_len))
		goto err;
	if (seed3 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed3,seed3_len))
		goto err;
	if (seed4 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed4,seed4_len))
		goto err;
	if (seed5 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed5,seed5_len))
		goto err;
	if (!HMAC_Final(&ctx,A1,&A1_len))
		goto err;

	for (;;)
		{
		if (!HMAC_Init_ex(&ctx,NULL,0,NULL,NULL)) /* re-init */
			goto err;
		if (!HMAC_Init_ex(&ctx_tmp,NULL,0,NULL,NULL)) /* re-init */
			goto err;
		if (!HMAC_Update(&ctx,A1,A1_len))
			goto err;
		if (!HMAC_Update(&ctx_tmp,A1,A1_len))
			goto err;
		if (seed1 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed1,seed1_len))
			goto err;
		if (seed2 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed2,seed2_len))
			goto err;
		if (seed3 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed3,seed3_len))
			goto err;
		if (seed4 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed4,seed4_len))
			goto err;
		if (seed5 != NULL && !HMAC_Update(&ctx,(const unsigned char*)seed5,seed5_len))
			goto err;

		if (olen > chunk)
			{
			if (!HMAC_Final(&ctx,out,&j))
				goto err;
			out+=j;
			olen-=j;
			if (!HMAC_Final(&ctx_tmp,A1,&A1_len)) /* calc the next A1 value */
				goto err;
			}
		else	/* last one */
			{
			if (!HMAC_Final(&ctx,A1,&A1_len))
				goto err;
			TINYCLR_SSL_MEMCPY(out,A1,olen);
			break;
			}
		}
	ret = 1;
err:
	HMAC_CTX_cleanup(&ctx);
	HMAC_CTX_cleanup(&ctx_tmp);
	OPENSSL_cleanse(A1,sizeof(A1));
	return ret;
	}
示例#23
0
int main(int argc, char *argv[]) {
  FILE *in, *out;
  cencrypted_v1_header v1header;
  cencrypted_v2_pwheader v2header;

  uint8_t hmacsha1_key[20], aes_key[16], inbuf[CHUNK_SIZE], outbuf[CHUNK_SIZE];
  uint32_t chunk_no;
  int hdr_version, c,i, optError = 0;
  char inFile[512], outFile[512], passphrase[512];
  int iflag = 0, oflag = 0, pflag = 0, kflag = 0, verbose = 0;
  extern char *optarg;
  extern int optind, optopt;

  memset(inFile, 0, 512);
  memset(outFile, 0, 512);
  memset(passphrase, 0, 512);

  while((c = getopt(argc, argv, "hvi:o:p:k:")) != -1) {
    switch(c) {
    case 'h':
      usage("Help is on the way. Stay calm.");
      break;
    case 'v':
      verbose++;
      break;
    case 'i':
      if(optarg) strncpy(inFile, optarg, sizeof(inFile)-1);
      iflag = 1;
      break;
    case 'o':
      if (optarg) strncpy(outFile, optarg, sizeof(outFile)-1);
      oflag = 1;
      break;
    case 'p':
      if (optarg) strncpy(passphrase, optarg, sizeof(passphrase)-1);
      pflag = 1;
      break;
    case 'k':
      convert_hex(optarg, aes_key, 16);
      convert_hex(optarg+32, hmacsha1_key, 20);
      kflag=1;
      break;
    case '?':
      fprintf(stderr, "Unknown option: -%c\n", optopt);
      optError++;
      break;
    }
  }

  /* check to see if our user gave incorrect options */
  if (optError) usage("Incorrect arguments.");

  if (strlen(inFile) == 0) {
    in = stdin;
  } else {
    if ((in = fopen(inFile, "rb")) == NULL) {
      fprintf(stderr, "Error: unable to open %s\n", inFile);
      exit(1);
    }
  }

  if (strlen(outFile) == 0) {
    out = stdout;
  } else {
    if ((out = fopen(outFile, "wb")) == NULL) {
      fprintf(stderr, "Error: unable to open %s\n", outFile);
      exit(1);
    }
  }

  if (!pflag && !kflag) {
    fprintf(stderr, "No Passphrase given.\n");
    exit(1);
  }

  hdr_version = determine_header_version(in);

  if (verbose >= 1) {
    if (hdr_version > 0) {
      fprintf(stderr, "v%d header detected.\n", hdr_version);
    } else {
      fprintf(stderr, "unknown format.\n");
      exit(1);
    }
  }

  if (hdr_version == 1) {
    fseek(in, (long) -sizeof(cencrypted_v1_header), SEEK_END);
    if (fread(&v1header, sizeof(cencrypted_v1_header), 1, in) < 1) {
      fprintf(stderr, "header corrupted?\n"), exit(1);
    }
    adjust_v1_header_byteorder(&v1header);
    if(!kflag) unwrap_v1_header(passphrase, &v1header, aes_key, hmacsha1_key);
  }

  if (hdr_version == 2) {
    fseek(in, 0L, SEEK_SET);
    if (fread(&v2header, sizeof(cencrypted_v2_pwheader), 1, in) < 1) {
      fprintf(stderr, "header corrupted?\n"), exit(1);
    }
    adjust_v2_header_byteorder(&v2header);
    dump_v2_header(&v2header);
    if(!kflag) unwrap_v2_header(passphrase, &v2header, aes_key, hmacsha1_key);
    CHUNK_SIZE = v2header.blocksize;
  }

  HMAC_CTX_init(&hmacsha1_ctx);
  HMAC_Init_ex(&hmacsha1_ctx, hmacsha1_key, sizeof(hmacsha1_key), EVP_sha1(), NULL);
  AES_set_decrypt_key(aes_key, CIPHER_KEY_LENGTH * 8, &aes_decrypt_key);

  if (verbose >= 1) {
    fprintf(stderr, "AES Key: \n");
    print_hex(aes_key, 16);
    fprintf(stderr, "SHA1 seed: \n");
    print_hex(hmacsha1_key, 20);
  }

  if (hdr_version == 2) fseek(in, v2header.dataoffset, SEEK_SET);
  else fseek(in, 0L, SEEK_SET);

  chunk_no = 0;
  while(fread(inbuf, CHUNK_SIZE, 1, in) > 0) {
    decrypt_chunk(inbuf, outbuf, chunk_no);
    chunk_no++;
    if(hdr_version == 2 && (v2header.datasize-ftell(out)) < CHUNK_SIZE) {
      fwrite(outbuf, v2header.datasize - ftell(out), 1, out);
      break;
    }
    fwrite(outbuf, CHUNK_SIZE, 1, out);
  }

  if (verbose)  fprintf(stderr, "%d chunks written\n", chunk_no);
  return(0);
}
示例#24
0
文件: hmac.c 项目: skaligotla/openssl
int HMAC_Init(HMAC_CTX *ctx, const void *key, int len, const EVP_MD *md)
{
    if (key && md)
        HMAC_CTX_reset(ctx);
    return HMAC_Init_ex(ctx, key, len, md, NULL);
}
示例#25
0
文件: Hmac.cpp 项目: Phatcat/mangos
void HmacHash::Initialize()
{
    HMAC_Init_ex(&m_ctx, &m_key, SEED_KEY_SIZE, EVP_sha1(), NULL);
}
示例#26
0
void crypto_hmac_sha1_init(CryptoHmac hmac, const uint8* data, uint32 length)
{
	HMAC_Init_ex(&hmac->hmac_ctx, data, length, EVP_sha1(), NULL);
}
示例#27
0
static int hmac_reset(lua_State *L)
{
  HMAC_CTX *c = (HMAC_CTX*)luaL_checkudata(L, 1, LUACRYPTO_HMACNAME);
  HMAC_Init_ex(c, NULL, 0, NULL, NULL);
  return 0;
}
示例#28
0
文件: ntlm.c 项目: Auto-Droid/FreeRDP
SECURITY_STATUS SEC_ENTRY ntlm_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, ULONG MessageSeqNo, PULONG pfQOP)
{
	int index;
	int length;
	void* data;
	UINT32 SeqNo;
	HMAC_CTX hmac;
	BYTE digest[16];
	BYTE checksum[8];
	UINT32 version = 1;
	NTLM_CONTEXT* context;
	BYTE expected_signature[16];
	PSecBuffer data_buffer = NULL;
	PSecBuffer signature_buffer = NULL;

	SeqNo = (UINT32) MessageSeqNo;
	context = (NTLM_CONTEXT*) sspi_SecureHandleGetLowerPointer(phContext);

	for (index = 0; index < (int) pMessage->cBuffers; index++)
	{
		if (pMessage->pBuffers[index].BufferType == SECBUFFER_DATA)
			data_buffer = &pMessage->pBuffers[index];
		else if (pMessage->pBuffers[index].BufferType == SECBUFFER_TOKEN)
			signature_buffer = &pMessage->pBuffers[index];
	}

	if (!data_buffer)
		return SEC_E_INVALID_TOKEN;

	if (!signature_buffer)
		return SEC_E_INVALID_TOKEN;

	/* Copy original data buffer */
	length = data_buffer->cbBuffer;
	data = malloc(length);

	if (!data)
		return SEC_E_INSUFFICIENT_MEMORY;

	CopyMemory(data, data_buffer->pvBuffer, length);

	/* Decrypt message using with RC4, result overwrites original buffer */

	if (context->confidentiality)
		RC4(&context->RecvRc4Seal, length, (BYTE*) data, (BYTE*) data_buffer->pvBuffer);
	else
		CopyMemory(data_buffer->pvBuffer, data, length);

	/* Compute the HMAC-MD5 hash of ConcatenationOf(seq_num,data) using the client signing key */
	HMAC_CTX_init(&hmac);
	HMAC_Init_ex(&hmac, context->RecvSigningKey, 16, EVP_md5(), NULL);
	HMAC_Update(&hmac, (void*) &(SeqNo), 4);
	HMAC_Update(&hmac, (void*) data_buffer->pvBuffer, data_buffer->cbBuffer);
	HMAC_Final(&hmac, digest, NULL);
	HMAC_CTX_cleanup(&hmac);

#ifdef WITH_DEBUG_NTLM
	fprintf(stderr, "Encrypted Data Buffer (length = %d)\n", length);
	winpr_HexDump(data, length);
	fprintf(stderr, "\n");

	fprintf(stderr, "Data Buffer (length = %d)\n", (int) data_buffer->cbBuffer);
	winpr_HexDump(data_buffer->pvBuffer, data_buffer->cbBuffer);
	fprintf(stderr, "\n");
#endif

	free(data);

	/* RC4-encrypt first 8 bytes of digest */
	RC4(&context->RecvRc4Seal, 8, digest, checksum);

	/* Concatenate version, ciphertext and sequence number to build signature */
	CopyMemory(expected_signature, (void*) &version, 4);
	CopyMemory(&expected_signature[4], (void*) checksum, 8);
	CopyMemory(&expected_signature[12], (void*) &(SeqNo), 4);
	context->RecvSeqNum++;

	if (memcmp(signature_buffer->pvBuffer, expected_signature, 16) != 0)
	{
		/* signature verification failed! */
		fprintf(stderr, "signature verification failed, something nasty is going on!\n");

		fprintf(stderr, "Expected Signature:\n");
		winpr_HexDump(expected_signature, 16);
		fprintf(stderr, "Actual Signature:\n");
		winpr_HexDump((BYTE*) signature_buffer->pvBuffer, 16);

		return SEC_E_MESSAGE_ALTERED;
	}

	return SEC_E_OK;
}
示例#29
0
/* tls_decrypt_ticket attempts to decrypt a session ticket.
 *
 *   etick: points to the body of the session ticket extension.
 *   eticklen: the length of the session tickets extenion.
 *   sess_id: points at the session ID.
 *   sesslen: the length of the session ID.
 *   psess: (output) on return, if a ticket was decrypted, then this is set to
 *       point to the resulting session.
 *
 * Returns:
 *   -1: fatal error, either from parsing or decrypting the ticket.
 *    2: the ticket couldn't be decrypted.
 *    3: a ticket was successfully decrypted and *psess was set.
 *    4: same as 3, but the ticket needs to be renewed.
 */
static int
tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen,
    const unsigned char *sess_id, int sesslen, SSL_SESSION **psess)
{
	SSL_SESSION *sess;
	unsigned char *sdec;
	const unsigned char *p;
	int slen, mlen, renew_ticket = 0;
	unsigned char tick_hmac[EVP_MAX_MD_SIZE];
	HMAC_CTX hctx;
	EVP_CIPHER_CTX ctx;
	SSL_CTX *tctx = s->initial_ctx;

	/*
	 * The API guarantees EVP_MAX_IV_LENGTH bytes of space for
	 * the iv to tlsext_ticket_key_cb().  Since the total space
	 * required for a session cookie is never less than this,
	 * this check isn't too strict.  The exact check comes later.
	 */
	if (eticklen < 16 + EVP_MAX_IV_LENGTH)
		return 2;

	/* Initialize session ticket encryption and HMAC contexts */
	HMAC_CTX_init(&hctx);
	EVP_CIPHER_CTX_init(&ctx);
	if (tctx->internal->tlsext_ticket_key_cb) {
		unsigned char *nctick = (unsigned char *)etick;
		int rv = tctx->internal->tlsext_ticket_key_cb(s,
		    nctick, nctick + 16, &ctx, &hctx, 0);
		if (rv < 0) {
			HMAC_CTX_cleanup(&hctx);
			EVP_CIPHER_CTX_cleanup(&ctx);
			return -1;
		}
		if (rv == 0) {
			HMAC_CTX_cleanup(&hctx);
			EVP_CIPHER_CTX_cleanup(&ctx);
			return 2;
		}
		if (rv == 2)
			renew_ticket = 1;
	} else {
		/* Check key name matches */
		if (timingsafe_memcmp(etick,
		    tctx->internal->tlsext_tick_key_name, 16))
			return 2;
		HMAC_Init_ex(&hctx, tctx->internal->tlsext_tick_hmac_key,
		    16, tlsext_tick_md(), NULL);
		EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
		    tctx->internal->tlsext_tick_aes_key, etick + 16);
	}

	/*
	 * Attempt to process session ticket, first conduct sanity and
	 * integrity checks on ticket.
	 */
	mlen = HMAC_size(&hctx);
	if (mlen < 0) {
		HMAC_CTX_cleanup(&hctx);
		EVP_CIPHER_CTX_cleanup(&ctx);
		return -1;
	}

	/* Sanity check ticket length: must exceed keyname + IV + HMAC */
	if (eticklen <= 16 + EVP_CIPHER_CTX_iv_length(&ctx) + mlen) {
		HMAC_CTX_cleanup(&hctx);
		EVP_CIPHER_CTX_cleanup(&ctx);
		return 2;
	}
	eticklen -= mlen;

	/* Check HMAC of encrypted ticket */
	if (HMAC_Update(&hctx, etick, eticklen) <= 0 ||
	    HMAC_Final(&hctx, tick_hmac, NULL) <= 0) {
		HMAC_CTX_cleanup(&hctx);
		EVP_CIPHER_CTX_cleanup(&ctx);
		return -1;
	}

	HMAC_CTX_cleanup(&hctx);
	if (timingsafe_memcmp(tick_hmac, etick + eticklen, mlen)) {
		EVP_CIPHER_CTX_cleanup(&ctx);
		return 2;
	}

	/* Attempt to decrypt session data */
	/* Move p after IV to start of encrypted ticket, update length */
	p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx);
	eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx);
	sdec = malloc(eticklen);
	if (sdec == NULL ||
	    EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen) <= 0) {
		free(sdec);
		EVP_CIPHER_CTX_cleanup(&ctx);
		return -1;
	}
	if (EVP_DecryptFinal_ex(&ctx, sdec + slen, &mlen) <= 0) {
		free(sdec);
		EVP_CIPHER_CTX_cleanup(&ctx);
		return 2;
	}
	slen += mlen;
	EVP_CIPHER_CTX_cleanup(&ctx);
	p = sdec;

	sess = d2i_SSL_SESSION(NULL, &p, slen);
	free(sdec);
	if (sess) {
		/* The session ID, if non-empty, is used by some clients to
		 * detect that the ticket has been accepted. So we copy it to
		 * the session structure. If it is empty set length to zero
		 * as required by standard.
		 */
		if (sesslen)
			memcpy(sess->session_id, sess_id, sesslen);
		sess->session_id_length = sesslen;
		*psess = sess;
		if (renew_ticket)
			return 4;
		else
			return 3;
	}
	ERR_clear_error();
	/* For session parse failure, indicate that we need to send a new
	 * ticket. */
	return 2;
}
示例#30
0
static int ntlm2_auth(krb5_context context, struct kcrap_auth_req_data *req,
                      int *errnum,
                      krb5_data *error_data, struct kcrap_data *extra)
{
	int retval;
	int nkeys;
	struct keyblocks keyblocks[5];
	HMAC_CTX *ctx;
	unsigned char *tmpbuf;
	int i, j;
	unsigned char v2hash[EVP_MAX_MD_SIZE];
	unsigned int v2hlen;
	unsigned char resp[EVP_MAX_MD_SIZE];
	unsigned int resplen;

	if (req->server_challenge.length < 1) {
		*errnum = EINVAL;
		error_data->data = strdup("Invalid server challenge length");
		error_data->length = strlen(error_data->data);
		return 0;
	}

	if (req->client_challenge.length < 1) {
		*errnum = EINVAL;
		error_data->data = strdup("Invalid client challenge length");
		error_data->length = strlen(error_data->data);
		return 0;
	}

	if (req->response.length != 16) {
		*errnum = EINVAL;
		error_data->data = strdup("Invalid response length");
		error_data->length = strlen(error_data->data);
		return 0;
	}

	nkeys = sizeof(keyblocks) / sizeof(struct keyblocks);

	if ((retval = kcrap_getkey(context, req->principal, ENCTYPE_ARCFOUR_HMAC,
	                           &nkeys,
	                           keyblocks)))
		goto fail0;

	tmpbuf = malloc((req->principal.length + req->alt_username.length) * 2);

	if (tmpbuf == NULL) {
		retval = errno;
		perror("malloc");
		goto fail;
	}

	j = 0;

	for(i = 0; i < req->principal.length; i++) {
		tmpbuf[j++] = toupper(req->principal.data[i]);
		tmpbuf[j++] = 0;
	}

	for(i = 0; i < req->alt_username.length; i++) {
		tmpbuf[j++] = req->alt_username.data[i];
		tmpbuf[j++] = 0;
	}


	for (i = 0; i < nkeys; i++) {
		if (keyblocks[i].key.length != 16) continue;

		HMAC(EVP_md5(), (unsigned char*)keyblocks[i].key.contents, 16, tmpbuf, j,
		     v2hash,
		     &v2hlen);

#ifdef DEBUG_PASSWORD
		fprintf(stderr, "principal:\n");
		dump_data(tmpbuf, j);
		fprintf(stderr, "principal hash:\n");
		dump_data(v2hash, v2hlen);
#endif

		ctx = HMAC_CTX_new();
		HMAC_Init_ex(ctx, v2hash, v2hlen, EVP_md5(), NULL);
		HMAC_Update(ctx, (unsigned char*)req->server_challenge.data,
		            req->server_challenge.length);
		HMAC_Update(ctx, (unsigned char*)req->client_challenge.data,
		            req->client_challenge.length);
		HMAC_Final(ctx, resp, &resplen);
		HMAC_CTX_free(ctx);

		if (resplen != 16) {
			if (tmpbuf) free(tmpbuf);

			for (i = 0; i < nkeys; i++)
				krb5_free_keyblock_contents(context, &keyblocks[i].key);

			*errnum = KRB5_CRYPTO_INTERNAL;
			error_data->data = strdup("Server internal error: NTLMv2 resplen != 16");
			error_data->length = strlen(error_data->data);
			return 0;
		}

#ifdef DEBUG_PASSWORD
		fprintf(stderr, "server challenge:\n");
		dump_data(req->server_challenge.data, req->server_challenge.length);
		fprintf(stderr, "client challenge:\n");
		dump_data(req->client_challenge.data, req->client_challenge.length);
		fprintf(stderr, "expected response:\n");
		dump_data(resp, resplen);
		fprintf(stderr, "client response:\n");
		dump_data(req->response.data, req->response.length);
#endif

		if (memcmp(resp, req->response.data, 16) == 0) {
			*errnum = 0;
			goto ok;
		}
	}

	for (i = 0; i < nkeys; i++)
		krb5_free_keyblock_contents(context, &keyblocks[i].key);

	*errnum = 0;
	error_data->data = strdup("Invalid response");
	error_data->length = strlen(error_data->data);
	return 0;

ok:

	if (tmpbuf) free(tmpbuf);

	for (i = 0; i < nkeys; i++)
		krb5_free_keyblock_contents(context, &keyblocks[i].key);

	return KCRAP_AUTH_OK;

fail:

	if (tmpbuf) free(tmpbuf);

	for (i = 0; i < nkeys; i++)
		krb5_free_keyblock_contents(context, &keyblocks[i].key);

fail0:
	*errnum = retval;
	error_data->data = strdup(error_message(retval));
	error_data->length = strlen(error_data->data);
	return 0;
}