Example #1
0
/*
 * --tls-auth is read in do_init_crypto_tls_c1() in src/vpn/init.c
 * by calling get_tls_handshake_key()
 * init_key_ctx()
 */
openvpn_encrypt(ovStruct_t *ovP, uchar *ptr, int length, int hmac_index) {
	uchar tmpPtr[5000];
	int tmpLen, i;
	uchar *hash;

	// 5th line for outgoing from server
	//uchar key[] = "\x25\x21\x1f\x2f\x4e\x2a\x50\x0d\x13\x3f\x19\xe2\x4c\xd5\xf5\x06\xc0\xa7\xe6\xf0";
	// 13th line for incoming into server
	uchar key[] = "\xac\x3c\x20\xbb\xb7\x54\x8d\x9a\x8d\x9c\x9f\xdd\x76\xde\x22\x14\x25\xfc\xcc\x07";

	memcpy(tmpPtr, ptr, length);
	memcpy(&tmpPtr[28], &tmpPtr[0], 9);
	tmpLen = length-28;
	// Copy pkt id + timestamp to the start of the pkt
	memcpy(&tmpPtr[20], &ptr[29], 8);
	tmpLen += 8;
	log_info(fp, "openvpn_encrypt: HMAC at:%d in pkt of len:%d, newlen:%d",
			hmac_index, length, tmpLen);
	fflush(fp);
	// Note that both the following HMAC versions work. Either way can be used.
	// Both have been tested with the openvpn_as server.
	{
	hash = HMAC(EVP_sha1(), key, strlen(key), &tmpPtr[20], tmpLen, NULL, NULL);
	}
	/*
	{
	unsigned char hash[SHA_DIGEST_LENGTH];
	uchar *output = NULL;
    HMAC_CTX hmac;
    unsigned int in_hmac_len = 0;
	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();

	HMAC_CTX_init(&hmac);
    HMAC_Init_ex(&hmac, key, 20, EVP_sha1(), NULL);
    HMAC_Update(&hmac,  &tmpPtr[20], tmpLen);
    HMAC_Final(&hmac, hash, &in_hmac_len);
    HMAC_CTX_cleanup(&hmac);
	}*/
	
	// hash now contains the 20-byte SHA-1 hash
	memcpy(&ptr[hmac_index], hash, SHA_DIGEST_LENGTH);
#if DEBUG
	printf("\n HMAC KEY: ");
	for (i=0;i<20;i++)
		printf("%2x ",key[i]);
	printf("\n HMAC ON DATA: ");
	for (i=0;i<tmpLen;i++)
		printf("%2x ",tmpPtr[20+i]);
	printf("\n HMAC SHA1: ");
	for (i=0;i<20;i++)
		printf("%2x ",hash[i]);
#endif
}
Example #2
0
static int nr_ice_crypto_openssl_hmac_sha1(UCHAR *key, int key_l, UCHAR *buf, int buf_l, UCHAR digest[20]) {
  unsigned int rl;

  HMAC(EVP_sha1(),
    key, key_l, buf, buf_l, digest, &rl);

  if (rl != 20)
    ERETURN(R_INTERNAL);

  return 0;
}
Example #3
0
char *hmacSha1(char *key, char *data)
/* Calculate a openssl SHA1 keyed-hash message authentication code (HMAC) */
{
unsigned char* digest;
digest=HMAC(EVP_sha1(), key, strlen(key), (unsigned char*)data, strlen(data), NULL, NULL);
char hmacStr[40];
int i;
for(i = 0; i < 20; i++)
    sprintf(&hmacStr[i*2], "%02x", (unsigned int)digest[i]);
return cloneStringZ(hmacStr, sizeof(hmacStr));
}
Example #4
0
char *s3_sign_string(const S3 *s3,const char *string)
{
	unsigned char md[EVP_MAX_MD_SIZE];
	unsigned int md_len;

	if(!s3) return NULL;

	HMAC(EVP_sha1(),s3->secret_key,strlen(s3->secret_key),
		(unsigned char *)string,strlen(string),md,&md_len);
	return ne_base64(md,md_len);
}
Example #5
0
int32 DeriveKey(const void *key, int32 keyLen, const uchar *magic, int32 magicLen, uchar **result) {
	uchar hash1[EVP_MAX_MD_SIZE];
	uchar hash2[EVP_MAX_MD_SIZE];
	uchar hash3[EVP_MAX_MD_SIZE];
	uchar hash4[EVP_MAX_MD_SIZE];
	unsigned int hash1Len = 0;
	unsigned int hash2Len = 0;
	unsigned int hash3Len = 0;
	unsigned int hash4Len = 0;
	int32 length = B_ERROR;
	BMallocIO temp;
	
	// HMAC-SHA1(magic)
	HMAC(EVP_sha1(), key, keyLen, magic, magicLen, hash1, &hash1Len);

	// Key 2 is HMAC-SHA1(HMAC-SHA1(magic) + magic)
	temp.Write(hash1, hash1Len);
	temp.Write(magic, magicLen);
	HMAC(EVP_sha1(), key, keyLen, (uchar *)temp.Buffer(), temp.BufferLength(), hash2, &hash2Len);

	// HMAC-SHA1(HMAC-SHA1(magic))
	HMAC(EVP_sha1(), key, keyLen, hash1, hash1Len, hash3, &hash3Len);
			
	// Clear the BMallocIO and reset the position to 0
	temp.SetSize(0);
	temp.Seek(0, SEEK_SET);

	// Key 4 is HMAC-SHA1(HMAC-SHA1(HMAC-SHA1(magic)) + magic)
	temp.Write(hash3, hash3Len);
	temp.Write(magic, magicLen);
	HMAC(EVP_sha1(), key, keyLen, (uchar *)temp.Buffer(), temp.BufferLength(), hash4, &hash4Len);

	// The key is Hash2 followed by the first four bytes of Hash4
	length = hash2Len + 4;
	*result = (uchar *)calloc(length, sizeof(uchar));

	memcpy(*result, hash2, hash2Len);
	memcpy(*result + hash2Len, hash4, 4);
	
	return length;
};
Example #6
0
/* Anonymize a buffer of given length. Places the resulting digest into the
 * provided digest buffer, which must be at least ANONYMIZATION_DIGEST_LENGTH
 * bytes long. */
