Ejemplo n.º 1
0
void sha256_twice(uint32_t hash[8], const uint8_t *data, int len)
{
    uint32_t hash_tmp[8];
    sha256_hash(hash_tmp, data, len);
    sha256_hash(hash, (uint8_t *)hash_tmp, sizeof hash_tmp);
}
Ejemplo n.º 2
0
static ssize_t read_rom_file(FILE *file, void **buf)
{
   ssize_t ret = 0;
   uint8_t *ret_buf = NULL;

   if (file == NULL) // stdin
   {
#if defined(_WIN32) && !defined(_XBOX)
      _setmode(0, O_BINARY);
#endif

      RARCH_LOG("Reading ROM from stdin ...\n");
      size_t buf_size = 0xfffff; // Some initial guesstimate.
      size_t buf_ptr = 0;
      uint8_t *rom_buf = (uint8_t*)malloc(buf_size);
      if (rom_buf == NULL)
      {
         RARCH_ERR("Couldn't allocate memory.\n");
         return -1;
      }

      for (;;)
      {
         size_t ret = fread(rom_buf + buf_ptr, 1, buf_size - buf_ptr, stdin);
         buf_ptr += ret;

         // We've reached the end
         if (buf_ptr < buf_size)
            break;

         rom_buf = (uint8_t*)realloc(rom_buf, buf_size * 2);
         if (rom_buf == NULL)
         {
            RARCH_ERR("Couldn't allocate memory.\n");
            return -1;
         }

         buf_size *= 2;
      }

      ret_buf = rom_buf;
      ret = buf_ptr;
   }
   else
   {
      fseek(file, 0, SEEK_END);
      ret = ftell(file);
      rewind(file);

      void *rom_buf = malloc(ret);
      if (rom_buf == NULL)
      {
         RARCH_ERR("Couldn't allocate memory.\n");
         return -1;
      }

      if (fread(rom_buf, 1, ret, file) < (size_t)ret)
      {
         RARCH_ERR("Didn't read whole file.\n");
         free(rom_buf);
         return -1;
      }

      ret_buf = (uint8_t*)rom_buf;
   }

   if (!g_extern.block_patch)
   {
      // Attempt to apply a patch.
      patch_rom(&ret_buf, &ret);
   }
   
   g_extern.cart_crc = crc32_calculate(ret_buf, ret);
   sha256_hash(g_extern.sha256, ret_buf, ret);
   RARCH_LOG("CRC32: 0x%x, SHA256: %s\n",
         (unsigned)g_extern.cart_crc, g_extern.sha256);
   *buf = ret_buf;
   return ret;
}
Ejemplo n.º 3
0
// Load SNES rom only. Applies a hack for headered ROMs.
static ssize_t read_rom_file(FILE *file, void **buf)
{
   ssize_t ret = 0;
   uint8_t *ret_buf = NULL;

   if (file == NULL) // stdin
   {
#if defined(_WIN32) && !defined(_XBOX)
      setmode(0, O_BINARY);
#endif

      RARCH_LOG("Reading ROM from stdin ...\n");
      size_t buf_size = 0xFFFFF; // Some initial guesstimate.
      size_t buf_ptr = 0;
      uint8_t *rom_buf = (uint8_t*)malloc(buf_size);
      if (rom_buf == NULL)
      {
         RARCH_ERR("Couldn't allocate memory.\n");
         return -1;
      }

      for (;;)
      {
         size_t ret = fread(rom_buf + buf_ptr, 1, buf_size - buf_ptr, stdin);
         buf_ptr += ret;

         // We've reached the end
         if (buf_ptr < buf_size)
            break;

         rom_buf = (uint8_t*)realloc(rom_buf, buf_size * 2);
         if (rom_buf == NULL)
         {
            RARCH_ERR("Couldn't allocate memory.\n");
            return -1;
         }

         buf_size *= 2;
      }

      ret_buf = rom_buf;
      ret = buf_ptr;
   }
   else
   {
      fseek(file, 0, SEEK_END);
      ret = ftell(file);
      rewind(file);

      void *rom_buf = malloc(ret);
      if (rom_buf == NULL)
      {
         RARCH_ERR("Couldn't allocate memory.\n");
         return -1;
      }

      if (fread(rom_buf, 1, ret, file) < (size_t)ret)
      {
         RARCH_ERR("Didn't read whole file.\n");
         free(rom_buf);
         return -1;
      }

      ret_buf = (uint8_t*)rom_buf;
   }

   if (!g_extern.block_patch)
   {
      // Attempt to apply a patch.
      patch_rom(&ret_buf, &ret);
   }
   
   // Remove copier header if present (512 first bytes).
   if ((ret & 0x7fff) == 512)
   {
      memmove(ret_buf, ret_buf + 512, ret - 512);
      ret -= 512;
   }

   g_extern.cart_crc = crc32_calculate(ret_buf, ret);
#ifdef HAVE_XML
   sha256_hash(g_extern.sha256, ret_buf, ret);
   RARCH_LOG("SHA256 sum: %s\n", g_extern.sha256);
#endif
   *buf = ret_buf;
   return ret;
}
Ejemplo n.º 4
0
void Cartridge::load(Mode cartridge_mode) {
    mode = cartridge_mode;
    read_header(memory::cartrom.data(), memory::cartrom.size());

    if(ram_size > 0) {
        memory::cartram.map(allocate<uint8_t>(ram_size, 0xff), ram_size);
    }

    if(has_srtc || has_spc7110rtc) {
        memory::cartrtc.map(allocate<uint8_t>(20, 0xff), 20);
    }

    if(mode == ModeBsx) {
        memory::bsxram.map (allocate<uint8_t>( 32 * 1024, 0xff),  32 * 1024);
        memory::bsxpram.map(allocate<uint8_t>(512 * 1024, 0xff), 512 * 1024);
    }

    if(mode == ModeSufamiTurbo) {
        if(memory::stArom.data()) memory::stAram.map(allocate<uint8_t>(128 * 1024, 0xff), 128 * 1024);
        if(memory::stBrom.data()) memory::stBram.map(allocate<uint8_t>(128 * 1024, 0xff), 128 * 1024);
    }

    if(mode == ModeSuperGameBoy) {
        if(memory::gbrom.data()) {
            unsigned ram_size = gameboy_ram_size();
            unsigned rtc_size = gameboy_rtc_size();

            if(ram_size) memory::gbram.map(allocate<uint8_t>(ram_size, 0xff), ram_size);
            if(rtc_size) memory::gbrtc.map(allocate<uint8_t>(rtc_size, 0x00), rtc_size);
        }
    }

    memory::cartrom.write_protect(true);
    memory::cartram.write_protect(false);
    memory::cartrtc.write_protect(false);
    memory::bsxflash.write_protect(true);
    memory::bsxram.write_protect(false);
    memory::bsxpram.write_protect(false);
    memory::stArom.write_protect(true);
    memory::stAram.write_protect(false);
    memory::stBrom.write_protect(true);
    memory::stBram.write_protect(false);
    memory::gbrom.write_protect(true);
    memory::gbram.write_protect(false);
    memory::gbrtc.write_protect(false);

    unsigned checksum = ~0;
    for(unsigned n = 0; n < memory::cartrom.size(); n++) checksum = crc32_adjust(checksum, memory::cartrom[n]);
    if(memory::bsxflash.size() != 0 && memory::bsxflash.size() != ~0)
        for(unsigned n = 0; n < memory::bsxflash.size(); n++) checksum = crc32_adjust(checksum, memory::bsxflash[n]);
    if(memory::stArom.size() != 0 && memory::stArom.size() != ~0)
        for(unsigned n = 0; n < memory::stArom.size(); n++) checksum = crc32_adjust(checksum, memory::stArom[n]);
    if(memory::stBrom.size() != 0 && memory::stBrom.size() != ~0)
        for(unsigned n = 0; n < memory::stBrom.size(); n++) checksum = crc32_adjust(checksum, memory::stBrom[n]);
    if(memory::gbrom.size() != 0 && memory::gbrom.size() != ~0)
        for(unsigned n = 0; n < memory::gbrom.size(); n++) checksum = crc32_adjust(checksum, memory::gbrom[n]);
    crc32 = ~checksum;

#if 0
    fprintf(stdout, "crc32  = %.8x\n", (unsigned)crc32);

    sha256_ctx sha;
    uint8_t shahash[32];
    sha256_init(&sha);
    sha256_chunk(&sha, memory::cartrom.data(), memory::cartrom.size());
    sha256_final(&sha);
    sha256_hash(&sha, shahash);

    fprintf(stdout, "sha256 = ");
    for(unsigned i = 0; i < 32; i++) fprintf(stdout, "%.2x", shahash[i]);
    fprintf(stdout, "\n");
#endif

    bus.load_cart();
    system.serialize_init();
    loaded = true;
}
Ejemplo n.º 5
0
// If bIgnoreCorrupted is TRUE the manager will try to ignore all database file
// errors, i.e. try to read as much as possible instead of breaking out at the
// first error.
// To open a file normally, set bIgnoreCorrupted to FALSE (default).
// To open a file in rescue mode, set it to TRUE.
int CPwManager::OpenDatabase(const TCHAR *pszFile, __out_opt PWDB_REPAIR_INFO *pRepair)
{
	char *pVirtualFile;
	unsigned long uFileSize, uAllocated, uEncryptedPartSize;
	unsigned long pos;
	PW_DBHEADER hdr;
	sha256_ctx sha32;
	UINT8 uFinalKey[32];
	char *p;
	char *pStart;
	USHORT usFieldType;
	DWORD dwFieldSize;
	PW_GROUP pwGroupTemplate;
	PW_ENTRY pwEntryTemplate;

	BOOST_STATIC_ASSERT(sizeof(char) == 1);

	ASSERT(pszFile != NULL); if(pszFile == NULL) return PWE_INVALID_PARAM;
	ASSERT(pszFile[0] != 0); if(pszFile[0] == 0) return PWE_INVALID_PARAM; // Length != 0

	RESET_PWG_TEMPLATE(&pwGroupTemplate);
	RESET_PWE_TEMPLATE(&pwEntryTemplate);

	if(pRepair != NULL) { ZeroMemory(pRepair, sizeof(PWDB_REPAIR_INFO)); }

	FILE *fp = NULL;
	_tfopen_s(&fp, pszFile, _T("rb"));
	if(fp == NULL) return PWE_NOFILEACCESS_READ;

	// Get file size
	fseek(fp, 0, SEEK_END);
	uFileSize = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	if(uFileSize < sizeof(PW_DBHEADER))
		{ fclose(fp); return PWE_INVALID_FILEHEADER; }

	// Allocate enough memory to hold the complete file
	uAllocated = uFileSize + 16 + 1 + 8 + 4; // 16 = encryption buffer space, 1+8 = string terminating NULL (UTF-8), 4 unused
	pVirtualFile = new char[uAllocated];
	if(pVirtualFile == NULL) { fclose(fp); return PWE_NO_MEM; }
	memset(&pVirtualFile[uFileSize + 17 - 1], 0, 1 + 8);

	fread(pVirtualFile, 1, uFileSize, fp);
	fclose(fp);

	// Extract header structure from memory file
	memcpy(&hdr, pVirtualFile, sizeof(PW_DBHEADER));

	// Check if it's a KDBX file created by KeePass 2.x
	if((hdr.dwSignature1 == PWM_DBSIG_1_KDBX_P) && (hdr.dwSignature2 == PWM_DBSIG_2_KDBX_P))
		{ _OPENDB_FAIL_LIGHT; return PWE_UNSUPPORTED_KDBX; }
	if((hdr.dwSignature1 == PWM_DBSIG_1_KDBX_R) && (hdr.dwSignature2 == PWM_DBSIG_2_KDBX_R))
		{ _OPENDB_FAIL_LIGHT; return PWE_UNSUPPORTED_KDBX; }

	// Check if we can open this
	if((hdr.dwSignature1 != PWM_DBSIG_1) || (hdr.dwSignature2 != PWM_DBSIG_2))
		{ _OPENDB_FAIL_LIGHT; return PWE_INVALID_FILESIGNATURE; }

	if((hdr.dwVersion & 0xFFFFFF00) != (PWM_DBVER_DW & 0xFFFFFF00))
	{
		if((hdr.dwVersion == 0x00020000) || (hdr.dwVersion == 0x00020001) || (hdr.dwVersion == 0x00020002))
		{
			if(pVirtualFile != NULL)
			{
				mem_erase((unsigned char *)pVirtualFile, uAllocated);
				SAFE_DELETE_ARRAY(pVirtualFile);
			}

			return ((CPwCompatImpl::OpenDatabaseV2(this, pszFile) != FALSE) ?
				PWE_SUCCESS : PWE_UNKNOWN);
		}
		else if(hdr.dwVersion <= 0x00010002)
		{
			if(pVirtualFile != NULL)
			{
				mem_erase((unsigned char *)pVirtualFile, uAllocated);
				SAFE_DELETE_ARRAY(pVirtualFile);
			}
			
			return ((CPwCompatImpl::OpenDatabaseV1(this, pszFile) != FALSE) ?
				PWE_SUCCESS : PWE_UNKNOWN);
		}
		else { ASSERT(FALSE); _OPENDB_FAIL; }
	}

	// Select algorithm
	if((hdr.dwFlags & PWM_FLAG_RIJNDAEL) != 0) m_nAlgorithm = ALGO_AES;
	else if((hdr.dwFlags & PWM_FLAG_TWOFISH) != 0) m_nAlgorithm = ALGO_TWOFISH;
	else { ASSERT(FALSE); _OPENDB_FAIL; }

	m_dwKeyEncRounds = hdr.dwKeyEncRounds;

	// Generate m_pTransformedMasterKey from m_pMasterKey
	if(_TransformMasterKey(hdr.aMasterSeed2) == FALSE) { ASSERT(FALSE); _OPENDB_FAIL; }

	ProtectTransformedMasterKey(false);

	// Hash the master password with the salt in the file
	sha256_begin(&sha32);
	sha256_hash(hdr.aMasterSeed, 16, &sha32);
	sha256_hash(m_pTransformedMasterKey, 32, &sha32);
	sha256_end((unsigned char *)uFinalKey, &sha32);

	ProtectTransformedMasterKey(true);

	if(pRepair == NULL)
	{
		// ASSERT(((uFileSize - sizeof(PW_DBHEADER)) % 16) == 0);
		if(((uFileSize - sizeof(PW_DBHEADER)) % 16) != 0)
		{
			_OPENDB_FAIL_LIGHT;
			return PWE_INVALID_FILESIZE;
		}
	}
	else // Repair the database
	{
		if(((uFileSize - sizeof(PW_DBHEADER)) % 16) != 0)
		{
			uFileSize -= sizeof(PW_DBHEADER); ASSERT((uFileSize & 0xF) != 0);
			uFileSize &= ~0xF;
			uFileSize += sizeof(PW_DBHEADER);
		}

		ASSERT(((uFileSize - sizeof(PW_DBHEADER)) % 16) == 0);

		pRepair->dwOriginalGroupCount = hdr.dwGroups;
		pRepair->dwOriginalEntryCount = hdr.dwEntries;
	}

	if(m_nAlgorithm == ALGO_AES)
	{
		CRijndael aes;

		// Initialize Rijndael algorithm
		if(aes.Init(CRijndael::CBC, CRijndael::DecryptDir, uFinalKey,
			CRijndael::Key32Bytes, hdr.aEncryptionIV) != RIJNDAEL_SUCCESS)
			{ _OPENDB_FAIL_LIGHT; return PWE_CRYPT_ERROR; }

		// Decrypt! The first bytes aren't encrypted (that's the header)
		uEncryptedPartSize = (unsigned long)aes.PadDecrypt((UINT8 *)pVirtualFile + sizeof(PW_DBHEADER),
			uFileSize - sizeof(PW_DBHEADER), (UINT8 *)pVirtualFile + sizeof(PW_DBHEADER));
	}
	else if(m_nAlgorithm == ALGO_TWOFISH)
	{
		CTwofish twofish;

		if(twofish.Init(uFinalKey, 32, hdr.aEncryptionIV) != true)
			{ _OPENDB_FAIL };

		uEncryptedPartSize = (unsigned long)twofish.PadDecrypt((UINT8 *)pVirtualFile + sizeof(PW_DBHEADER),
			uFileSize - sizeof(PW_DBHEADER), (UINT8 *)pVirtualFile + sizeof(PW_DBHEADER));
	}
Ejemplo n.º 6
0
short_hash bitcoin_short_hash(data_slice data)
{
    return ripemd160_hash(sha256_hash(data));
}
Ejemplo n.º 7
0
hash_digest bitcoin_hash(data_slice data)
{
    return sha256_hash(sha256_hash(data));
}
Ejemplo n.º 8
0
void sss_encode(int m, int n, uint8_t stype, const uint8_t secret[], int len)
{
    assert(n > 0 && n < 16);
    assert(m > 0 && m <= n);
    assert(len <= SSS_MAX_SECRET_SIZE);

    struct Share {
        uint8_t stype;
        uint8_t id[2];
        uint8_t m_and_x;
        uint8_t y[SSS_MAX_SECRET_SIZE];
    } share;

    int x, i, j;

    sha256_twice(_estack, secret, len);
    share.id[0] = COEFF[0];
    share.id[1] = COEFF[1];
    share.stype = stype;
    share.m_and_x = (m - 1) << 4;

    // Make pseudo-random coefficients, which should be unpredictable to
    // anyone who doesn't know the secret.
    // This implementation does not follow the spec's optional algorithm
    // for computing deterministic coefficients, although it looks a bit
    // similar.  The results of hashing are treated as if they are already
    // in logarithmic form.
    // We need m - 1 coefficients of len bytes each.
    sha256_hash(_estack, secret, len + 1);
    for (i = SHA256_SIZE; i < len * (m - 1); i += SHA256_SIZE)
        sha256_hash(&_estack[i / 4], &COEFF[i - SHA256_SIZE], SHA256_SIZE);

    for (x = 1; x <= n; x++) {
        unsigned xpow = 0;          // log(x**i), starting from i = 0
        unsigned logx = rs.log[x];
        const uint8_t *cptr = COEFF;

        memcpy(share.y, secret, len);  // start with y = a0

        for (i = 1; i < m; i++) {
            xpow += logx;           // update xpow = log(x**i)
            if (xpow >= 255)
               xpow -= 255;         // modulo 255
            // multiply i-th coefficient by x**i and add to share.y in GF
            for (j = 0; j < len; j++) {
                unsigned c = *cptr++;
                if (c != INFTY) {
                    c += xpow;
                    if (c >= 255)
                        c -= 255;
                }
                share.y[j] ^= rs.exp[c];
            }
        }

        strcpy(texts[IDX_SSS_PART(x)], "SSS-");
        base58check_encode(&share.stype, len + offsetof(struct Share, y),
                           texts[IDX_SSS_PART(x)] + 4);

        share.m_and_x++;
    }
}
Ejemplo n.º 9
0
/// @brief 
bool 
FileInfoCache::file_util_get_hash(
	_In_ const wchar_t* file_path, 
	_Out_ std::string& md5, 
	_Out_ std::string& sha2)
{
	handle_ptr file_handle(
		CreateFileW(file_path,
					GENERIC_READ,
					FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
					NULL,
					OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL,
					NULL),
		[](HANDLE h) 
		{
			if (INVALID_HANDLE_VALUE != h)
			{
				CloseHandle(h);
			}
		});

    if (INVALID_HANDLE_VALUE == file_handle.get())
    {
        log_err
            "CreateFileW() failed. path=%ws, gle = %u",
            file_path, 
			GetLastError()
            log_end;
        return false; 
    }
    
    if (INVALID_SET_FILE_POINTER == SetFilePointer(file_handle.get(), 
												   0, 
												   NULL, 
												   FILE_BEGIN))
    {
        log_err
            "SetFilePointer() failed. path=%ws, gle = %u", 
			file_path, 
			GetLastError()
            log_end;
        return false;
    }

    uint8_t sha2_buf[32];
    MD5_CTX ctx_md5;
    sha256_ctx ctx_sha2;
    MD5Init(&ctx_md5, 0);
    sha256_begin(&ctx_sha2);

    const uint32_t read_buffer_size = 4096;
    uint8_t read_buffer[read_buffer_size];
    DWORD read = read_buffer_size;

    while (read_buffer_size == read)
    {
		if (FALSE == ::ReadFile(file_handle.get(),
								read_buffer,
								read_buffer_size,
								&read,
								NULL))
        {
            log_err
                "ReadFile() failed. path=%ws, gle = %u",
                file_path,
                GetLastError()
                log_end;
            return false;
        }

        if (0 != read)
        {
            MD5Update(&ctx_md5, read_buffer, read);
            sha256_hash(read_buffer, read, &ctx_sha2);
        }
    }

    MD5Final(&ctx_md5);
    sha256_end(sha2_buf, &ctx_sha2);

	//
	//	Hash 바이너리 버퍼를 hex 문자열로 변환
	//
	if (true != bin_to_hexa_fast(sizeof(ctx_md5.digest),
								 ctx_md5.digest,
								 false,
								 md5))
	{
		log_err "bin_to_hexa_fast() failed. " log_end;
		return false;
	}

	if (true != bin_to_hexa_fast(sizeof(sha2_buf), 
								 sha2_buf, 
								 false, 
								 sha2))
	{
		log_err "bin_to_hexa_fast() failed. " log_end;
		return false;
	}
    return true;
}