Exemplo n.º 1
0
static void
ChallengeHash(const uint8_t peer_challenge[MSCHAP2_CHALLENGE_SIZE],
	      const uint8_t auth_challenge[MSCHAP2_CHALLENGE_SIZE],
	      const uint8_t * username,
	      uint8_t challenge[MSCHAP_NT_CHALLENGE_SIZE])
{
    const uint8_t *	user;
    CC_SHA1_CTX		context;
    uint8_t		hash[CC_SHA1_DIGEST_LENGTH];

    /* find the last backslash to get the user name to use for the hash */
    user = (const uint8_t *)strrchr((const char *)username, '\\');
    if (user == NULL) {
	user = username;
    }
    else {
	user = user + 1;
    }
    CC_SHA1_Init(&context);
    CC_SHA1_Update(&context, peer_challenge, MSCHAP2_CHALLENGE_SIZE);
    CC_SHA1_Update(&context, auth_challenge, MSCHAP2_CHALLENGE_SIZE);
    CC_SHA1_Update(&context, user, (int)strlen((const char *)user));
    CC_SHA1_Final(hash, &context);
    bcopy(hash, challenge, MSCHAP_NT_CHALLENGE_SIZE);
    return;
}
Exemplo n.º 2
0
void
MSChap2_MPPEGetAsymetricStartKey(const uint8_t MasterKey[NT_MASTER_KEY_SIZE],
				 uint8_t SessionKey[NT_SESSION_KEY_SIZE],
				 int SessionKeyLength,
				 bool IsSend,
				 bool IsServer)
{
    CC_SHA1_CTX		context;
    uint8_t		Digest[CC_SHA1_DIGEST_LENGTH];
    const uint8_t *	s;

    /*
     * The logic in the spec says:
     *  if (IsSend) {
     *	    if (IsServer) {
     *         	s = Magic3;
     *	    }
     *	    else {
     *	    	s = Magic2;
     *	    }
     * 	} 
     *  else {
     *	    if (IsServer) {
     *      	s = Magic2;
     *	    } 
     *	    else {
     *      	s = Magic3;
     *	    }
     *	}
     *
     * The corresponding truth table is:
     * IsSend	IsServer	s
     *   0	  0		Magic3
     *   0	  1		Magic2
     *   1	  0		Magic2
     *   1	  1		Magic3
     * which is simply:
     *	s = (IsSend == IsServer) ? Magic3 : Magic2;
     */
    s = (IsSend == IsServer) ? Magic3 : Magic2;
    memset(Digest, 0, sizeof(Digest));
    CC_SHA1_Init(&context);
    CC_SHA1_Update(&context, MasterKey, NT_MASTER_KEY_SIZE);
    CC_SHA1_Update(&context, SHSpad1, sizeof(SHSpad1));
    CC_SHA1_Update(&context, s, MAGIC2_3_SIZE);
    CC_SHA1_Update(&context, SHSpad2, sizeof(SHSpad2));
    CC_SHA1_Final(Digest, &context);

    if (SessionKeyLength > NT_SESSION_KEY_SIZE) {
	SessionKeyLength = NT_SESSION_KEY_SIZE;
    }
    memcpy(SessionKey, Digest, SessionKeyLength);
    return;
}
Exemplo n.º 3
0
static NTSTATUS hash_update( struct hash *hash, UCHAR *input, ULONG size )
{
    switch (hash->alg_id)
    {
    case ALG_ID_SHA1:
        CC_SHA1_Update( &hash->u.sha1_ctx, input, size );
        break;

    case ALG_ID_SHA256:
        CC_SHA256_Update( &hash->u.sha256_ctx, input, size );
        break;

    case ALG_ID_SHA384:
        CC_SHA384_Update( &hash->u.sha512_ctx, input, size );
        break;

    case ALG_ID_SHA512:
        CC_SHA512_Update( &hash->u.sha512_ctx, input, size );
        break;

    default:
        ERR( "unhandled id %u\n", hash->alg_id );
        return STATUS_NOT_IMPLEMENTED;
    }
    return STATUS_SUCCESS;
}
Exemplo n.º 4
0
UInt8* CC_SHA1(const void *data, CC_LONG len, UInt8 *md)
{	
	CC_LONG bytes_hashed = 0;
	const UInt8 *data_buff = (const UInt8 *)data;
	
	if(md == NULL)
		return NULL;									
		
	CC_SHA1_CTX ctx;
	CC_SHA1_Init(&ctx);
	
	if (len > CC_SHA1_USE_HARDWARE_THRESHOLD &&
        !((intptr_t)data_buff & 3) &&
        !pthread_once(&cc_sha1_connect_once, cc_sha1_connect) && cc_sha1_device >= 0) 
    {
		bytes_hashed = sha1_hash_in_hardware(&ctx, data_buff, len, true);
		if (bytes_hashed == len) {
            OSWriteBigInt32(md, 0, ctx.h0);
            OSWriteBigInt32(md, 4, ctx.h1);
            OSWriteBigInt32(md, 8, ctx.h2);
            OSWriteBigInt32(md, 12, ctx.h3);
            OSWriteBigInt32(md, 16, ctx.h4); 
			return md;
        }

		//Either we have failed partially or completely.
		//Fall through to the software.
		data_buff += bytes_hashed;
		len -= bytes_hashed;
	}
	//Fall back to Software SHA1.
	CC_SHA1_Update(&ctx, data_buff, len);
	CC_SHA1_Final(md, &ctx);					
	return md;												
}
Exemplo n.º 5
0
char* calculate_digest(int fd) {
	unsigned char md[CC_SHA1_DIGEST_LENGTH];
	CC_SHA1_CTX c;
	CC_SHA1_Init(&c);
	
	memset(md, 0, CC_SHA1_DIGEST_LENGTH);
	
	ssize_t len;
	const unsigned int blocklen = 8192;
	unsigned char* block = (unsigned char*)malloc(blocklen);
	if (!block) {
		errno = ENOMEM;
		return NULL;
	}
	while(1) {
		len = read(fd, block, blocklen);
		if (len == 0) { close(fd); break; }
		if ((len < 0) && (errno == EINTR)) continue;
		if (len < 0) { close(fd); return NULL; }
		CC_SHA1_Update(&c, block, (CC_LONG)len);
	}
	
	CC_SHA1_Final(md, &c);
	free(block);
	return format_digest(md);
}
Exemplo n.º 6
0
static int
__archive_libsystem_sha1update(archive_sha1_ctx *ctx, const void *indata,
    size_t insize)
{
  CC_SHA1_Update(ctx, indata, insize);
  return (ARCHIVE_OK);
}
Exemplo n.º 7
0
/*
 * Obtain a mallocd C-string representation of a certificate's SHA1 digest.
 * Only error is a NULL return indicating memory failure.
 * Caller must free the returned string.
 */