static int anonymization_process(const uint8_t* const data,
                                 const int len,
                                 unsigned char* const digest) {
#ifndef NDEBUG
  assert(initialized);
#endif

  if (!HMAC(EVP_sha1(), seed, ANONYMIZATION_SEED_LEN, data, len, digest, NULL)) {
    return -1;
  }
  return 0;
}
Example #7
0
char * zauthToken(unsigned long int gid, unsigned long int zid,time_t exp_time)
{
        char str[MAX],str_final[MAX],temp[MAX],str_sig[MAX];
         int len,len1;
        char *ret = (char *) malloc(1024 * sizeof(char *));
        sprintf(str, "%lu:%lu.%lu.AAAAAA==",gid,zid,(unsigned long int)exp_time);
        unsigned char *ptr = HMAC(EVP_sha256(),my.secret,strlen(my.secret),str,strlen(str),str_final,&len); // hmac--sha256 before base64 encoding....

        base64_enc(str_final,len,1,str_sig);                                                                    //base64 encoding to get signature
        sprintf(ret, "%s|%s\n",str,str_sig);
	return ret;
}
Example #8
0
rdpBlob* crypto_kdcmsg_cksum_hmacmd5(rdpBlob* msg, uint8* key, uint32 msgtype)
{
	rdpBlob* cksum;
	uint8* Ksign;
	uint8* tmpdata;
	uint8* tmp;
	CryptoMd5 md5;
	Ksign = xzalloc(16);
	tmp = xzalloc(16);
	cksum = xnew(rdpBlob);
	freerdp_blob_alloc(cksum, 16);
	tmpdata = xzalloc(msg->length + 4);
	HMAC(EVP_md5(), (void*) key, 16, (uint8*)"signaturekey\0", 13, (void*) Ksign, NULL);
	memcpy(tmpdata, (void*)&msgtype, 4);
	memcpy(tmpdata + 4, msg->data, msg->length);
	md5 = crypto_md5_init();
	crypto_md5_update(md5, tmpdata, msg->length + 4);
	crypto_md5_final(md5, tmp);
	HMAC(EVP_md5(), (void*) Ksign, 16, (uint8*)tmp, 16, (void*) cksum->data, NULL);
	return cksum;
}
Example #9
0
char *hmacMd5(char *key, char *data)
/* Calculate a openssl MD5 keyed-hash message authentication code (HMAC) */
{
unsigned char* digest;
digest=HMAC(EVP_md5(), key, strlen(key), (unsigned char*)data, strlen(data), NULL, NULL);
//printf("Raw mdr digest: %s\n", digest);
char hmacStr[32];
int i;
for(i = 0; i < 16; i++)
    sprintf(&hmacStr[i*2], "%02x", (unsigned int)digest[i]);
return cloneStringZ(hmacStr, sizeof(hmacStr));
}
int decrypt_and_verify_secrets(CPOR_key *key, unsigned char *input, size_t input_len, unsigned char *plaintext, size_t *plaintext_len, unsigned char *authenticator, size_t authenticator_len) {

    EVP_CIPHER_CTX ctx;
    EVP_CIPHER *cipher = NULL;
    unsigned char mac[EVP_MAX_MD_SIZE];
    size_t mac_size = EVP_MAX_MD_SIZE;
    int len;

    if(!key || !key->k_enc || !key->k_mac || !input || !input_len || !plaintext || !plaintext_len || !authenticator || !authenticator_len) return 0;

    OpenSSL_add_all_algorithms();
    memset(mac, 0, mac_size);

    /* Verify the HMAC-SHA1 */
    if(!HMAC(EVP_sha1(), key->k_mac, key->k_mac_size, input, input_len, mac, (unsigned int *)&mac_size)) goto cleanup;
    if(authenticator_len != mac_size) goto cleanup;
    if(memcmp(mac, authenticator, mac_size) != 0) goto cleanup;


    EVP_CIPHER_CTX_init(&ctx);
    switch(key->k_enc_size) {
    case 16:
        cipher = (EVP_CIPHER *)EVP_aes_128_cbc();
        break;
    case 24:
        cipher = (EVP_CIPHER *)EVP_aes_192_cbc();
        break;
    case 32:
        cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
        break;
    default:
        return 0;
    }
    if(!EVP_DecryptInit(&ctx, cipher, key->k_enc, NULL)) goto cleanup;

    *plaintext_len = 0;

    if(!EVP_DecryptUpdate(&ctx, plaintext, (int *)plaintext_len, input, input_len)) goto cleanup;
    EVP_DecryptFinal(&ctx, plaintext + *plaintext_len, &len);

    *plaintext_len += len;

    EVP_CIPHER_CTX_cleanup(&ctx);

    return 1;

cleanup:
    *plaintext_len = 0;

    return 0;

}
Example #11
0
int main(int argc, char **argv)
{
    Octstr *data, *filename, *mac, *key;
    unsigned char macbuf[EVP_MAX_MD_SIZE], *p;
    int mac_len;
#ifdef HAVE_LIBSSL
    HMAC_CTX ctx;
#endif

    gwlib_init();

    get_and_set_debugs(argc, argv, NULL);

    if (argc < 3)
        panic(0, "Syntax: %s <key> <file>\n", argv[0]);
  
    key = octstr_create(argv[1]);    
    filename = octstr_create(argv[2]);
    data = octstr_read_file(octstr_get_cstr(filename));

    if (data == NULL)
        panic(0, "Cannot read file.");

    debug("",0,"Dumping file `%s':", octstr_get_cstr(filename));
    octstr_dump(data, 0);

#ifdef HAVE_LIBSSL
    HMAC_Init(&ctx, octstr_get_cstr(key), octstr_len(key), EVP_sha1());
    p = HMAC(EVP_sha1(), octstr_get_cstr(key), octstr_len(key), 
         octstr_get_cstr(data), octstr_len(data), 
         macbuf, &mac_len);
    HMAC_cleanup(&ctx);
#else
    macbuf[0] = 0;
    mac_len = 0;
    p = macbuf;
    warning(0, "No SSL support. Can't calculate HMAC value.");
#endif
    
    mac = octstr_create_from_data(p, mac_len);
    octstr_binary_to_hex(mac, 0);
    
    debug("",0,"HMAC of file `%s' and key `%s' is:", 
          octstr_get_cstr(filename), octstr_get_cstr(key));
    octstr_dump(mac, 0);      

    octstr_destroy(data);
    octstr_destroy(mac);
    octstr_destroy(key);
    gwlib_shutdown();
    return 0;
}
Example #12
0
static unsigned char *HKDF_Extract(const EVP_MD *evp_md,
                                   const unsigned char *salt, size_t salt_len,
                                   const unsigned char *key, size_t key_len,
                                   unsigned char *prk, size_t *prk_len)
{
    unsigned int tmp_len;

    if (!HMAC(evp_md, salt, salt_len, key, key_len, prk, &tmp_len))
        return NULL;

    *prk_len = tmp_len;
    return prk;
}
Example #13
0
std::string computeHMAC(const std::string& input, const std::string& key) 
{	
    //DebugL << "Compute HMAC: input='" << util::dumpbin(input.c_str(), input.length()) 
	//	<< "', inputLength=" << input.length() << ", key='" << key << "', keyLength=" << key.length() << std::endl;
	unsigned int len = 0;
	char buf[20];	
	HMAC(EVP_sha1(), 
		key.c_str(), key.length(), 
        reinterpret_cast<const unsigned char*>(input.c_str()), input.length(), 
        reinterpret_cast<unsigned char*>(&buf), &len);
	assert(len == 20);
	return std::string(buf, len);
}
void
rdssl_hmac_md5(const void *key, int key_len, const unsigned char *msg, int msg_len,
	       unsigned char *md)
{
#if OPENSSL_VERSION_NUMBER < 0x10100000 || defined(LIBRESSL_VERSION_NUMBER)
	HMAC_CTX ctx;
	HMAC_CTX_init(&ctx);
#endif
	HMAC(EVP_md5(), key, key_len, msg, msg_len, md, NULL);
#if OPENSSL_VERSION_NUMBER < 0x10100000 || defined(LIBRESSL_VERSION_NUMBER)
	HMAC_CTX_cleanup(&ctx);
#endif
}
/*
 * Calculate the HMAC-SHA1 digest for a specified message with a defined key.
 *
 *	@parameters:	*pool		pool for memory allocation;
 *					*key		the hmac key;
 *					*message	the message to digest;
 *	
 *	@return	NGX_ERROR 	on error
 *			NGX_OK		on success
 */
