static void ssl_mac_sha1(uint8_t *secret, uint8_t *buf, size_t len, uint8_t *ctr, int type) { uint8_t header[11]; uint8_t padding[40]; sha1_context sha1; memcpy(header, ctr, 8); header[8] = (uint8_t)type; header[9] = (uint8_t)(len >> 8); header[10] = (uint8_t)(len); memset(padding, 0x36, 40); sha1_starts(&sha1); sha1_update(&sha1, secret, 20); sha1_update(&sha1, padding, 40); sha1_update(&sha1, header, 11); sha1_update(&sha1, buf, len); sha1_finish(&sha1, buf + len); memset(padding, 0x5C, 40); sha1_starts(&sha1); sha1_update(&sha1, secret, 20); sha1_update(&sha1, padding, 40); sha1_update(&sha1, buf + len, 20); sha1_finish(&sha1, buf + len); }
/** * Fill an authentication block in a request. * This func can create the first as well as the second auth block (for * double authorized commands). * * @param request pointer to the request (w/ uninitialised auth data) * @param request_len0 length of the request without auth data * @param handles_len length of the handles area in request * @param auth_session pointer to the (valid) auth session to be used * @param request_auth pointer to the auth block of the request to be filled * @param auth authentication data (HMAC key) */ static u32 create_request_auth(const void *request, size_t request_len0, size_t handles_len, struct session_data *auth_session, void *request_auth, const void *auth) { u8 hmac_data[DIGEST_LENGTH * 3 + 1]; sha1_context hash_ctx; const size_t command_code_offset = 6; const size_t auth_nonce_odd_offset = 4; const size_t auth_continue_offset = 24; const size_t auth_auth_offset = 25; if (!auth_session || !auth_session->valid) return TPM_LIB_ERROR; sha1_starts(&hash_ctx); sha1_update(&hash_ctx, request + command_code_offset, 4); if (request_len0 > TPM_REQUEST_HEADER_LENGTH + handles_len) sha1_update(&hash_ctx, request + TPM_REQUEST_HEADER_LENGTH + handles_len, request_len0 - TPM_REQUEST_HEADER_LENGTH - handles_len); sha1_finish(&hash_ctx, hmac_data); sha1_starts(&hash_ctx); sha1_update(&hash_ctx, auth_session->nonce_odd, DIGEST_LENGTH); sha1_update(&hash_ctx, hmac_data, sizeof(hmac_data)); sha1_finish(&hash_ctx, auth_session->nonce_odd); if (pack_byte_string(request_auth, TPM_REQUEST_AUTH_LENGTH, "dsb", 0, auth_session->handle, auth_nonce_odd_offset, auth_session->nonce_odd, DIGEST_LENGTH, auth_continue_offset, 1)) return TPM_LIB_ERROR; if (pack_byte_string(hmac_data, sizeof(hmac_data), "ss", DIGEST_LENGTH, auth_session->nonce_even, DIGEST_LENGTH, 2 * DIGEST_LENGTH, request_auth + auth_nonce_odd_offset, DIGEST_LENGTH + 1)) return TPM_LIB_ERROR; sha1_hmac(auth, DIGEST_LENGTH, hmac_data, sizeof(hmac_data), request_auth + auth_auth_offset); return TPM_SUCCESS; }
void Connection_fingerprint_from_cert(Connection *conn) { x509_cert* _x509P = conn->iob->ssl.peer_cert; int i = 0; debug("Connection_send_to_handler: peer_cert: %016lX: tag=%d length=%ld", (unsigned long) _x509P, _x509P ? _x509P->raw.tag : -1, _x509P ? _x509P->raw.len : -1); if (_x509P != NULL && _x509P->raw.len > 0) { sha1_context ctx; unsigned char sha1sum[CERT_FINGERPRINT_SIZE + 1] = {0}; sha1_starts(&ctx); sha1_update(&ctx, _x509P->raw.p, _x509P->raw.len); sha1_finish(&ctx, sha1sum); bstring hex = bfromcstr(""); for (i = 0; i < (int)sizeof(sha1sum); i++) { bformata(hex, "%02X", sha1sum[i]); } Request_set(conn->req, &PEER_CERT_SHA1_KEY, hex, 1); } }
/* * Perform the MPPE rekey algorithm, from RFC 3078, sec. 7.3. * Well, not what's written there, but rather what they meant. */ static void mppe_rekey(ppp_mppe_state * state, int initial_key) { sha1_context sha1_ctx; u8_t sha1_digest[SHA1_SIGNATURE_SIZE]; /* * Key Derivation, from RFC 3078, RFC 3079. * Equivalent to Get_Key() for MS-CHAP as described in RFC 3079. */ sha1_starts(&sha1_ctx); sha1_update(&sha1_ctx, state->master_key, state->keylen); sha1_update(&sha1_ctx, mppe_sha1_pad1, SHA1_PAD_SIZE); sha1_update(&sha1_ctx, state->session_key, state->keylen); sha1_update(&sha1_ctx, mppe_sha1_pad2, SHA1_PAD_SIZE); sha1_finish(&sha1_ctx, sha1_digest); MEMCPY(state->session_key, sha1_digest, state->keylen); if (!initial_key) { arc4_setup(&state->arc4, sha1_digest, state->keylen); arc4_crypt(&state->arc4, state->session_key, state->keylen); } if (state->keylen == 8) { /* See RFC 3078 */ state->session_key[0] = 0xd1; state->session_key[1] = 0x26; state->session_key[2] = 0x9e; } arc4_setup(&state->arc4, state->session_key, state->keylen); }
CryptoSha1 crypto_sha1_init(void) { CryptoSha1 sha1 = xmalloc(sizeof(*sha1)); sha1_starts(&sha1->ctx); return sha1; }
static int hash_init_sha1(struct hash_algo *algo, void **ctxp) { sha1_context *ctx = malloc(sizeof(sha1_context)); sha1_starts(ctx); *ctxp = ctx; return 0; }
int ssl_init( ssl_context *ssl ) { int len = SSL_BUFFER_LEN; memset( ssl, 0, sizeof( ssl_context ) ); ssl->in_ctr = (unsigned char *) malloc( len ); ssl->in_hdr = ssl->in_ctr + 8; ssl->in_msg = ssl->in_ctr + 13; if( ssl->in_ctr == NULL ){ SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len ) ); return( 1 ); } ssl->out_ctr = (unsigned char *) malloc( len ); ssl->out_hdr = ssl->out_ctr + 8; ssl->out_msg = ssl->out_ctr + 13; if( ssl->out_ctr == NULL ) { SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed", len ) ); free( ssl-> in_ctr ); return( 1 ); } memset( ssl-> in_ctr, 0, SSL_BUFFER_LEN ); memset( ssl->out_ctr, 0, SSL_BUFFER_LEN ); ssl->hostname = NULL; ssl->hostname_len = 0; md5_starts( &ssl->fin_md5 ); sha1_starts( &ssl->fin_sha1 ); return 0; }
/** * Verify an authentication block in a response. * Since this func updates the nonce_even in the session data it has to be * called when receiving a succesfull AUTH response. * This func can verify the first as well as the second auth block (for * double authorized commands). * * @param command_code command code of the request * @param response pointer to the request (w/ uninitialised auth data) * @param handles_len length of the handles area in response * @param auth_session pointer to the (valid) auth session to be used * @param response_auth pointer to the auth block of the response to be verified * @param auth authentication data (HMAC key) */ static u32 verify_response_auth(u32 command_code, const void *response, size_t response_len0, size_t handles_len, struct session_data *auth_session, const void *response_auth, const void *auth) { u8 hmac_data[DIGEST_LENGTH * 3 + 1]; u8 computed_auth[DIGEST_LENGTH]; sha1_context hash_ctx; const size_t return_code_offset = 6; const size_t auth_continue_offset = 20; const size_t auth_auth_offset = 21; u8 auth_continue; if (!auth_session || !auth_session->valid) return TPM_AUTHFAIL; if (pack_byte_string(hmac_data, sizeof(hmac_data), "d", 0, command_code)) return TPM_LIB_ERROR; if (response_len0 < TPM_RESPONSE_HEADER_LENGTH) return TPM_LIB_ERROR; sha1_starts(&hash_ctx); sha1_update(&hash_ctx, response + return_code_offset, 4); sha1_update(&hash_ctx, hmac_data, 4); if (response_len0 > TPM_RESPONSE_HEADER_LENGTH + handles_len) sha1_update(&hash_ctx, response + TPM_RESPONSE_HEADER_LENGTH + handles_len, response_len0 - TPM_RESPONSE_HEADER_LENGTH - handles_len); sha1_finish(&hash_ctx, hmac_data); memcpy(auth_session->nonce_even, response_auth, DIGEST_LENGTH); auth_continue = ((u8 *)response_auth)[auth_continue_offset]; if (pack_byte_string(hmac_data, sizeof(hmac_data), "ssb", DIGEST_LENGTH, response_auth, DIGEST_LENGTH, 2 * DIGEST_LENGTH, auth_session->nonce_odd, DIGEST_LENGTH, 3 * DIGEST_LENGTH, auth_continue)) return TPM_LIB_ERROR; sha1_hmac(auth, DIGEST_LENGTH, hmac_data, sizeof(hmac_data), computed_auth); if (memcmp(computed_auth, response_auth + auth_auth_offset, DIGEST_LENGTH)) return TPM_AUTHFAIL; return TPM_SUCCESS; }
int sceKernelUtilsSha1BlockInit(u32 ctxAddr) { DEBUG_LOG(HLE, "sceKernelUtilsSha1BlockInit(%08x)", ctxAddr); if (!Memory::IsValidAddress(ctxAddr)) return -1; // TODO: Until I know how large a context is, we just go all lazy and use a global context, // which will work just fine unless games do several MD5 concurrently. sha1_starts(&sha1_ctx); return 0; }
void sha1_calculate(const struct image_region region[], int region_count, uint8_t *checksum) { sha1_context ctx; uint32_t i; i = 0; sha1_starts(&ctx); for (i = 0; i < region_count; i++) sha1_update(&ctx, region[i].data, region[i].size); sha1_finish(&ctx, checksum); }
static void cms_verify_msg_digest(proto_item *pi, tvbuff_t *content, const char *alg, tvbuff_t *tvb, int offset) { sha1_context sha1_ctx; md5_state_t md5_ctx; int i= 0, buffer_size = 0; /* we only support two algorithms at the moment - if we do add SHA2 we should add a registration process to use a registration process */ if(strcmp(alg, HASH_SHA1) == 0) { sha1_starts(&sha1_ctx); sha1_update(&sha1_ctx, tvb_get_ptr(content, 0, tvb_length(content)), tvb_length(content)); sha1_finish(&sha1_ctx, digest_buf); buffer_size = SHA1_BUFFER_SIZE; } else if(strcmp(alg, HASH_MD5) == 0) { md5_init(&md5_ctx); md5_append(&md5_ctx, tvb_get_ptr(content, 0, tvb_length(content)), tvb_length(content)); md5_finish(&md5_ctx, digest_buf); buffer_size = MD5_BUFFER_SIZE; } if(buffer_size) { /* compare our computed hash with what we have received */ if(tvb_bytes_exist(tvb, offset, buffer_size) && (memcmp(tvb_get_ptr(tvb, offset, buffer_size), digest_buf, buffer_size) != 0)) { proto_item_append_text(pi, " [incorrect, should be "); for(i = 0; i < buffer_size; i++) proto_item_append_text(pi, "%02X", digest_buf[i]); proto_item_append_text(pi, "]"); } else proto_item_append_text(pi, " [correct]"); } else { proto_item_append_text(pi, " [unable to verify]"); } }
u32 getFunctionId(const char* name) { const char* suffix = "\x67\x59\x65\x99\x04\x25\x04\x90\x56\x64\x27\x49\x94\x89\x74\x1A"; // Symbol name suffix u8 output[20]; // Compute SHA-1 hash sha1_context ctx; sha1_starts(&ctx); sha1_update(&ctx, (const u8*)name, strlen(name)); sha1_update(&ctx, (const u8*)suffix, strlen(suffix)); sha1_finish(&ctx, output); return (u32&)output[0]; }
void Sha::Reset(){ if(_bits==sha_160){ sha1_starts(tvcast<sha1_context>(_sha_ctx)); }else if(_bits==sha_224){ sha2_starts(tvcast<sha2_context>(_sha_ctx),1); }else if(_bits==sha_256){ sha2_starts(tvcast<sha2_context>(_sha_ctx),0); }else if(_bits==sha_384){ sha4_starts(tvcast<sha4_context>(_sha_ctx),1); }else if(_bits==sha_512){ sha4_starts(tvcast<sha4_context>(_sha_ctx),0); }else{ _ASSERT(0); } }
extern u32 ppu_generate_id(const char* name) { // Symbol name suffix const auto suffix = "\x67\x59\x65\x99\x04\x25\x04\x90\x56\x64\x27\x49\x94\x89\x74\x1A"; sha1_context ctx; u8 output[20]; // Compute SHA-1 hash sha1_starts(&ctx); sha1_update(&ctx, reinterpret_cast<const u8*>(name), std::strlen(name)); sha1_update(&ctx, reinterpret_cast<const u8*>(suffix), std::strlen(suffix)); sha1_finish(&ctx, output); return reinterpret_cast<le_t<u32>&>(output[0]); }
void ssl_calc_verify(ssl_context * ssl, uint8_t hash[36]) { md5_context md5; sha1_context sha1; uint8_t pad_1[48]; uint8_t pad_2[48]; SSL_DEBUG_MSG(2, ("=> calc verify")); memcpy(&md5, &ssl->fin_md5, sizeof(md5_context)); memcpy(&sha1, &ssl->fin_sha1, sizeof(sha1_context)); if (ssl->minor_ver == SSL_MINOR_VERSION_0) { memset(pad_1, 0x36, 48); memset(pad_2, 0x5C, 48); md5_update(&md5, ssl->session->master, 48); md5_update(&md5, pad_1, 48); md5_finish(&md5, hash); md5_starts(&md5); md5_update(&md5, ssl->session->master, 48); md5_update(&md5, pad_2, 48); md5_update(&md5, hash, 16); md5_finish(&md5, hash); sha1_update(&sha1, ssl->session->master, 48); sha1_update(&sha1, pad_1, 40); sha1_finish(&sha1, hash + 16); sha1_starts(&sha1); sha1_update(&sha1, ssl->session->master, 48); sha1_update(&sha1, pad_2, 40); sha1_update(&sha1, hash + 16, 20); sha1_finish(&sha1, hash + 16); } else { /* TLSv1 */ md5_finish(&md5, hash); sha1_finish(&sha1, hash + 16); } SSL_DEBUG_BUF(3, "calculated verify result", hash, 36); SSL_DEBUG_MSG(2, ("<= calc verify")); return; }
static int sha1_sum (lua_State *L) { size_t lmsg; char *msg = (char*)luaL_checklstring(L, 1, &lmsg); /* message */ sha1_context ctx; char result[20]; sha1_starts(&ctx); sha1_update(&ctx, msg, lmsg); sha1_finish(&ctx, result); memset(&ctx, 0, sizeof(sha1_context)); lua_pushstring(L, result); /* digest */ return 1; }
/* * SHA-1 HMAC context setup */ void sha1_hmac_starts( sha1_context *ctx, const unsigned char *key, size_t keylen ) { if( keylen > 64 ) // Key shortened if greater than BLOCK SIZE (64 bytes) { sha1_context cty; sha1_init(&cty); sha1_starts(&cty); sha1_update(&cty, key, keylen); // Get the 20 char digest of the key sha1_finish(&cty, ctx->key); // Store the digest in ctx.key sha1_free(&cty); ctx->keyLen = 20; } else { ctx->keyLen = keylen; // Use the key as is memcpy(ctx->key, key, keylen); // Store the key in ctx.key } }
void cSHA1Checksum::Restart(void) { sha1_starts(&m_Sha1); m_DoesAcceptInput = true; }
cSHA1Checksum::cSHA1Checksum(void) : m_DoesAcceptInput(true) { sha1_starts(&m_Sha1); }
static void sha1_starts_wrap( void *ctx ) { sha1_starts( (sha1_context *) ctx ); }
void CServer::RunOTThread() { cout << "\not thread started\n" << flush; // IKNP-first step: receiver of Naor-Pinkas ZZ& p = CConfig::GetInstance()->GetPrime(); ZZ q = p/2 - 1; ZZ& g = CConfig::GetInstance()->GetGenerator(); // NP receiver: receive Cs int nBufSize = NUM_EXECS_NAOR_PINKAS * FIELD_SIZE_IN_BYTES; BYTE* pBuf = new BYTE[nBufSize]; m_sockOT.Receive(pBuf, nBufSize); ZZ* pC = new ZZ[NUM_EXECS_NAOR_PINKAS]; BYTE* pBufIdx = pBuf; for(int i=0, idx=0; i<NUM_EXECS_NAOR_PINKAS; i++) { ZZFromBytes(pC[i], pBufIdx, FIELD_SIZE_IN_BYTES); pBufIdx += FIELD_SIZE_IN_BYTES; #ifdef _DEBUG cout << "pC[" << i <<"]: " << pC[i] << endl; #endif } // compute pk0, pk1 CBitVector rnd; rnd.Create(NUM_EXECS_NAOR_PINKAS*FIELD_SIZE_IN_BITS, m_aSeed, m_nCounter); BYTE* pBufRnd = rnd.GetArr(); ZZ* pK = new ZZ[NUM_EXECS_NAOR_PINKAS]; ZZ ztmp; for(int i=0, idx=0; !m_bStop && i<NUM_EXECS_NAOR_PINKAS; i++) { ZZFromBytes(ztmp, pBufRnd, FIELD_SIZE_IN_BYTES); pBufRnd += FIELD_SIZE_IN_BYTES; rem(pK[i], ztmp, q); } pBufIdx = pBuf; ZZ pk0, pk1; for(int i=0, idx=0; !m_bStop && i<NUM_EXECS_NAOR_PINKAS; i++) { // compute pk0, pk1 if( !m_S.GetBit(i) ) { PowerMod(pk0, g, pK[i], p); } else { PowerMod(pk1, g, pK[i], p); //pk0 = pC[i]/pk1; InvMod(ztmp, pk1, p); MulMod(pk0, pC[i], ztmp, p); } #ifdef _DEBUG cout << "pk0[" << i << "]: " << pk0 << endl; #endif // put pk0 BytesFromZZ(pBufIdx, pk0, FIELD_SIZE_IN_BYTES); pBufIdx += FIELD_SIZE_IN_BYTES; } m_sockOT.Send(pBuf, nBufSize); delete [] pC; delete [] pBuf; if( m_bStop ) return; // NP receiver: get the g^r0, Enc(M0), g^r2, Enc(M1) int nInputStart = m_pCircuit->GetInputStart(ID_CLIENT); int nInputEnd = m_pCircuit->GetInputEnd(ID_CLIENT); int nMsgSize = (nInputEnd-nInputStart)/SHA1_BITS + 1; // in sha1 scale int nMsginOT = FIELD_SIZE_IN_BYTES + nMsgSize*SHA1_BYTES; int nBufSize2 = NUM_EXECS_NAOR_PINKAS * nMsginOT * 2; BYTE* pBuf2 = new BYTE[nBufSize2]; m_sockOT.Receive(pBuf2, nBufSize2); ZZ w; ZZ key; BYTE tmp[FIELD_SIZE_IN_BYTES]; sha1_context sha; SHA_BUFFER buf_key; BYTE** ppMat = new BYTE*[NUM_EXECS_NAOR_PINKAS]; BYTE* pBufToRead; BYTE* pBufMatIdx; pBufIdx = pBuf2; for(int i=0, idx=0; !m_bStop && i<NUM_EXECS_NAOR_PINKAS; i++) { ppMat[i] = new BYTE[nMsgSize*SHA1_BYTES]; if( !m_S.GetBit(i)) { pBufToRead = pBufIdx; pBufIdx += nMsginOT + nMsginOT; } else { pBufIdx += nMsginOT; pBufToRead = pBufIdx; pBufIdx += nMsginOT; } ZZFromBytes(w, pBufToRead, FIELD_SIZE_IN_BYTES); pBufToRead += FIELD_SIZE_IN_BYTES; PowerMod(key, w, pK[i], p); BytesFromZZ(tmp, key, FIELD_SIZE_IN_BYTES); sha1_starts(&sha); sha1_update(&sha, tmp, FIELD_SIZE_IN_BYTES); sha1_finish(&sha, (BYTE*) &buf_key); pBufMatIdx=ppMat[i]; for(int j=0; j<nMsgSize; j++) { sha1_starts(&sha); sha1_update(&sha, (BYTE*) &buf_key, sizeof(buf_key)); sha1_update(&sha, (BYTE*) &j, sizeof(int)); sha1_finish(&sha, tmp); for(int x=0; x<SHA1_BYTES; x++, pBufMatIdx++, pBufToRead++ ) { *(pBufMatIdx) = *(pBufToRead) ^ tmp[x]; } } } delete [] pK; if( m_bStop ) return; // IKNP-second step: send the keys for client inputs int nInputSize = nInputEnd - nInputStart + 1; KEY* pKeys = new KEY[nInputSize*2]; YAO_WIRE* wire; KEY* wirekey; CBitVector qj; qj.Create(NUM_EXECS_NAOR_PINKAS); int j=0; // 0-starting index KEY* pKeyIdx = pKeys; for(int i=nInputStart; !m_bStop && i<=nInputEnd; i++,j++) { while( m_nGatesDone < i ) { SleepMiliSec(100); } // compute qj for(int r=0; r<NUM_EXECS_NAOR_PINKAS; r++) { qj.SetBit( r, ppMat[r][j/8] & bitmask[j & 0x7] ); } // compute hash sha1_starts(&sha); sha1_update(&sha, qj.GetArr(), NUM_EXECS_NAOR_PINKAS/8); sha1_update(&sha, (BYTE*)&j, sizeof(int)); sha1_finish(&sha, (BYTE*)&buf_key); // y0 wire = m_pYaoWires+i; wirekey = wire->keys + wire->b; XOR_KEYP3( pKeyIdx, (&buf_key), wirekey ); pKeyIdx++; // compute qj xor s for(int x=0; x<NUM_EXECS_NAOR_PINKAS/8; x++ ) qj.GetArr()[x] ^= m_S.GetByte(x); /* #ifdef _DEBUG cout << "qj xor s = "; for(int z=0; z<NUM_EXECS_NAOR_PINKAS; z++) cout << (int) qj.GetBit(z); cout << endl; #endif */ // y1 sha1_starts(&sha); sha1_update(&sha, qj.GetArr(), NUM_EXECS_NAOR_PINKAS/8); sha1_update(&sha, (BYTE*)&j, sizeof(int)); sha1_finish(&sha, (BYTE*)&buf_key); wirekey = wire->keys + (wire->b^1); XOR_KEYP3( pKeyIdx, (&buf_key), wirekey ); pKeyIdx++; } m_sockOT.Send( pKeys, nInputSize*sizeof(KEY)*2); // clean-up delete [] pBuf2; for(int i=0; i<NUM_EXECS_NAOR_PINKAS; i++) { delete [] ppMat[i]; } delete [] ppMat; delete [] pKeys; cout << "\not thread ended \n" << flush; }
static int optimus_sha1sum_verify_partition(const char* partName, const u64 verifyLen, const u8 imgType, u8* genSum) { int ret = 0; u8* buff = (u8*) OPTIMUS_SHA1SUM_BUFFER_ADDR; const u32 buffSz = OPTIMUS_SHA1SUM_BUFFER_LEN; sha1_context ctx; u64 leftLen = verifyLen; if(strcmp(partName, OptimusImgBurnInfo.partName)){ DWN_ERR("partName %s err, must %s\n", partName, OptimusImgBurnInfo.partName); return OPT_DOWN_FAIL; } if(!is_optimus_burn_complete()){ return OPT_DOWN_FAIL; } memset(buff, 0xde, 1024);//clear 1kb data before verfiy, in case read buffer not overlapped if(IMG_TYPE_BOOTLOADER == imgType) { return optimus_verify_bootloader(&OptimusImgBurnInfo, genSum); } else if(IMG_TYPE_SPARSE == imgType)//sparse image { ret = optimus_sparse_back_info_probe(); if(OPT_DOWN_TRUE != ret){ DWN_ERR("Fail to probe back sparse info\n"); return OPT_DOWN_FAIL; } } ret = optimus_storage_open(&OptimusImgBurnInfo, NULL, 0); if(ret){ DWN_ERR("Fail to open storage for read\n"); return OPT_DOWN_FAIL; } sha1_starts(&ctx); DWN_MSG("To verify part %s in fmt %s\n", partName, (IMG_TYPE_SPARSE == imgType) ? "sparse": "normal"); if(IMG_TYPE_SPARSE == imgType)//sparse image { for(; leftLen;) { u32 spHeadSz = 0; u32 chunkDataLen = 0; u64 chunkDataOffset = 0; u8* head = NULL; ret = optimus_sparse_get_chunk_data(&head, &spHeadSz, &chunkDataLen, &chunkDataOffset); if(ret){ DWN_ERR("Fail to get chunk data\n"); goto _finish; } sha1_update(&ctx, head, spHeadSz); leftLen -= spHeadSz + chunkDataLen;//update image read info for(;chunkDataLen;) { const int thisReadLen = (chunkDataLen > buffSz) ? buffSz : chunkDataLen; ret = optimus_storage_read(&OptimusImgBurnInfo, chunkDataOffset, thisReadLen, buff, NULL); if(ret){ DWN_ERR("Fail to read at offset 0x[%x, %8x], len=0x%8x\n", ((u32)(chunkDataOffset>>32)), (u32)chunkDataOffset, thisReadLen); goto _finish; } sha1_update(&ctx, buff, thisReadLen); chunkDataLen -= thisReadLen; chunkDataOffset += thisReadLen; } if(leftLen && !spHeadSz) { DWN_ERR("Fail to read when pkt len left 0x%x\n", (u32)leftLen); break; } } } else//normal image { for(; leftLen;)
int ssl_derive_keys(ssl_context * ssl) { size_t i; md5_context md5; sha1_context sha1; uint8_t tmp[64]; uint8_t padding[16]; uint8_t sha1sum[20]; uint8_t keyblk[256]; uint8_t *key1; uint8_t *key2; SSL_DEBUG_MSG(2, ("=> derive keys")); /* * SSLv3: * master = * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) + * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) + * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) ) * * TLSv1: * master = PRF( premaster, "master secret", randbytes )[0..47] */ if (ssl->resume == 0) { size_t len = ssl->pmslen; SSL_DEBUG_BUF(3, "premaster secret", ssl->premaster, len); if (ssl->minor_ver == SSL_MINOR_VERSION_0) { for (i = 0; i < 3; i++) { memset(padding, 'A' + i, 1 + i); sha1_starts(&sha1); sha1_update(&sha1, padding, 1 + i); sha1_update(&sha1, ssl->premaster, len); sha1_update(&sha1, ssl->randbytes, 64); sha1_finish(&sha1, sha1sum); md5_starts(&md5); md5_update(&md5, ssl->premaster, len); md5_update(&md5, sha1sum, 20); md5_finish(&md5, ssl->session->master + i * 16); } } else tls1_prf(ssl->premaster, len, "master secret", ssl->randbytes, 64, ssl->session->master, 48); memset(ssl->premaster, 0, sizeof(ssl->premaster)); } else SSL_DEBUG_MSG(3, ("no premaster (session resumed)")); /* * Swap the client and server random values. */ memcpy(tmp, ssl->randbytes, 64); memcpy(ssl->randbytes, tmp + 32, 32); memcpy(ssl->randbytes + 32, tmp, 32); memset(tmp, 0, sizeof(tmp)); /* * SSLv3: * key block = * MD5( master + SHA1( 'A' + master + randbytes ) ) + * MD5( master + SHA1( 'BB' + master + randbytes ) ) + * MD5( master + SHA1( 'CCC' + master + randbytes ) ) + * MD5( master + SHA1( 'DDDD' + master + randbytes ) ) + * ... * * TLSv1: * key block = PRF( master, "key expansion", randbytes ) */ if (ssl->minor_ver == SSL_MINOR_VERSION_0) { for (i = 0; i < 16; i++) { memset(padding, 'A' + i, 1 + i); sha1_starts(&sha1); sha1_update(&sha1, padding, 1 + i); sha1_update(&sha1, ssl->session->master, 48); sha1_update(&sha1, ssl->randbytes, 64); sha1_finish(&sha1, sha1sum); md5_starts(&md5); md5_update(&md5, ssl->session->master, 48); md5_update(&md5, sha1sum, 20); md5_finish(&md5, keyblk + i * 16); } memset(&md5, 0, sizeof(md5)); memset(&sha1, 0, sizeof(sha1)); memset(padding, 0, sizeof(padding)); memset(sha1sum, 0, sizeof(sha1sum)); } else tls1_prf(ssl->session->master, 48, "key expansion", ssl->randbytes, 64, keyblk, 256); SSL_DEBUG_MSG(3, ("cipher = %s", ssl_get_cipher(ssl))); SSL_DEBUG_BUF(3, "master secret", ssl->session->master, 48); SSL_DEBUG_BUF(4, "random bytes", ssl->randbytes, 64); SSL_DEBUG_BUF(4, "key block", keyblk, 256); memset(ssl->randbytes, 0, sizeof(ssl->randbytes)); /* * Determine the appropriate key, IV and MAC length. */ switch (ssl->session->cipher) { #if defined(TROPICSSL_ARC4) case TLS_RSA_WITH_RC4_128_MD5: ssl->keylen = 16; ssl->minlen = 16; ssl->ivlen = 0; ssl->maclen = 16; break; case TLS_RSA_WITH_RC4_128_SHA: ssl->keylen = 16; ssl->minlen = 20; ssl->ivlen = 0; ssl->maclen = 20; break; #endif #if defined(TROPICSSL_DES) case TLS_RSA_WITH_3DES_EDE_CBC_SHA: case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: ssl->keylen = 24; ssl->minlen = 24; ssl->ivlen = 8; ssl->maclen = 20; break; #endif #if defined(TROPICSSL_AES) case TLS_RSA_WITH_AES_128_CBC_SHA: ssl->keylen = 16; ssl->minlen = 32; ssl->ivlen = 16; ssl->maclen = 20; break; case TLS_RSA_WITH_AES_256_CBC_SHA: case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: ssl->keylen = 32; ssl->minlen = 32; ssl->ivlen = 16; ssl->maclen = 20; break; #endif #if defined(TROPICSSL_CAMELLIA) case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: ssl->keylen = 16; ssl->minlen = 32; ssl->ivlen = 16; ssl->maclen = 20; break; case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: ssl->keylen = 32; ssl->minlen = 32; ssl->ivlen = 16; ssl->maclen = 20; break; #endif default: SSL_DEBUG_MSG(1, ("cipher %s is not available", ssl_get_cipher(ssl))); return (TROPICSSL_ERR_SSL_FEATURE_UNAVAILABLE); } SSL_DEBUG_MSG(3, ("keylen: %d, minlen: %d, ivlen: %d, maclen: %d", ssl->keylen, ssl->minlen, ssl->ivlen, ssl->maclen)); /* * Finally setup the cipher contexts, IVs and MAC secrets. */ if (ssl->endpoint == SSL_IS_CLIENT) { key1 = keyblk + ssl->maclen * 2; key2 = keyblk + ssl->maclen * 2 + ssl->keylen; memcpy(ssl->mac_enc, keyblk, ssl->maclen); memcpy(ssl->mac_dec, keyblk + ssl->maclen, ssl->maclen); memcpy(ssl->iv_enc, key2 + ssl->keylen, ssl->ivlen); memcpy(ssl->iv_dec, key2 + ssl->keylen + ssl->ivlen, ssl->ivlen); } else { key1 = keyblk + ssl->maclen * 2 + ssl->keylen; key2 = keyblk + ssl->maclen * 2; memcpy(ssl->mac_dec, keyblk, ssl->maclen); memcpy(ssl->mac_enc, keyblk + ssl->maclen, ssl->maclen); memcpy(ssl->iv_dec, key1 + ssl->keylen, ssl->ivlen); memcpy(ssl->iv_enc, key1 + ssl->keylen + ssl->ivlen, ssl->ivlen); } switch (ssl->session->cipher) { #if defined(TROPICSSL_ARC4) case TLS_RSA_WITH_RC4_128_MD5: case TLS_RSA_WITH_RC4_128_SHA: arc4_setup((arc4_context *) ssl->ctx_enc, key1, ssl->keylen); arc4_setup((arc4_context *) ssl->ctx_dec, key2, ssl->keylen); break; #endif #if defined(TROPICSSL_DES) case TLS_RSA_WITH_3DES_EDE_CBC_SHA: case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA: des3_set3key_enc((des3_context *) ssl->ctx_enc, key1); des3_set3key_dec((des3_context *) ssl->ctx_dec, key2); break; #endif #if defined(TROPICSSL_AES) case TLS_RSA_WITH_AES_128_CBC_SHA: aes_setkey_enc((aes_context *) ssl->ctx_enc, key1, 128); aes_setkey_dec((aes_context *) ssl->ctx_dec, key2, 128); break; case TLS_RSA_WITH_AES_256_CBC_SHA: case TLS_DHE_RSA_WITH_AES_256_CBC_SHA: aes_setkey_enc((aes_context *) ssl->ctx_enc, key1, 256); aes_setkey_dec((aes_context *) ssl->ctx_dec, key2, 256); break; #endif #if defined(TROPICSSL_CAMELLIA) case TLS_RSA_WITH_CAMELLIA_128_CBC_SHA: camellia_setkey_enc((camellia_context *) ssl->ctx_enc, key1, 128); camellia_setkey_dec((camellia_context *) ssl->ctx_dec, key2, 128); break; case TLS_RSA_WITH_CAMELLIA_256_CBC_SHA: case TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA: camellia_setkey_enc((camellia_context *) ssl->ctx_enc, key1, 256); camellia_setkey_dec((camellia_context *) ssl->ctx_dec, key2, 256); break; #endif default: return (TROPICSSL_ERR_SSL_FEATURE_UNAVAILABLE); } memset(keyblk, 0, sizeof(keyblk)); SSL_DEBUG_MSG(2, ("<= derive keys")); return (0); }
int main(void) { socklen_t fromlen; int len, n, server_socket, fd_log; unsigned long int nb_written; struct sockaddr_in client_addr; struct sockaddr_in server_addr; unsigned char logbuf[MAX_LOG_PKT_SZ]; unsigned char sha1sum[SHA1_SZ]; sha1_context sha1; create_log(&fd_log); nb_written = 0; /* start the UDP listening server */ if ((server_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { server_err("Socket creation failed: %d\n", errno); exit(1); } n = 1; if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, (void *) &n, sizeof ( n)) < 0) { server_err("Set socket options failed: %d\n", errno); exit(1); } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(SHELL_LOG_SERVER_PORT); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(server_socket, (struct sockaddr *) &server_addr, sizeof ( server_addr)) < 0) { server_err("Bind socket failed: %d\n", errno); exit(1); } if (fork() != 0) exit(0); setsid(); while (1) { fromlen = sizeof (client_addr); if ((len = recvfrom(server_socket, &logbuf[IP_SZ + LENGTH_SZ], BUF_SZ, 0, (struct sockaddr *) &client_addr, &fromlen)) < MIN_TRANSFER_PKT_SZ) { // sleep(1); continue; } server_dbg("Received packet: %d\n", len); sha1_starts(&sha1); sha1_update(&sha1, logbuf + IP_SZ + LENGTH_SZ + RC4_SZ, len - RC4_SZ - SHA1_SZ); sha1_finish(&sha1, sha1sum); if (memcmp(logbuf + IP_SZ + LENGTH_SZ + len - SHA1_SZ, sha1sum, SHA1_SZ) != 0) { server_err("SHA-1 checksum verification failed\n"); continue; } memcpy(logbuf, &client_addr.sin_addr.s_addr, IP_SZ); memcpy(&logbuf[IP_SZ], &len, LENGTH_SZ); server_dbg("From : %d.%d.%d.%d\n", (client_addr.sin_addr.s_addr) & 0xFF, (client_addr.sin_addr.s_addr >> 8) & 0xFF, (client_addr.sin_addr.s_addr >> 16) & 0xFF, (client_addr.sin_addr.s_addr >> 24) & 0xFF ); write(fd_log, logbuf, IP_SZ + LENGTH_SZ + len); nb_written += (IP_SZ + LENGTH_SZ + len); if (nb_written > MAX_LOG_SIZE) { nb_written = 0; close(fd_log); create_log(&fd_log); } } return ( 0); }
static char * digest_string( char *txt, int algo, int length, char *output) { FILE *fp=0; error_message = NULL; int nChar = strlen(txt); if (length>=0 && length<nChar) nChar = length; switch (algo) { case 1: { /* md5 case */ md5_context ctx; unsigned char md5sum[16]; int j; md5_starts( &ctx ); md5_update( &ctx, (uint8 *) txt, nChar); md5_finish( &ctx, md5sum ); for(j = 0; j < 16; j++) { sprintf(output + j * 2, "%02x", md5sum[j]); } break; } case 2: { /* sha1 case */ int j; sha1_context ctx; unsigned char sha1sum[20]; sha1_starts( &ctx ); sha1_update( &ctx, (uint8 *) txt, nChar); sha1_finish( &ctx, sha1sum ); for( j = 0; j < 20; j++ ) { sprintf( output + j * 2, "%02x", sha1sum[j] ); } break; } case 3: { /* crc32 case */ unsigned long val, l; l = nChar; val = digest_crc32(0L, 0, 0); val = digest_crc32(val, (unsigned char*) txt, (unsigned) l); sprintf(output, "%2.2x", (unsigned int) val); break; } case 101: { /* md5 file case */ int j; md5_context ctx; unsigned char buf[1024]; unsigned char md5sum[16]; if (!(fp = fopen(txt,"rb"))) { error_message = (strcat("Can not open input file: ", txt)); return (char *)NULL; } md5_starts( &ctx ); if (length>=0) { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0 && length>0) { if (nChar>length) nChar=length; md5_update( &ctx, buf, nChar ); length -= nChar; } } else { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0) md5_update( &ctx, buf, nChar ); } fclose(fp); md5_finish( &ctx, md5sum ); for(j = 0; j < 16; j++) sprintf(output + j * 2, "%02x", md5sum[j]); break; } case 102: { /* sha1 file case */ int j; sha1_context ctx; unsigned char buf[1024]; unsigned char sha1sum[20]; if (!(fp = fopen(txt,"rb"))) { error_message = (strcat("Can not open input file: ", txt)); return (char *)NULL; } sha1_starts ( &ctx ); if (length>=0) { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0 && length>0) { if (nChar>length) nChar=length; sha1_update( &ctx, buf, nChar ); length -= nChar; } } else { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0) sha1_update( &ctx, buf, nChar ); } fclose(fp); sha1_finish ( &ctx, sha1sum ); for( j = 0; j < 20; j++ ) sprintf( output + j * 2, "%02x", sha1sum[j] ); break; } case 103: { /* crc32 file case */ unsigned char buf[1024]; unsigned long val; if (!(fp = fopen(txt,"rb"))) { error_message = (strcat("Can not open input file: ", txt)); return (char *)NULL; } val = digest_crc32(0L, 0, 0); if (length>=0) { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0 && length>0) { if (nChar>length) nChar=length; val = digest_crc32(val , buf, (unsigned) nChar); length -= nChar; } } else { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0) val = digest_crc32(val , buf, (unsigned) nChar); } fclose(fp); sprintf(output, "%2.2x", (unsigned int) val); break; } default: { error_message = ("Unsupported algorithm code"); return (char *)NULL; } } return output; }
static int SHA1_Init(SHA_CTX *ctx) { sha1_starts(ctx); return 1; }
const wxString wxSHA1::GetDigest(bool mainthread) { if (m_isfile) { if(m_bCalculatedDigest) { const wxString szRetVal = m_pszDigestString; return szRetVal; } else if(!m_file.FileExists()) { return wxEmptyString; } else { sha1_context sha1Context; sha1_starts(&sha1Context); wxFile sha1file(m_file.GetFullPath(), wxFile::read); unsigned char buffer[16384]; unsigned int i = 1; while (i >0) { i = sha1file.Read(buffer,16384); sha1_update(&sha1Context, buffer, (unsigned) i); if (mainthread) wxYield(); } sha1_finish(&sha1Context,m_arrDigest); wxString szRetVal; unsigned int j=0; for (i = 0; i < sizeof m_arrDigest; i++) { szRetVal << wxString::Format(wxT("%02X"),m_arrDigest[i]); m_pszDigestString[j] = szRetVal.GetChar(j); m_pszDigestString[j+1] = szRetVal.GetChar(j+1); j+=2; } return szRetVal; } } else { if(m_bCalculatedDigest) { const wxString szRetVal = m_pszDigestString; return szRetVal; } else if(m_szText.IsEmpty()) { return wxEmptyString; } else { sha1_context sha1Context; sha1_starts(&sha1Context); char *text = new char[m_szText.Len()+1]; unsigned int i; for (i=0; i < (m_szText.Len());i++) text[i] = m_szText.GetChar(i); text[i] = '\0'; sha1_update(&sha1Context, (unsigned char*)(text), strlen(text)); sha1_finish(&sha1Context,m_arrDigest); wxString szRetVal; unsigned int j=0; for (i = 0; i < sizeof m_arrDigest; i++) { szRetVal << wxString::Format(wxT("%02X"),m_arrDigest[i]); m_pszDigestString[j] = szRetVal.GetChar(j); m_pszDigestString[j+1] = szRetVal.GetChar(j+1); j+=2; } return szRetVal; } } }
SEXP digest(SEXP Txt, SEXP Algo, SEXP Length, SEXP Skip, SEXP Leave_raw) { FILE *fp=0; char *txt; int algo = INTEGER_VALUE(Algo); int length = INTEGER_VALUE(Length); int skip = INTEGER_VALUE(Skip); int leaveRaw = INTEGER_VALUE(Leave_raw); SEXP result = NULL; char output[128+1], *outputp = output; /* 33 for md5, 41 for sha1, 65 for sha256, 128 for sha512; plus trailing NULL */ int nChar; int output_length = -1; if (IS_RAW(Txt)) { /* Txt is either RAW */ txt = (char*) RAW(Txt); nChar = LENGTH(Txt); } else { /* or a string */ txt = (char*) STRING_VALUE(Txt); nChar = strlen(txt); } if (skip>0) { if (skip>=nChar) nChar=0; else { nChar -= skip; txt += skip; } } if (length>=0 && length<nChar) nChar = length; switch (algo) { case 1: { /* md5 case */ md5_context ctx; output_length = 16; unsigned char md5sum[16]; int j; md5_starts( &ctx ); md5_update( &ctx, (uint8 *) txt, nChar); md5_finish( &ctx, md5sum ); memcpy(output, md5sum, 16); if (!leaveRaw) for(j = 0; j < 16; j++) sprintf(output + j * 2, "%02x", md5sum[j]); break; } case 2: { /* sha1 case */ int j; sha1_context ctx; output_length = 20; unsigned char sha1sum[20]; sha1_starts( &ctx ); sha1_update( &ctx, (uint8 *) txt, nChar); sha1_finish( &ctx, sha1sum ); memcpy(output, sha1sum, 20); if (!leaveRaw) for( j = 0; j < 20; j++ ) sprintf( output + j * 2, "%02x", sha1sum[j] ); break; } case 3: { /* crc32 case */ unsigned long val, l; l = nChar; val = digest_crc32(0L, 0, 0); val = digest_crc32(val, (unsigned char*) txt, (unsigned) l); sprintf(output, "%2.2x", (unsigned int) val); break; } case 4: { /* sha256 case */ int j; sha256_context ctx; output_length = 32; unsigned char sha256sum[32]; sha256_starts( &ctx ); sha256_update( &ctx, (uint8 *) txt, nChar); sha256_finish( &ctx, sha256sum ); memcpy(output, sha256sum, 32); if(!leaveRaw) for( j = 0; j < 32; j++ ) sprintf( output + j * 2, "%02x", sha256sum[j] ); break; } case 5: { /* sha2-512 case */ int j; SHA512_CTX ctx; output_length = SHA512_DIGEST_LENGTH; uint8_t sha512sum[output_length], *d = sha512sum; SHA512_Init(&ctx); SHA512_Update(&ctx, (uint8 *) txt, nChar); // Calling SHA512_Final, because SHA512_End will already // convert the hash to a string, and we also want RAW SHA512_Final(sha512sum, &ctx); memcpy(output, sha512sum, output_length); // adapted from SHA512_End if(!leaveRaw) { for (j = 0; j < output_length; j++) { *outputp++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *outputp++ = sha2_hex_digits[*d & 0x0f]; d++; } *outputp = (char)0; } break; } case 101: { /* md5 file case */ int j; md5_context ctx; output_length = 16; unsigned char buf[1024]; unsigned char md5sum[16]; if (!(fp = fopen(txt,"rb"))) { error("Cannot open input file: %s", txt); return(NULL); } if (skip > 0) fseek(fp, skip, SEEK_SET); md5_starts( &ctx ); if (length>=0) { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0 && length>0) { if (nChar>length) nChar=length; md5_update( &ctx, buf, nChar ); length -= nChar; } } else { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0) md5_update( &ctx, buf, nChar ); } fclose(fp); md5_finish( &ctx, md5sum ); memcpy(output, md5sum, 16); if (!leaveRaw) for(j = 0; j < 16; j++) sprintf(output + j * 2, "%02x", md5sum[j]); break; } case 102: { /* sha1 file case */ int j; sha1_context ctx; output_length = 20; unsigned char buf[1024]; unsigned char sha1sum[20]; if (!(fp = fopen(txt,"rb"))) { error("Cannot open input file: %s", txt); return(NULL); } if (skip > 0) fseek(fp, skip, SEEK_SET); sha1_starts ( &ctx ); if (length>=0) { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0 && length>0) { if (nChar>length) nChar=length; sha1_update( &ctx, buf, nChar ); length -= nChar; } } else { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0) sha1_update( &ctx, buf, nChar ); } fclose(fp); sha1_finish ( &ctx, sha1sum ); memcpy(output, sha1sum, 20); if(!leaveRaw) for( j = 0; j < 20; j++ ) sprintf( output + j * 2, "%02x", sha1sum[j] ); break; } case 103: { /* crc32 file case */ unsigned char buf[1024]; unsigned long val; if (!(fp = fopen(txt,"rb"))) { error("Cannot open input file: %s", txt); return(NULL); } if (skip > 0) fseek(fp, skip, SEEK_SET); val = digest_crc32(0L, 0, 0); if (length>=0) { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0 && length>0) { if (nChar>length) nChar=length; val = digest_crc32(val , buf, (unsigned) nChar); length -= nChar; } } else { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0) val = digest_crc32(val , buf, (unsigned) nChar); } fclose(fp); sprintf(output, "%2.2x", (unsigned int) val); break; } case 104: { /* sha256 file case */ int j; sha256_context ctx; output_length = 32; unsigned char buf[1024]; unsigned char sha256sum[32]; if (!(fp = fopen(txt,"rb"))) { error("Cannot open input file: %s", txt); return(NULL); } if (skip > 0) fseek(fp, skip, SEEK_SET); sha256_starts ( &ctx ); if (length>=0) { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0 && length>0) { if (nChar>length) nChar=length; sha256_update( &ctx, buf, nChar ); length -= nChar; } } else { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0) sha256_update( &ctx, buf, nChar ); } fclose(fp); sha256_finish ( &ctx, sha256sum ); memcpy(output, sha256sum, 32); if(!leaveRaw) for( j = 0; j < 32; j++ ) sprintf( output + j * 2, "%02x", sha256sum[j] ); break; } case 105: { /* sha2-512 file case */ int j; SHA512_CTX ctx; output_length = SHA512_DIGEST_LENGTH; uint8_t sha512sum[output_length], *d = sha512sum; unsigned char buf[1024]; if (!(fp = fopen(txt,"rb"))) { error("Cannot open input file: %s", txt); return(NULL); } if (skip > 0) fseek(fp, skip, SEEK_SET); SHA512_Init(&ctx); if (length>=0) { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0 && length>0) { if (nChar>length) nChar=length; SHA512_Update( &ctx, buf, nChar ); length -= nChar; } } else { while( ( nChar = fread( buf, 1, sizeof( buf ), fp ) ) > 0) SHA512_Update( &ctx, buf, nChar ); } fclose(fp); // Calling SHA512_Final, because SHA512_End will already // convert the hash to a string, and we also want RAW SHA512_Final(sha512sum, &ctx); memcpy(output, sha512sum, output_length); // adapted from SHA512_End if(!leaveRaw) { for (j = 0; j < output_length; j++) { *outputp++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *outputp++ = sha2_hex_digits[*d & 0x0f]; d++; } *outputp = (char)0; } break; } default: { error("Unsupported algorithm code"); return(NULL); } } if (leaveRaw && output_length > 0) { PROTECT(result=allocVector(RAWSXP, output_length)); memcpy(RAW(result), output, output_length); } else { PROTECT(result=allocVector(STRSXP, 1)); SET_STRING_ELT(result, 0, mkChar(output)); } UNPROTECT(1); return result; }
int main(int argc, char *argv[]) { int res = EXIT_FAILURE; int buflen; int err; struct stat st; char *buf; struct planex_hdr *hdr; sha1_context ctx; uint32_t t = HOST_TO_BE32(2); FILE *outfile, *infile; progname = basename(argv[0]); while ( 1 ) { int c; c = getopt(argc, argv, "i:o:v:h"); if (c == -1) break; switch (c) { case 'i': ifname = optarg; break; case 'o': ofname = optarg; break; case 'v': version = optarg; break; case 'h': usage(EXIT_SUCCESS); break; default: usage(EXIT_FAILURE); break; } } if (ifname == NULL) { ERR("no input file specified"); goto err; } if (ofname == NULL) { ERR("no output file specified"); goto err; } err = stat(ifname, &st); if (err) { ERRS("stat failed on %s", ifname); goto err; } buflen = (st.st_size + 3) & ~3; buflen += sizeof(*hdr); buf = malloc(buflen); if (!buf) { ERR("no memory for buffer\n"); goto err; } memset(buf, 0xff, buflen); hdr = (struct planex_hdr *)buf; hdr->datalen = HOST_TO_BE32(buflen - sizeof(*hdr)); hdr->unk1[0] = 0x04; hdr->unk1[1] = 0x08; snprintf(hdr->version, sizeof(hdr->version), "%s", version); infile = fopen(ifname, "r"); if (infile == NULL) { ERRS("could not open \"%s\" for reading", ifname); goto err_free; } errno = 0; fread(buf + sizeof(*hdr), st.st_size, 1, infile); if (errno != 0) { ERRS("unable to read from file %s", ifname); goto err_close_in; } sha1_starts(&ctx); sha1_update(&ctx, (uchar *) &t, sizeof(t)); sha1_update(&ctx, buf + sizeof(*hdr), buflen - sizeof(*hdr)); sha1_finish(&ctx, hdr->sha1sum); outfile = fopen(ofname, "w"); if (outfile == NULL) { ERRS("could not open \"%s\" for writing", ofname); goto err_close_in; } errno = 0; fwrite(buf, buflen, 1, outfile); if (errno) { ERRS("unable to write to file %s", ofname); goto err_close_out; } res = EXIT_SUCCESS; out_flush: fflush(outfile); err_close_out: fclose(outfile); if (res != EXIT_SUCCESS) { unlink(ofname); } err_close_in: fclose(infile); err_free: free(buf); err: return res; }
/* Restore the checksum before writing */ hdr->prolog_checksum = checksum_ref; printf("Image checksum...OK!\n"); return 0; } #elif defined(CONFIG_ARMADA_3700) /* Armada 3700 */ static int check_image_header(void) { struct common_tim_data *hdr = (struct common_tim_data *)get_load_addr(); int image_num; u8 hash_160_output[SHA1_SUM_LEN]; u8 hash_256_output[SHA256_SUM_LEN]; sha1_context hash1_text; sha256_context hash256_text; u8 *hash_output; u32 hash_algorithm_id; u32 image_size_to_hash; u32 flash_entry_addr; u32 *hash_value; u32 internal_hash[HASH_SUM_LEN]; const u8 *buff; u32 num_of_image = hdr->num_images; u32 version = hdr->version; u32 trusted = hdr->trusted; /* bubt checksum validation only supports nontrusted images */ if (trusted == 1) { printf("bypass image validation, "); printf("only untrusted image is supported now\n"); return 0; } /* only supports image version 3.5 and 3.6 */ if (version != IMAGE_VERSION_3_5_0 && version != IMAGE_VERSION_3_6_0) { printf("Error: Unsupported Image version = 0x%08x\n", version); return -ENOEXEC; } /* validate images hash value */ for (image_num = 0; image_num < num_of_image; image_num++) { struct mvebu_image_info *info = (struct mvebu_image_info *)(get_load_addr() + sizeof(struct common_tim_data) + image_num * sizeof(struct mvebu_image_info)); hash_algorithm_id = info->hash_algorithm_id; image_size_to_hash = info->image_size_to_hash; flash_entry_addr = info->flash_entry_addr; hash_value = info->hash; buff = (const u8 *)(get_load_addr() + flash_entry_addr); if (image_num == 0) { /* * The first image includes hash values in its content. * For hash calculation, we need to save the original * hash values to a local variable that will be * copied back for comparsion and set all zeros to * the orignal hash values for calculating new value. * First image original format : * x...x (datum1) x...x(orig. hash values) x...x(datum2) * Replaced first image format : * x...x (datum1) 0...0(hash values) x...x(datum2) */ memcpy(internal_hash, hash_value, sizeof(internal_hash)); memset(hash_value, 0, sizeof(internal_hash)); } if (image_size_to_hash == 0) { printf("Warning: Image_%d hash checksum is disabled, ", image_num); printf("skip the image validation.\n"); continue; } switch (hash_algorithm_id) { case SHA1_SUM_LEN: sha1_starts(&hash1_text); sha1_update(&hash1_text, buff, image_size_to_hash); sha1_finish(&hash1_text, hash_160_output); hash_output = hash_160_output; break; case SHA256_SUM_LEN: sha256_starts(&hash256_text); sha256_update(&hash256_text, buff, image_size_to_hash); sha256_finish(&hash256_text, hash_256_output); hash_output = hash_256_output; break; default: printf("Error: Unsupported hash_algorithm_id = %d\n", hash_algorithm_id); return -ENOEXEC; } if (image_num == 0) memcpy(hash_value, internal_hash, sizeof(internal_hash)); if (memcmp(hash_value, hash_output, hash_algorithm_id) != 0) { printf("Error: Image_%d checksum is not correct\n", image_num); return -ENOEXEC; } } printf("Image checksum...OK!\n"); return 0; }