char *krb5_pkinit_cert_hash_str(
    const krb5_data *cert)
{
    CC_SHA1_CTX ctx;
    char *outstr;
    char *cpOut;
    unsigned char digest[CC_SHA1_DIGEST_LENGTH];
    unsigned dex;

    assert(cert != NULL);
    CC_SHA1_Init(&ctx);
    CC_SHA1_Update(&ctx, cert->data, cert->length);
    CC_SHA1_Final(digest, &ctx);

    outstr = (char *)malloc((2 * CC_SHA1_DIGEST_LENGTH) + 1);
    if(outstr == NULL) {
        return NULL;
    }
    cpOut = outstr;
    for(dex=0; dex<CC_SHA1_DIGEST_LENGTH; dex++) {
        snprintf(cpOut, 3, "%02X", (unsigned)(digest[dex]));
        cpOut += 2;
    }
    *cpOut = '\0';
    return outstr;
}
Exemplo n.º 8
0
extern "C" int32_t AppleCryptoNative_DigestUpdate(DigestCtx* ctx, uint8_t* pBuf, int32_t cbBuf)
{
    if (cbBuf == 0)
        return 1;
    if (ctx == nullptr || pBuf == nullptr)
        return -1;

    CC_LONG bufSize = static_cast<CC_LONG>(cbBuf);

    switch (ctx->algorithm)
    {
        case PAL_MD5:
            return CC_MD5_Update(&ctx->d.md5, pBuf, bufSize);
        case PAL_SHA1:
            return CC_SHA1_Update(&ctx->d.sha1, pBuf, bufSize);
        case PAL_SHA256:
            return CC_SHA256_Update(&ctx->d.sha256, pBuf, bufSize);
        case PAL_SHA384:
            return CC_SHA384_Update(&ctx->d.sha384, pBuf, bufSize);
        case PAL_SHA512:
            return CC_SHA512_Update(&ctx->d.sha512, pBuf, bufSize);
        default:
            return -1;
    }
}
Exemplo n.º 9
0
int
_mesa_sha1_update(struct mesa_sha1 *ctx, const void *data, int size)
{
    CC_SHA1_CTX *sha1_ctx = (CC_SHA1_CTX *) ctx;

    CC_SHA1_Update(sha1_ctx, data, size);
    return 1;
}
Exemplo n.º 10
0
static OSStatus HashSHA1Update(SSLBuffer *digestCtx, const SSLBuffer *data)
{
    /* 64 bits cast: safe, SSL records are always smaller than 2^32 bytes */
	assert(digestCtx->length >= sizeof(CC_SHA1_CTX));
	CC_SHA1_CTX *ctx = (CC_SHA1_CTX *)digestCtx->data;
	CC_SHA1_Update(ctx, data->data, (CC_LONG)data->length);
    return noErr;
}
Exemplo n.º 11
0
static void
GetMasterKey(const uint8_t PasswordHashHash[NT_PASSWORD_HASH_SIZE],
	     const uint8_t NTResponse[MSCHAP_NT_RESPONSE_SIZE],
	     uint8_t MasterKey[NT_MASTER_KEY_SIZE])
{
    CC_SHA1_CTX		context;
    uint8_t		Digest[CC_SHA1_DIGEST_LENGTH];

    memset(Digest, 0, sizeof(Digest));

    CC_SHA1_Init(&context);
    CC_SHA1_Update(&context, PasswordHashHash, NT_PASSWORD_HASH_SIZE);
    CC_SHA1_Update(&context, NTResponse, MSCHAP_NT_RESPONSE_SIZE);
    CC_SHA1_Update(&context, Magic1, sizeof(Magic1));
    CC_SHA1_Final(Digest, &context);
    memcpy(MasterKey, Digest, NT_MASTER_KEY_SIZE);
    return;
}
Exemplo n.º 12
0
void get_device_infos(CFMutableDictionaryRef out) {
    CC_SHA1_CTX sha1ctx;
    uint8_t udid[20];
    char udid1[100];
    CFStringRef serial;
    CFStringRef imei;
    CFStringRef macwifi;
    CFStringRef macbt;
    
    CFStringRef hw = copy_hardware_model(); 
    if (hw != NULL)
    {
        CFDictionaryAddValue(out, CFSTR("hwModel"), hw);
        CFRelease(hw);
    }
    
    serial = copy_device_serial_number();
    imei = copy_device_imei();
    macwifi = copy_wifi_mac_address();
    macbt = copy_bluetooth_mac_address();
    
    CFMutableStringRef udidInput = CFStringCreateMutable(kCFAllocatorDefault, 0);
    if (serial != NULL)
    {
        CFStringAppend(udidInput, serial);
        CFDictionaryAddValue(out, CFSTR("serialNumber"), serial);
        CFRelease(serial);
    }
    if (imei != NULL)
    {
        CFStringAppend(udidInput, imei);
        CFDictionaryAddValue(out, CFSTR("imei"), imei);
        CFRelease(imei);
    }
    if (macwifi != NULL)
    {
        CFStringAppend(udidInput, macwifi);
        CFDictionaryAddValue(out, CFSTR("wifiMac"), macwifi);
        CFRelease(macwifi);
    }
    if (macbt != NULL)
    {
        CFStringAppend(udidInput, macbt);
        CFDictionaryAddValue(out, CFSTR("btMac"), macbt);
        CFRelease(macbt);
    }
    
    CFStringGetCString(udidInput, udid1, 99, kCFStringEncodingASCII);
    
    CC_SHA1_Init(&sha1ctx);
    CC_SHA1_Update(&sha1ctx, udid1, CFStringGetLength(udidInput));
    CC_SHA1_Final(udid, &sha1ctx);
    
    CFRelease(udidInput);
    addHexaString(out, CFSTR("udid"), udid, 20);

}
Exemplo n.º 13
0
void ocspdSha1(
	const void		*data,
	CC_LONG			len,
	unsigned char	*md)		// allocd by caller, CC_SHA1_DIGEST_LENGTH bytes
{
	CC_SHA1_CTX ctx;
	CC_SHA1_Init(&ctx);
	CC_SHA1_Update(&ctx, data, len);
	CC_SHA1_Final(md, &ctx);
}
Exemplo n.º 14
0
void Crypto::DigestUpdate(Digest x, const StringPiece &in) {
  auto d = FromVoid<CCDigest*>(x);
  switch(d->algo) {
    case CCDigestAlgo::MD5:    CC_MD5_Update   (static_cast<CC_MD5_CTX*>   (d->v), in.data(), in.size()); break;
    case CCDigestAlgo::SHA1:   CC_SHA1_Update  (static_cast<CC_SHA1_CTX*>  (d->v), in.data(), in.size()); break;
    case CCDigestAlgo::SHA256: CC_SHA256_Update(static_cast<CC_SHA256_CTX*>(d->v), in.data(), in.size()); break;
    case CCDigestAlgo::SHA384: CC_SHA384_Update(static_cast<CC_SHA512_CTX*>(d->v), in.data(), in.size()); break;
    case CCDigestAlgo::SHA512: CC_SHA512_Update(static_cast<CC_SHA512_CTX*>(d->v), in.data(), in.size()); break;
    default: break;
  }
}
Exemplo n.º 15
0
	void hasher::update(const char* data, int len)
	{
		TORRENT_ASSERT(data != 0);
		TORRENT_ASSERT(len > 0);
#ifdef TORRENT_USE_GCRYPT
		gcry_md_write(m_context, data, len);
#elif TORRENT_USE_COMMONCRYPTO
		CC_SHA1_Update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#elif defined TORRENT_USE_OPENSSL
		SHA1_Update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#else
		SHA1_update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#endif
	}