static ngx_int_t
ngx_apikey_hamac_sha1_digest( ngx_pool_t *pool, ngx_str_t *key, ngx_str_t *message, ngx_str_t *digest ) {

	ngx_str_t	hmac_digest		= ngx_null_string;

	u_char		*last			= NULL;
	

	hmac_digest.len 	= EVP_MAX_MD_SIZE;
	hmac_digest.data = ngx_pcalloc( pool, EVP_MAX_MD_SIZE );
	if ( hmac_digest.data == NULL ) {
		ngx_log_error(NGX_LOG_ERR, pool->log, 0, "(%s) failed allocating memory", __func__ );
        return NGX_ERROR;
	}

	/*
	HMAC_CTX ctx;
	HMAC_Init( &ctx, key->data, sizeof(key->data), EVP_sha1() );
	HMAC_Update(&ctx,  message->data, sizeof(message->data));
 	HMAC_Final(&ctx, hmac_digest.data, &hmac_digest.len );		
	HMAC_cleanup(&ctx);
	*/
	
	last = HMAC (EVP_sha1 (), 
		(const void *)key->data, (int)key->len, 
		message->data, (int)message->len, 
		hmac_digest.data, (unsigned int *)&hmac_digest.len );

	if ( last == NULL ) {
		ngx_pfree( pool, hmac_digest.data );
		ngx_log_error(NGX_LOG_ERR, pool->log, 0, "(%s) failed calculating HMAC digest", __func__ );
        return NGX_ERROR;
	}
	
	digest->len  = EVP_MAX_MD_SIZE*2;
	digest->data = ngx_pcalloc( pool, digest->len + 1 );
    if ( digest->data == NULL ) {
		ngx_pfree( pool, hmac_digest.data );
		ngx_log_error(NGX_LOG_ERR, pool->log, 0, "(%s) failed allocating memory", __func__ );
        return NGX_ERROR;
	}
	
	ngx_hex_dump(digest->data, hmac_digest.data, hmac_digest.len);
	

	ngx_pfree( pool, hmac_digest.data );

	
	return NGX_OK;
}
Example #16
0
int Peer::attachHash(const void *data_begin, unsigned int data_len, void *hash_begin){
	//we suppose the hash value takes 20 bytes, if the length is not 20 bytes, return 1, if fail to generate hash, return -1
	unsigned int hash_len;
	if(HMAC(EVP_sha1(), this->key, this->key_len, (const unsigned char*)data_begin, data_len, (unsigned char *)hash_begin, &hash_len) == NULL){
			Helper::LiveWithUserMessage("HMAC()", "fail to generate server-side hash");
			return -1;
	}
	else if(hash_len != 20){
		Helper::LiveWithUserMessage("HMAC()", "generate an abnormal sha1(length not 20)");
		return 1;
	}
	else
		return 0;
}
Example #17
0
K hmac(K x,K y,K f) {
    int lenx,leny,lenf,i;
    lenx=x->n;
    leny=y->n;
    lenf=f->n;
    unsigned char secret[lenx+1];
    unsigned char message[leny+1];
    unsigned char hashfunction[lenf+1];

    // copy x and y into regular cstrings
    if(10==(x->t)){ for(i=0;i<lenx;i++){ secret[i]      =kC(x)[i]; } secret[lenx]=0;       }
    if(10==(y->t)){ for(i=0;i<leny;i++){ message[i]     =kC(y)[i]; } message[leny]=0;      }
    if(10==(f->t)){ for(i=0;i<lenf;i++){ hashfunction[i]=kC(f)[i]; } hashfunction[lenf]=0; }

    unsigned int bytelength;
    const EVP_MD* (*evp_fn)(void);
    if(strcmp("sha1",hashfunction)==0){
        bytelength=SHA_DIGEST_LENGTH;
        evp_fn=&EVP_sha1;
    } else if(strcmp("sha224",hashfunction)==0){
        bytelength=SHA224_DIGEST_LENGTH;
        evp_fn=&EVP_sha224;
    } else if(strcmp("sha256",hashfunction)==0){
        bytelength=SHA256_DIGEST_LENGTH;
        evp_fn=&EVP_sha256;
    } else if(strcmp("sha384",hashfunction)==0){
        bytelength=SHA384_DIGEST_LENGTH;
        evp_fn=&EVP_sha384;
    } else if(strcmp("sha512",hashfunction)==0){
        bytelength=SHA512_DIGEST_LENGTH;
        evp_fn=&EVP_sha512;
    } else if(strcmp("md5",hashfunction)==0){
        bytelength=MD5_DIGEST_LENGTH;
        evp_fn=&EVP_md5;
    } else{
        krr("Please choose a supported hash function");
        return (K)0;
    }

    unsigned char* result;
    result=calloc(bytelength,sizeof(char));
    HMAC(evp_fn(),secret,strlen(secret),message,strlen(message),result,NULL);

    K output=ktn(KG,bytelength);
    for(i=0;i<bytelength;i++){
        kG(output)[i]=result[i];
    }
    free(result);
    return output;
}
/* internal function */
OpcUa_StatusCode OpcUa_P_OpenSSL_PSHA256_Hash_Generate(
    OpcUa_P_OpenSSL_PSHA256_Ctx* a_pPsha256Context,
    OpcUa_Byte*              a_pHash)
{
    OpcUa_InitializeStatus(OpcUa_Module_P_OpenSSL, "PSHA256_Hash_Generate");

    OpcUa_ReturnErrorIfArgumentNull(a_pPsha256Context);

    /* Calculate P_SHA256(n) = HMAC_SHA256(secret, A(n)+seed) */
    HMAC(EVP_sha256(), OpcUa_P_OpenSSL_PSHA256_SECRET(a_pPsha256Context), a_pPsha256Context->secret_len,
                     (unsigned char*)a_pPsha256Context->A, sizeof(a_pPsha256Context->A) + a_pPsha256Context->seed_len,
                     a_pHash, OpcUa_Null);

    /* Calculate A(n) = HMAC_SHA256(secret, A(n-1)) */
    HMAC(EVP_sha256(), OpcUa_P_OpenSSL_PSHA256_SECRET(a_pPsha256Context), a_pPsha256Context->secret_len, (const unsigned char*)a_pPsha256Context->A, sizeof(a_pPsha256Context->A), (unsigned char*)a_pPsha256Context->A, (unsigned int*)OpcUa_Null);

    OpcUa_ReturnErrorIfNull(a_pHash, OpcUa_Bad);

OpcUa_ReturnStatusCode;

OpcUa_BeginErrorHandling;
OpcUa_FinishErrorHandling;
}
void CRegProtocol::DeriveKey(BufferObj &KDK, 
                             BufferObj &prsnlString, 
                             uint32 keyBits, 
                             BufferObj &key)
{
    uint32 i = 0, iterations = 0;
    BufferObj input, output;    
    uint8 hmac[SIZE_256_BITS];
    uint32 hmacLen = 0;
    uint8 *inPtr;
    uint32 temp;

    TUTRACE((TUTRACE_INFO, "RPROTO: Deriving a key of %d bits\n", keyBits));

    iterations = ((keyBits/8) + PRF_DIGEST_SIZE - 1)/PRF_DIGEST_SIZE;

    //Prepare the input buffer. During the iterations, we need only replace the 
    //value of i at the start of the buffer.
    temp = WscHtonl(i);
    input.Append(SIZE_4_BYTES, (uint8 *)&temp);
    input.Append(prsnlString.Length(), prsnlString.GetBuf());
    temp = WscHtonl(keyBits);
    input.Append(SIZE_4_BYTES, (uint8 *)&temp);
    inPtr = input.GetBuf();

    for(i = 0; i < iterations; i++)
    {
        //Set the current value of i at the start of the input buffer
        *(uint32 *)inPtr = WscHtonl(i+1); //i should start at 1
        if(HMAC(EVP_sha256(), KDK.GetBuf(), SIZE_256_BITS, input.GetBuf(), 
                input.Length(), hmac, &hmacLen) == NULL)
        {
            TUTRACE((TUTRACE_ERR, "RPROTO: HMAC failed\n"));
            throw RPROT_ERR_CRYPTO;
        }
        output.Append(hmacLen, hmac);
    }

    //Sanity check
    if(keyBits/8 > output.Length())
    {
        TUTRACE((TUTRACE_ERR, "RPROTO: Key derivation generated less bits "
                              "than asked\n"));
        throw RPROT_ERR_CRYPTO;
    }

    //We now have at least the number of key bits requested.
    //Return only the number of bits asked for. Discard the excess.
    key.Append(keyBits/8, output.GetBuf());
}
Example #20
0
/**
 * @brief computes hmac_md5(K, I)
 * @param key hmac_md5 key
 * @param keylen hmac_md5 key length
 * @param in input data to compute hash for
 * @param inlen input data length in bytes
 * @param hmac space for output (MD5_DIGEST_LENGTH bytes)
 * @return 0 on success, -1 on error
 */