Exemplo n.º 16
0
	hasher& hasher::update(span<char const> data)
	{
		TORRENT_ASSERT(!data.empty());
#ifdef TORRENT_USE_LIBGCRYPT
		gcry_md_write(m_context, data.data(), data.size());
#elif TORRENT_USE_COMMONCRYPTO
		CC_SHA1_Update(&m_context, reinterpret_cast<unsigned char const*>(data.data()), CC_LONG(data.size()));
#elif TORRENT_USE_CRYPTOAPI
		m_context.update(data);
#elif defined TORRENT_USE_LIBCRYPTO
		SHA1_Update(&m_context, reinterpret_cast<unsigned char const*>(data.data()), data.size());
#else
		SHA1_update(&m_context, reinterpret_cast<unsigned char const*>(data.data()), data.size());
#endif
		return *this;
	}
Exemplo n.º 17
0
int32_t mz_crypt_sha_update(void *handle, const void *buf, int32_t size)
{
    mz_crypt_sha *sha = (mz_crypt_sha *)handle;

    if (sha == NULL || buf == NULL || !sha->initialized)
        return MZ_PARAM_ERROR;

    if (sha->algorithm == MZ_HASH_SHA1)
        sha->error = CC_SHA1_Update(&sha->ctx1, buf, size);
    else
        sha->error = CC_SHA256_Update(&sha->ctx256, buf, size);
        
    if (!sha->error)
        return MZ_HASH_ERROR;

    return size;
}
Exemplo n.º 18
0
static void
lib_md_update(mrb_state *mrb, struct mrb_md *md, unsigned char *data, mrb_int len)
{
  if (sizeof(len) > sizeof(CC_LONG)) {
    if (len != (CC_LONG)len) {
      mrb_raise(mrb, E_ARGUMENT_ERROR, "too long string (not supported yet)");
    }
  }
  switch (md->type) {
  case MD_TYPE_MD5:	CC_MD5_Update(md->ctx, data, len);	break;
  case MD_TYPE_SHA1:	CC_SHA1_Update(md->ctx, data, len);	break;
  case MD_TYPE_SHA256:	CC_SHA256_Update(md->ctx, data, len);	break;
  case MD_TYPE_SHA384:	CC_SHA384_Update(md->ctx, data, len);	break;
  case MD_TYPE_SHA512:	CC_SHA512_Update(md->ctx, data, len);	break;
  default: break;
  }
}
Exemplo n.º 19
0
static void
GenerateAuthResponse(uint8_t * password, uint32_t password_len,
		     const uint8_t nt_response[MSCHAP_NT_RESPONSE_SIZE],
		     const uint8_t peer_challenge[MSCHAP2_CHALLENGE_SIZE],
		     const uint8_t auth_challenge[MSCHAP2_CHALLENGE_SIZE],
		     const uint8_t * username,
		     uint8_t auth_response[MSCHAP2_AUTH_RESPONSE_SIZE])
{
    uint8_t		challenge[MSCHAP_NT_CHALLENGE_SIZE];
    CC_SHA1_CTX		context;
    int			i;
    uint8_t		hash[CC_SHA1_DIGEST_LENGTH];
    uint8_t		password_hash[NT_PASSWORD_HASH_SIZE];
    uint8_t *		scan;

    NTPasswordHashHash(password, password_len, password_hash);

    CC_SHA1_Init(&context);
    CC_SHA1_Update(&context, password_hash, NT_PASSWORD_HASH_SIZE);
    CC_SHA1_Update(&context, nt_response, MSCHAP_NT_RESPONSE_SIZE);
    CC_SHA1_Update(&context, magic1, 39);
    CC_SHA1_Final(hash, &context);

    ChallengeHash(peer_challenge, auth_challenge, username,
		  challenge);
    
    CC_SHA1_Init(&context);
    CC_SHA1_Update(&context, hash, CC_SHA1_DIGEST_LENGTH);
    CC_SHA1_Update(&context, challenge, MSCHAP_NT_CHALLENGE_SIZE);
    CC_SHA1_Update(&context, magic2, 41);
    CC_SHA1_Final(hash, &context);

    /*
     * Encode the value of 'hash' as "S=" followed by
     * 40 ASCII hexadecimal digits and return it in
     * 'auth_response'.
     * For example,
     *   "S=0123456789ABCDEF0123456789ABCDEF01234567"
     */
    auth_response[0] = 'S';
    auth_response[1] = '=';
    for (i = 0, scan = auth_response + 2; 
	 i < CC_SHA1_DIGEST_LENGTH; i++, scan +=2) {
	char	hexstr[3];
	snprintf(hexstr, 3, "%02X", hash[i]);
	scan[0] = hexstr[0];
	scan[1] = hexstr[1];
    }
    return;
}
void CryptoDigest::addBytes(const void* input, size_t length)
{
    switch (m_context->algorithm) {
    case CryptoDigest::Algorithm::SHA_1:
        CC_SHA1_Update(toSHA1Context(m_context.get()), input, length);
        return;
    case CryptoDigest::Algorithm::SHA_224:
        CC_SHA224_Update(toSHA224Context(m_context.get()), input, length);
        return;
    case CryptoDigest::Algorithm::SHA_256:
        CC_SHA256_Update(toSHA256Context(m_context.get()), input, length);
        return;
    case CryptoDigest::Algorithm::SHA_384:
        CC_SHA384_Update(toSHA384Context(m_context.get()), input, length);
        return;
    case CryptoDigest::Algorithm::SHA_512:
        CC_SHA512_Update(toSHA512Context(m_context.get()), input, length);
        return;
    }
}
Exemplo n.º 21
0
Arquivo: utils.c Projeto: Tyilo/hydra
unsigned char *sha1file(char *path) {
	FILE *f = fopen(path, "r");
	if(!f) {
		return NULL;
	}
	
	CC_SHA1_CTX ctx;
	CC_SHA1_Init(&ctx);
	
	char buf[CC_SHA1_BLOCK_BYTES];
	while(!feof(f)) {
		size_t read = fread(buf, 1, CC_SHA1_BLOCK_BYTES, f);
		CC_SHA1_Update(&ctx, buf, (CC_LONG)read);
	}
	fclose(f);
	
	unsigned char *hash = malloc(CC_SHA1_DIGEST_LENGTH);
	CC_SHA1_Final(hash, &ctx);
	
	return hash;
}
Exemplo n.º 22
0
void CryptoDigest::addBytes(const void* input, size_t length)
{
    switch (m_context->algorithm) {
    case CryptoAlgorithmIdentifier::SHA_1:
        CC_SHA1_Update(toSHA1Context(m_context.get()), input, length);
        return;
    case CryptoAlgorithmIdentifier::SHA_224:
        CC_SHA224_Update(toSHA224Context(m_context.get()), input, length);
        return;
    case CryptoAlgorithmIdentifier::SHA_256:
        CC_SHA256_Update(toSHA256Context(m_context.get()), input, length);
        return;
    case CryptoAlgorithmIdentifier::SHA_384:
        CC_SHA384_Update(toSHA384Context(m_context.get()), input, length);
        return;
    case CryptoAlgorithmIdentifier::SHA_512:
        CC_SHA512_Update(toSHA512Context(m_context.get()), input, length);
        return;
    default:
        ASSERT_NOT_REACHED();
    }
}
Exemplo n.º 23
0
	hasher& hasher::update(const char* data, int len)
	{
		TORRENT_ASSERT(data != nullptr);
		TORRENT_ASSERT(len > 0);
#ifdef TORRENT_USE_LIBGCRYPT
		gcry_md_write(m_context, data, len);
#elif TORRENT_USE_COMMONCRYPTO
		CC_SHA1_Update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#elif TORRENT_USE_CRYPTOAPI
		if (CryptHashData(m_context, reinterpret_cast<BYTE const*>(data), len, 0) == false)
		{
#ifndef BOOST_NO_EXCEPTIONS
			throw system_error(error_code(GetLastError(), system_category()));
#else
			std::terminate();
#endif
		}
#elif defined TORRENT_USE_LIBCRYPTO
		SHA1_Update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#else
		SHA1_update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#endif
		return *this;
	}
Exemplo n.º 24
0
void SHA1Digest::Update(const void* buffer, size_t length)
{
	CC_SHA1_Update(&mContext, buffer, (CC_LONG)length);
}
Exemplo n.º 25
0
int p12_pbe_gen(CFStringRef passphrase, uint8_t *salt_ptr, size_t salt_length, 
    unsigned iter_count, P12_PBE_ID pbe_id, uint8_t *data, size_t length)
{
    unsigned int hash_blocksize = CC_SHA1_BLOCK_BYTES;
    unsigned int hash_outputsize = CC_SHA1_DIGEST_LENGTH;

    if (!passphrase)
        return -1;

    /* generate diversifier block */
    unsigned char diversifier[hash_blocksize];    
    memset(diversifier, pbe_id, sizeof(diversifier));

    /* convert passphrase to BE UTF16 and append double null */
    CFDataRef passphrase_be_unicode = CFStringCreateExternalRepresentation(kCFAllocatorDefault, passphrase, kCFStringEncodingUTF16BE, '\0');
    if (!passphrase_be_unicode)
        return -1;
    uint8_t null_termination[2] = { 0, 0 };
    CFMutableDataRef passphrase_be_unicode_null_term = CFDataCreateMutableCopy(NULL, 0, passphrase_be_unicode);
    CFRelease(passphrase_be_unicode);
    if (!passphrase_be_unicode_null_term)
        return -1;
    CFDataAppendBytes(passphrase_be_unicode_null_term, null_termination, sizeof(null_termination));

    /* generate passphrase block */
    uint8_t *passphrase_data = NULL;
    size_t passphrase_data_len = 0;
    size_t passphrase_length = CFDataGetLength(passphrase_be_unicode_null_term);
    const unsigned char *passphrase_ptr = CFDataGetBytePtr(passphrase_be_unicode_null_term);
    passphrase_data = concatenate_to_blocksize(passphrase_ptr, passphrase_length, hash_blocksize, &passphrase_data_len);
    CFRelease(passphrase_be_unicode_null_term);
    if (!passphrase_data)
        return -1;

    /* generate salt block */
    uint8_t *salt_data = NULL;
    size_t salt_data_len = 0;
    if (salt_length)
        salt_data = concatenate_to_blocksize(salt_ptr, salt_length, hash_blocksize, &salt_data_len);
    if (!salt_data)
        return -1;
    
    /* generate S||P block */
    size_t I_length = salt_data_len + passphrase_data_len;
    uint8_t *I_data = malloc(I_length);
    if (!I_data)
        return -1;
        
    memcpy(I_data + 0, salt_data, salt_data_len);
    memcpy(I_data + salt_data_len, passphrase_data, passphrase_data_len);
    free(salt_data);
    free(passphrase_data);

    /* round up output buffer to multiple of hash block size and allocate */
    size_t hash_output_blocks = (length + hash_outputsize - 1) / hash_outputsize;
    size_t temp_buf_size = hash_output_blocks * hash_outputsize;
    uint8_t *temp_buf = malloc(temp_buf_size);
    uint8_t *cursor = temp_buf;
    if (!temp_buf)
        return -1;

    /* 64 bits cast(s): worst case here is we dont hash all the data and incorectly derive the wrong key,
       when the passphrase + salt are over 2^32 bytes long */
    /* loop over output in hash_output_size increments */
    while (cursor < temp_buf + temp_buf_size) {
        CC_SHA1_CTX ctx;
        CC_SHA1_Init(&ctx);
        CC_SHA1_Update(&ctx, diversifier, (CC_LONG)sizeof(diversifier));
        assert(I_length<=UINT32_MAX); /* debug check. Correct as long as CC_LONG is uint32_t */
        CC_SHA1_Update(&ctx, I_data, (CC_LONG)I_length);
        CC_SHA1_Final(cursor, &ctx);

        /* run block through SHA-1 for iteration count */
        unsigned int i;
        for (i = 1; /*first round done above*/ i < iter_count; i++)
            CC_SHA1(cursor, hash_outputsize, cursor);

        /*
         * b) Concatenate copies of A[i] to create a string B of 
         *    length v bits (the final copy of A[i]i may be truncated 
         *    to create B).
         */
        size_t A_i_len = 0;
        uint8_t *A_i = concatenate_to_blocksize(cursor, 
            hash_outputsize, hash_blocksize, &A_i_len);
        if (!A_i)
            return -1;
        
        /*
         * c) Treating I as a concatenation I[0], I[1], ..., 
         *    I[k-1] of v-bit blocks, where k = ceil(s/v) + ceil(p/v),
         *    modify I by setting I[j]=(I[j]+B+1) mod (2 ** v)
         *    for each j.
         */

        /* tmp1 = B+1 */

        const cc_size tmp_n = ccn_nof_size(A_i_len + 1) > ccn_nof_size(hash_blocksize) ? ccn_nof_size(A_i_len + 1) : ccn_nof_size(hash_blocksize);
        cc_unit tmp1[tmp_n];
        ccn_read_uint(tmp_n, tmp1, A_i_len, A_i);
        ccn_add1(tmp_n, tmp1, tmp1, 1);

        free(A_i);

        cc_unit tmp2[tmp_n];
        unsigned int j;
        for (j = 0; j < I_length; j+=hash_blocksize) {
            /* tempg = I[j];  */
            ccn_read_uint(tmp_n, tmp2, hash_blocksize, I_data + j);
            /* tempg += tmp1 */
            ccn_add(tmp_n, tmp2, tmp2, tmp1);
            
            /* I[j] = tempg mod 2**v
               Just clear all the high bits above 2**v
               In practice at most it rolled over by 1 bit, since all we did was add so
               we should only clear one bit at most.
             */
            size_t bitSize;
            const size_t hash_blocksize_bits = hash_blocksize * 8;
            while ((bitSize = ccn_bitlen(tmp_n, tmp2)) > hash_blocksize_bits)
            {
                ccn_set_bit(tmp2, bitSize - 1, 0);
            }

            ccn_write_uint_padded(tmp_n, tmp2, hash_blocksize, I_data + j);
        }

        cursor += hash_outputsize;
    }

    /*
     * 7. Concatenate A[1], A[2], ..., A[c] together to form a 
     *    pseudo-random bit string, A.
     *
     * 8. Use the first n bits of A as the output of this entire 
     *    process.
     */
    memmove(data, temp_buf, length);
    free(temp_buf);
    free(I_data);
    return 0;
}
Exemplo n.º 26
0
CFStringRef FileSHA1HashCreateWithPath(CFStringRef filePath,
                                      size_t chunkSizeForReadingData) {
    
    // Declare needed variables
    CFStringRef result = NULL;
    CFReadStreamRef readStream = NULL;
    
    // Get the file URL
    CFURLRef fileURL =
    CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                  (CFStringRef)filePath,
                                  kCFURLPOSIXPathStyle,
                                  (Boolean)false);
    if (!fileURL) goto done;
    
    // Create and open the read stream
    readStream = CFReadStreamCreateWithFile(kCFAllocatorDefault,
                                            (CFURLRef)fileURL);
    if (!readStream) goto done;
    bool didSucceed = (bool)CFReadStreamOpen(readStream);
    if (!didSucceed) goto done;
    
    // Initialize the hash object
    CC_SHA1_CTX hashObject;
    CC_SHA1_Init(&hashObject);
    
    // Make sure chunkSizeForReadingData is valid
    if (!chunkSizeForReadingData) {
        chunkSizeForReadingData = FileHashDefaultChunkSizeForReadingData;
    }
    
    // Feed the data to the hash object
    bool hasMoreData = true;
    while (hasMoreData) {
        uint8_t buffer[chunkSizeForReadingData];
        CFIndex readBytesCount = CFReadStreamRead(readStream,
                                                  (UInt8 *)buffer,
                                                  (CFIndex)sizeof(buffer));
        if (readBytesCount == -1) break;
        if (readBytesCount == 0) {
            hasMoreData = false;
            continue;
        }
        CC_SHA1_Update(&hashObject,
                      (const void *)buffer,
                      (CC_LONG)readBytesCount);
    }
    
    // Check if the read operation succeeded
    didSucceed = !hasMoreData;
    
    // Compute the hash digest
    unsigned char digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1_Final(digest, &hashObject);
    
    // Abort if the read operation failed
    if (!didSucceed) goto done;
    
    // Compute the string result
    char hash[2 * sizeof(digest) + 1];
    for (size_t i = 0; i < sizeof(digest); ++i) {
        snprintf(hash + (2 * i), 3, "%02x", (int)(digest[i]));
    }
    result = CFStringCreateWithCString(kCFAllocatorDefault,
                                       (const char *)hash,
                                       kCFStringEncodingUTF8);
    