int
saslc__crypto_hmac_md5_hash(const unsigned char *key, size_t keylen,
    const unsigned char *in, size_t inlen, unsigned char *hmac)
{
	unsigned int hmac_len;

	assert(hmac != NULL);
	if (hmac == NULL || HMAC(EVP_md5(), key, (int)keylen, in,
	    inlen, hmac, &hmac_len) == NULL)
		return -1;

	assert(hmac_len == MD5_DIGEST_LENGTH);
	return 0;
}
Example #21
0
 /*
  * Computes a HMAC SHA-1 keyed hash of 'input' using the key 'key'
  */
 bool hmacSha1(const unsigned char* key,
               const size_t keyLen,
               const unsigned char* input,
               const size_t inputLen,
               unsigned char* output,
               unsigned int* outputLen) {
     return HMAC(EVP_sha1(),
                 key,
                 keyLen,
                 input,
                 inputLen,
                 output,
                 outputLen);
 }
int encrypt_and_authentucate_secrets(CPOR_key *key, unsigned char *input, size_t input_len, unsigned char *ciphertext, size_t *ciphertext_len, unsigned char *authenticator, size_t *authenticator_len) {

    EVP_CIPHER_CTX ctx;
    EVP_CIPHER *cipher = NULL;
    int len;

    if(!key || !key->k_enc || !key->k_mac || !input || !input_len || !ciphertext || !ciphertext_len || !authenticator || !authenticator_len) return 0;

    OpenSSL_add_all_algorithms();

    EVP_CIPHER_CTX_init(&ctx);
    switch(key->k_enc_size) {
    case 16:
        cipher = (EVP_CIPHER *)EVP_aes_128_cbc();
        break;
    case 24:
        cipher = (EVP_CIPHER *)EVP_aes_192_cbc();
        break;
    case 32:
        cipher = (EVP_CIPHER *)EVP_aes_256_cbc();
        break;
    default:
        return 0;
    }
    //TODO: Fix the NULL IV
    if(!EVP_EncryptInit(&ctx, cipher, key->k_enc, NULL)) goto cleanup;

    *ciphertext_len = 0;

    if(!EVP_EncryptUpdate(&ctx, ciphertext, (int *)ciphertext_len, input, input_len)) goto cleanup;
    EVP_EncryptFinal(&ctx, ciphertext + *ciphertext_len, &len);

    *ciphertext_len += len;

    *authenticator_len = 0;
    /* Do the HMAC-SHA1 */
    if(!HMAC(EVP_sha1(), key->k_mac, key->k_mac_size, ciphertext, *ciphertext_len,
             authenticator, (unsigned int *)authenticator_len)) goto cleanup;

    EVP_CIPHER_CTX_cleanup(&ctx);

    return 1;

cleanup:
    *ciphertext_len = 0;
    *authenticator_len = 0;

    return 0;

}
Example #23
0
/**
 * Sign a string
 * 
 * @param sdb the SimpleDB handle
 * @param str the string to sign
 * @param buffer the buffer to write the signature to (must be at least EVP_MAX_MD_SIZE * 2 bytes)
 * @param plen the pointer to the place to store the length of the signature (can be NULL)
 * @return SDB_OK if no errors occurred
 */