done:
    
    if (readStream) {
        CFReadStreamClose(readStream);
        CFRelease(readStream);
    }
    if (fileURL) {
        CFRelease(fileURL);
    }
    return result;
}
Exemplo n.º 27
0
Arquivo: hash.c Projeto: apple/cups
ssize_t					/* O - Size of hash or -1 on error */
cupsHashData(const char    *algorithm,	/* I - Algorithm name */
             const void    *data,	/* I - Data to hash */
             size_t        datalen,	/* I - Length of data to hash */
             unsigned char *hash,	/* I - Hash buffer */
             size_t        hashsize)	/* I - Size of hash buffer */
{
  if (!algorithm || !data || datalen == 0 || !hash || hashsize == 0)
  {
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad arguments to function"), 1);
    return (-1);
  }

#ifdef __APPLE__
  if (!strcmp(algorithm, "sha"))
  {
   /*
    * SHA-1...
    */

    CC_SHA1_CTX	ctx;			/* SHA-1 context */

    if (hashsize < CC_SHA1_DIGEST_LENGTH)
      goto too_small;

    CC_SHA1_Init(&ctx);
    CC_SHA1_Update(&ctx, data, (CC_LONG)datalen);
    CC_SHA1_Final(hash, &ctx);

    return (CC_SHA1_DIGEST_LENGTH);
  }
  else if (!strcmp(algorithm, "sha2-224"))
  {
    CC_SHA256_CTX	ctx;		/* SHA-224 context */

    if (hashsize < CC_SHA224_DIGEST_LENGTH)
      goto too_small;

    CC_SHA224_Init(&ctx);
    CC_SHA224_Update(&ctx, data, (CC_LONG)datalen);
    CC_SHA224_Final(hash, &ctx);

    return (CC_SHA224_DIGEST_LENGTH);
  }
  else if (!strcmp(algorithm, "sha2-256"))
  {
    CC_SHA256_CTX	ctx;		/* SHA-256 context */

    if (hashsize < CC_SHA256_DIGEST_LENGTH)
      goto too_small;

    CC_SHA256_Init(&ctx);
    CC_SHA256_Update(&ctx, data, (CC_LONG)datalen);
    CC_SHA256_Final(hash, &ctx);

    return (CC_SHA256_DIGEST_LENGTH);
  }
  else if (!strcmp(algorithm, "sha2-384"))
  {
    CC_SHA512_CTX	ctx;		/* SHA-384 context */

    if (hashsize < CC_SHA384_DIGEST_LENGTH)
      goto too_small;

    CC_SHA384_Init(&ctx);
    CC_SHA384_Update(&ctx, data, (CC_LONG)datalen);
    CC_SHA384_Final(hash, &ctx);

    return (CC_SHA384_DIGEST_LENGTH);
  }
  else if (!strcmp(algorithm, "sha2-512"))
  {
    CC_SHA512_CTX	ctx;		/* SHA-512 context */

    if (hashsize < CC_SHA512_DIGEST_LENGTH)
      goto too_small;

    CC_SHA512_Init(&ctx);
    CC_SHA512_Update(&ctx, data, (CC_LONG)datalen);
    CC_SHA512_Final(hash, &ctx);

    return (CC_SHA512_DIGEST_LENGTH);
  }
  else if (!strcmp(algorithm, "sha2-512_224"))
  {
    CC_SHA512_CTX	ctx;		/* SHA-512 context */
    unsigned char	temp[CC_SHA512_DIGEST_LENGTH];
                                        /* SHA-512 hash */

   /*
    * SHA2-512 truncated to 224 bits (28 bytes)...
    */

    if (hashsize < CC_SHA224_DIGEST_LENGTH)
      goto too_small;

    CC_SHA512_Init(&ctx);
    CC_SHA512_Update(&ctx, data, (CC_LONG)datalen);
    CC_SHA512_Final(temp, &ctx);

    memcpy(hash, temp, CC_SHA224_DIGEST_LENGTH);

    return (CC_SHA224_DIGEST_LENGTH);
  }
  else if (!strcmp(algorithm, "sha2-512_256"))
  {
    CC_SHA512_CTX	ctx;		/* SHA-512 context */
    unsigned char	temp[CC_SHA512_DIGEST_LENGTH];
                                        /* SHA-512 hash */

   /*
    * SHA2-512 truncated to 256 bits (32 bytes)...
    */

    if (hashsize < CC_SHA256_DIGEST_LENGTH)
      goto too_small;

    CC_SHA512_Init(&ctx);
    CC_SHA512_Update(&ctx, data, (CC_LONG)datalen);
    CC_SHA512_Final(temp, &ctx);

    memcpy(hash, temp, CC_SHA256_DIGEST_LENGTH);

    return (CC_SHA256_DIGEST_LENGTH);
  }

#elif defined(HAVE_GNUTLS)
  gnutls_digest_algorithm_t alg = GNUTLS_DIG_UNKNOWN;
					/* Algorithm */
  unsigned char	temp[64];		/* Temporary hash buffer */
  size_t	tempsize = 0;		/* Truncate to this size? */

  if (!strcmp(algorithm, "sha"))
    alg = GNUTLS_DIG_SHA1;
  else if (!strcmp(algorithm, "sha2-224"))
    alg = GNUTLS_DIG_SHA224;
  else if (!strcmp(algorithm, "sha2-256"))
    alg = GNUTLS_DIG_SHA256;
  else if (!strcmp(algorithm, "sha2-384"))
    alg = GNUTLS_DIG_SHA384;
  else if (!strcmp(algorithm, "sha2-512"))
    alg = GNUTLS_DIG_SHA512;
  else if (!strcmp(algorithm, "sha2-512_224"))
  {
    alg      = GNUTLS_DIG_SHA512;
    tempsize = 28;
  }
  else if (!strcmp(algorithm, "sha2-512_256"))
  {
    alg      = GNUTLS_DIG_SHA512;
    tempsize = 32;
  }

  if (alg != GNUTLS_DIG_UNKNOWN)
  {
    if (tempsize > 0)
    {
     /*
      * Truncate result to tempsize bytes...
      */

      if (hashsize < tempsize)
        goto too_small;

      gnutls_hash_fast(alg, data, datalen, temp);
      memcpy(hash, temp, tempsize);

      return ((ssize_t)tempsize);
    }

    if (hashsize < gnutls_hash_get_len(alg))
      goto too_small;

    gnutls_hash_fast(alg, data, datalen, hash);

    return (gnutls_hash_get_len(alg));
  }

#else
 /*
  * No hash support without CommonCrypto or GNU TLS...
  */

  if (hashsize < 64)
    goto too_small;
#endif /* __APPLE__ */

 /*
  * Unknown hash algorithm...
  */

  _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown hash algorithm."), 1);

  return (-1);

 /*
  * We get here if the buffer is too small.
  */

  too_small:

  _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Hash buffer too small."), 1);
  return (-1);
}
Exemplo n.º 28
0
//http://iphonedevwiki.net/index.php/Lockdownd
void get_device_infos(CFMutableDictionaryRef out) {
    CC_SHA1_CTX sha1ctx;
    uint8_t udid[20];
    char udid1[100];
    CFStringRef serial;
    CFStringRef imei;
    CFStringRef macwifi;
    CFStringRef macbt;
    
    CFStringRef hw = copy_hardware_model(); 
    if (hw != NULL)
    {
        CFDictionaryAddValue(out, CFSTR("hwModel"), hw);
        CFRelease(hw);
    }
    
    serial = copy_device_serial_number();
    imei = copy_device_imei();
    macwifi = copy_wifi_mac_address();
    macbt = copy_bluetooth_mac_address();
    
    CFMutableStringRef udidInput = CFStringCreateMutable(kCFAllocatorDefault, 0);
    if (serial != NULL)
    {
        CFStringAppend(udidInput, serial);
        CFDictionaryAddValue(out, CFSTR("serialNumber"), serial);
        CFRelease(serial);
    }
    
    uint64_t _ecid = 0;
    CFNumberRef ecid = copyNumberFromChosen(CFSTR("unique-chip-id"));
    if (ecid != NULL)
    {
        CFDictionaryAddValue(out, CFSTR("ECID"), ecid);
    }
    
    if (ecid != NULL && useNewUDID(hw))
    {
        CFNumberGetValue(ecid, kCFNumberSInt64Type, &_ecid);
        CFStringAppendFormat(udidInput, NULL, CFSTR("%llu"), _ecid);
    }
    else if (imei != NULL)
    {
        CFStringAppend(udidInput, imei);
        CFDictionaryAddValue(out, CFSTR("imei"), imei);
        CFRelease(imei);
    }
    if (macwifi != NULL)
    {
        CFStringAppend(udidInput, macwifi);
        CFDictionaryAddValue(out, CFSTR("wifiMac"), macwifi);
        CFRelease(macwifi);
    }
    if (macbt != NULL)
    {
        CFStringAppend(udidInput, macbt);
        CFDictionaryAddValue(out, CFSTR("btMac"), macbt);
        CFRelease(macbt);
    }
    
    CFStringGetCString(udidInput, udid1, 99, kCFStringEncodingASCII);
    
    CC_SHA1_Init(&sha1ctx);
    CC_SHA1_Update(&sha1ctx, udid1, CFStringGetLength(udidInput));
    CC_SHA1_Final(udid, &sha1ctx);
    
    CFRelease(udidInput);
    addHexaString(out, CFSTR("udid"), udid, 20);

}
Exemplo n.º 29
0
char *
mit_krb5_pkinit_cert_hash_str(const mit_krb5_data *cert)
{
#ifdef HAVE_COMMONCRYPTO_COMMONDIGEST_H

    CC_SHA1_CTX ctx;
    char *outstr, *cpOut;
    unsigned char digest[CC_SHA1_DIGEST_LENGTH];
    unsigned i;
    
    LOG_ENTRY();

    CC_SHA1_Init(&ctx);
    CC_SHA1_Update(&ctx, cert->data, cert->length);
    CC_SHA1_Final(digest, &ctx);
    
    cpOut = outstr = (char *)malloc((2 * CC_SHA1_DIGEST_LENGTH) + 1);
    if(outstr == NULL)
	return NULL;

    for(i = 0; i < CC_SHA1_DIGEST_LENGTH; i++, cpOut += 2)
	sprintf(cpOut, "%02X", (unsigned)digest[i]);
    *cpOut = '\0';
    return outstr;

#elif defined(_WIN32)

    HCRYPTPROV  hProv = 0;
    HCRYPTHASH  hHash = 0;
    char        *outstr = NULL;
    char        *outpos;
    size_t      cch_left;
    BYTE        *hash = NULL;
    DWORD       hashSize = 0;
    DWORD       len, i;

    LOG_ENTRY();

    if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_SIG, CRYPT_VERIFYCONTEXT)) {
        LOG_LASTERROR("CryptAcquireContext failed");
        goto done;
    }

    if (!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash)) {
        LOG_LASTERROR("CryptCreateHash failed");
        goto done;
    }

    if (!CryptHashData(hHash, (BYTE *) cert->data, cert->length, 0)) {
        LOG_LASTERROR("CryptHashData failed");
        goto done;
    }

    len = sizeof(hashSize);
    if (!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *) &hashSize, &len, 0)) {
        LOG_LASTERROR("CryptGetHashParam failed while getting hash size");
        goto done;
    }

    hash = malloc(hashSize);
    if (hash == NULL) {
        goto done;
    }

    len = hashSize;
    if (!CryptGetHashParam(hHash, HP_HASHVAL, hash, &len, 0)) {
        LOG_LASTERROR("CryptGetHashParam failed while getting hash");
        goto done;
    }

    outstr = malloc(hashSize * 2 + 1);
    if (outstr == NULL) {
        goto done;
    }

    outpos = outstr;
    cch_left = hashSize * 2 + 1;
    for (i = 0; i < hashSize; i++) {
        StringCchPrintfExA(outpos, cch_left, &outpos, &cch_left, STRSAFE_FILL_ON_FAILURE,
                           "%02X", (unsigned) hash[i]);
    }

    *outpos = '\0';

done:

    if (hHash != 0)
        CryptDestroyHash(hHash);

    if (hProv != 0)
        CryptReleaseContext(hProv, 0);

    if (hash != NULL)
        free(hash);

    return outstr;

#endif
}
Exemplo n.º 30
0
void SHA1Object::digestUpdate(
	const void 	*data, 
	size_t 		len)
{
	CC_SHA1_Update(&mCtx, (const unsigned char *)data, len);
}