int sdb_sign(struct SDB* sdb, const char* str, char* buffer, size_t* plen)
{
	unsigned char md[EVP_MAX_MD_SIZE];
	unsigned mdl;
	
	HMAC(EVP_sha256(), sdb->sdb_secret, sdb->sdb_secret_len, (const unsigned char*) str, strlen(str), md, &mdl);
	 
	size_t l = base64(md, mdl, buffer, EVP_MAX_MD_SIZE * 2);
	
	if (l == 0) return SDB_E_OPEN_SSL_FAILED;
	if (plen != NULL) *plen = l;
	
	return SDB_OK;
}
Example #24
0
/**
 * @ingroup SnmpParser
 * @brief SNMPv3 msgAuthenticationParameters 를 계산한다.
 * @param pszPacket			패킷
 * @param iPacketLen		패킷 길이
 * @param pszPassWord		비밀번호
 * @param pszEngineId		SNMPv3 engine ID
 * @param iEngineIdLen	SNMPv3 engine ID 길이
 * @param strAuthParams SNMPv3 msgAuthenticationParameters 저장 변수
 * @returns 성공하면 true 를 리턴하고 실패하면 false 를 리턴한다.
 */
bool SnmpMakeHmac( const char * pszPacket, int iPacketLen, const char * pszPassWord, const char * pszEngineId, int iEngineIdLen, std::string & strAuthParams )
{
	uint8_t szKey[16], szAuthKey[16], szResult[16];
	unsigned int iResultSize = sizeof(szResult);

	if( SnmpMakeKey( pszPassWord, szKey ) == false ) return false;
	if( SnmpMakeAuthKey( szKey, (const uint8_t *)pszEngineId, iEngineIdLen, szAuthKey ) == false ) return false;

	HMAC( EVP_md5(), szAuthKey, 16, (const uint8_t *)pszPacket, iPacketLen, szResult, &iResultSize );

	strAuthParams.clear();
	strAuthParams.append( (char *)szResult, 12 );

	return true;
}
Example #25
0
void Network::HmacSha1(const void *key, int key_len,
	const void *buf, size_t size,
	ShaDigest &result)
{
	static_assert(ShaDigestLen == SHA_DIGEST_LENGTH, "SHA_DIGEST_LENGTH");

	unsigned int reslen = 0;

	unsigned char *ret = HMAC(EVP_sha1(),
		key, key_len, static_cast<const unsigned char *>(buf), size,
		result, &reslen);
	if (ret == nullptr || reslen != ShaDigestLen) {
		throw NetworkError("HMAC-SHA1 error");
	}
}
char *findHmac(char *data){
	 // The key to hash
	//unsigned char *key = (unsigned char *)"01234567890123456789012345678901";
	unsigned char *digest1;
	digest1 = HMAC(EVP_sha1(), key, strlen(key), (unsigned char*)data, strlen(data), NULL, NULL);   
	

	for(int i = 0; i < 20; i++)
	 {
		sprintf(&mdString[i*2], "%02x", (unsigned int)digest1[i]);
	}
	puts("Computing HMAC");
	puts(mdString);
	return mdString;
}
/**
  *  @brief To generate Auth Code for RAKP 3, RAKP-HMAC-SHA1, RAKP-HMAC-MD5.
  *
  *  @param[in] alg algorithm
  *  @param[in] key
  *  @param[in] key_len
  *  @param[in] data the input data before encode
  *  @param[in] data_len the input data length
  *  @param[out] buf the output buffer
  *  @return  the output data length
  */
int ipmi20_generate_auth_code(unsigned char alg,
							  void *key,
							  int key_len,
							  unsigned char *data,
							  int data_len,
							  unsigned char *buf)
{
	unsigned int len = 0;

	switch (alg) {
	case AUTH_ALG_RAKP_NONE: /* INTEGRITY_ALG_NONE has the same value */
		return 0;
	case AUTH_ALG_RAKP_HMAC_SHA1: /* INTEGRITY_ALG_HMAC_SHA1_96 has the same value */
		HMAC(EVP_sha1(), key, key_len, data, data_len, buf, &len);
		break;
	case AUTH_ALG_RAKP_HMAC_MD5: /* INTEGRITY_ALG_HMAC_MD5_128 has the same value */
	case INTEGRITY_ALG_MD5_128:
		HMAC(EVP_md5(), key, key_len, data, data_len, buf, &len);
	default:
		break;
	}

	return len;
}
/*
 * Generate the base64 encoded hmac sha1 hash of string str using the secret 
 * key in the amazon_context_struct pointed to in request.
 */
static char *get_hmac_sha1_b64(struct s3_request_struct *req, const char *str)
{
	uint8_t hmac_sha1_buf[EVP_MAX_MD_SIZE];
	unsigned int hmac_sha1_len = 0;

	HMAC(EVP_sha1(), 
	     req->amz_ctx->secret_key,
	     strlen(req->amz_ctx->secret_key),
	     str,
	     strlen(str),
	     hmac_sha1_buf,
	     &hmac_sha1_len);

	return base64_enc(get_tmp_context(req), hmac_sha1_buf, hmac_sha1_len);
}
Example #29
0
static string encode(const char *aws_secret_access_key,string str)
{
    unsigned char md[20];
    uint32_t md_len = sizeof(md);

    /* Note: This MUST be sha1() */
    HMAC(EVP_sha1(),aws_secret_access_key,strlen(aws_secret_access_key),
	 (const unsigned char *)str.c_str(),str.size(),
	 md,&md_len);
    /* Now encode this to base64 */
    char b64str[64];
    memset(b64str,0,sizeof(b64str));
    b64_ntop(md,md_len,b64str,sizeof(b64str));
    return string(b64str);
}
Example #30
-1
	std::string eval(const std::string& key, const std::string& data)
	{
		std::string out(evp_->md_size + 1, 0);
		unsigned int outLen = 0;
		if (HMAC(evp_, key.c_str(), static_cast<int>(key.size()),
			cybozu::cast<const uint8_t *>(data.c_str()), data.size(), cybozu::cast<uint8_t *>(&out[0]), &outLen)) {
			out.resize(outLen);
			return out;
		}
		throw cybozu::Exception("crypto::Hamc::eval");
	}