Example #1
0
void
sum(FILE *fd, char *name)
{
	byte *buf;
	byte digest[16];
	char pr64[25];
	int i, n;
	MD5state *s;

	s = nil;
	n = 0;
	buf = calloc(256,64);
	for(;;){
		i = fread(buf+n, 1, 128*64-n, fd);
		if(i <= 0)
			break;
		n += i;
		if(n & 0x3f)
			continue;
		s = md5(buf, n, 0, s);
		n = 0;
	}
	md5(buf, n, digest, s);
	if(hex){
		for(i=0;i<16;i++) printf("%.2X", digest[i]);
	}else{
		enc64(pr64,digest,sizeof(digest));
		pr64[22] = '\0';  /* chop trailing == */
		printf("%s",pr64);
	}
	if(name)
		printf("\t%s", name);
	printf("\n");
	free(buf);
}
Example #2
0
main(){
  while(1){
    printf("Input file:");
    gets(filename);    //用get函数,避免scanf以空格分割数据,
    if (filename[0]==34) filename[strlen(filename)-1]=0,strcpy(filename,filename+1);  //支持文件拖曳,但会多出双引号,这里是处理多余的双引号
    if (!strcmp(filename,"exit")) exit(0);  //输入exit退出
    if (!(fp=fopen(filename,"rb"))) {printf("Can not open this file!\n");continue;}  //以二进制打开文件
    fseek(fp, 0, SEEK_END);  //文件指针转到文件末尾
    if((len=ftell(fp))==-1) {printf("Sorry! Can not calculate files which larger than 2 GB!\n");fclose(fp);continue;}  //ftell函数返回long,最大为2GB,超出返回-1
    rewind(fp);  //文件指针复位到文件头
    A=0x67452301,B=0xefcdab89,C=0x98badcfe,D=0x10325476; //初始化链接变量
    flen[1]=len/0x20000000;     //flen单位是bit
    flen[0]=(len%0x20000000)*8;
    memset(x,0,64);   //初始化x数组为0
    fread(&x,4,16,fp);  //以4字节为一组,读取16组数据
    for(i=0;i<len/64;i++){    //循环运算直至文件结束
      md5();
      memset(x,0,64);
      fread(&x,4,16,fp);
    }
    ((char*)x)[len%64]=128;  //文件结束补1,补0操作,128二进制即10000000
    if(len%64>55) md5(),memset(x,0,64);
    memcpy(x+14,flen,8);    //文件末尾加入原文件的bit长度
    md5();
    fclose(fp);
    printf("MD5 Code:%08x%08x%08x%08x\n",PP(A),PP(B),PP(C),PP(D));  //高低位逆反输出
    system("pause");
  }
}
Example #3
0
static void _BRMD5Compress(uint32_t *r, uint32_t *x)
{
    static const uint32_t k[] = {
        0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
        0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
        0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
        0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
        0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
        0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
        0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
        0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
    };

    static const int s[] = { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 };
    
    int i = 0;
    uint32_t a = r[0], b = r[1], c = r[2], d = r[3], t;
    
    for (; i < 16; i++) md5(F, a, b, c, d, x[i], k[i], s[i % 4], t);
    for (; i < 32; i++) md5(G, a, b, c, d, x[(5*i + 1) % 16], k[i], s[4 + (i % 4)], t);
    for (; i < 48; i++) md5(H, a, b, c, d, x[(3*i + 5) % 16], k[i], s[8 + (i % 4)], t);
    for (; i < 64; i++) md5(I, a, b, c, d, x[(7*i) % 16], k[i], s[12 + (i % 4)], t);
    
    r[0] += a, r[1] += b, r[2] += c, r[3] += d;
    var_clean(&a, &b, &c, &d, &t);
}
Example #4
0
void
chap(Ticketreq *tr)
{
	char *secret, *hkey;
	DigestState *s;
	char sbuf[SECRETLEN], hbuf[DESKEYLEN];
	uchar digest[MD5dlen];
	char chal[CHALLEN];
	OChapreply reply;

	/*
	 *  Create a challenge and send it.
	 */
	randombytes((uchar*)chal, sizeof(chal));
	write(1, chal, sizeof(chal));

	/*
	 *  get chap reply
	 */
	if(readn(0, &reply, sizeof(reply)) < 0)
		exits(0);
	safecpy(tr->uid, reply.uid, sizeof(tr->uid));

	/*
	 * lookup
	 */
	secret = findsecret(KEYDB, tr->uid, sbuf);
	hkey = findkey(KEYDB, tr->hostid, hbuf);
	if(hkey == 0 || secret == 0){
		replyerror("chap-fail bad response %s", raddr);
		logfail(tr->uid);
		exits(0);
	}

	/*
	 *  check for match
	 */
	s = md5(&reply.id, 1, 0, 0);
	md5((uchar*)secret, strlen(secret), 0, s);
	md5((uchar*)chal, sizeof(chal), digest, s);

	if(memcmp(digest, reply.resp, MD5dlen) != 0){
		replyerror("chap-fail bad response %s", raddr);
		logfail(tr->uid);
		exits(0);
	}

	succeed(tr->uid);

	/*
	 *  reply with ticket & authenticator
	 */
	if(tickauthreply(tr, hkey) < 0)
		exits(0);

	if(debug)
		syslog(0, AUTHLOG, "chap-ok %s %s", tr->uid, raddr);
}
Example #5
0
md5::md5(const std::string& password, const std::string& salt, int iteration_count)
{
	iteration_count = 1 << iteration_count;

	hash = md5(salt + password).raw_digest();
	do {
		hash = md5(std::string(hash.begin(), hash.end()).append(password)).raw_digest();
	} while(--iteration_count);
}
Example #6
0
static void check(skiatest::Reporter* r,
                  const char path[],
                  SkISize size,
                  bool supportsScanlineDecoding) {
    SkAutoTDelete<SkStream> stream(resource(path));
    if (!stream) {
        SkDebugf("Missing resource '%s'\n", path);
        return;
    }
    SkAutoTDelete<SkCodec> codec(SkCodec::NewFromStream(stream.detach()));
    if (!codec) {
        ERRORF(r, "Unable to decode '%s'", path);
        return;
    }

    // This test is used primarily to verify rewinding works properly.  Using kN32 allows
    // us to test this without the added overhead of creating different bitmaps depending
    // on the color type (ex: building a color table for kIndex8).  DM is where we test
    // decodes to all possible destination color types.
    SkImageInfo info = codec->getInfo().makeColorType(kN32_SkColorType);
    REPORTER_ASSERT(r, info.dimensions() == size);
    SkBitmap bm;
    bm.allocPixels(info);
    SkAutoLockPixels autoLockPixels(bm);
    SkImageGenerator::Result result =
        codec->getPixels(info, bm.getPixels(), bm.rowBytes(), NULL, NULL, NULL);
    REPORTER_ASSERT(r, result == SkImageGenerator::kSuccess);

    SkMD5::Digest digest1, digest2;
    md5(bm, &digest1);

    bm.eraseColor(SK_ColorYELLOW);

    result =
        codec->getPixels(info, bm.getPixels(), bm.rowBytes(), NULL, NULL, NULL);

    REPORTER_ASSERT(r, result == SkImageGenerator::kSuccess);
    // verify that re-decoding gives the same result.
    md5(bm, &digest2);
    REPORTER_ASSERT(r, digest1 == digest2);

    SkScanlineDecoder* scanlineDecoder = codec->getScanlineDecoder(info);
    if (supportsScanlineDecoding) {
        bm.eraseColor(SK_ColorYELLOW);
        REPORTER_ASSERT(r, scanlineDecoder);
        for (int y = 0; y < info.height(); y++) {
            result = scanlineDecoder->getScanlines(bm.getAddr(0, y), 1, 0);
            REPORTER_ASSERT(r, result == SkImageGenerator::kSuccess);
        }
        // verify that scanline decoding gives the same result.
        SkMD5::Digest digest3;
        md5(bm, &digest3);
        REPORTER_ASSERT(r, digest3 == digest1);
    } else {
        REPORTER_ASSERT(r, !scanlineDecoder);
    }
}
Example #7
0
//creates accounts and cards in the system
void DataStorage::initATM(){
    Account ac("Petro","Petrov","16.03.1984");
    _data.accounts().push_back(ac);
    _data.accounts().back().insertCard("1234567890123651",md5("7561"));
    _data.accounts().back().insertCard("4984654351484864",md5("5768"));
    _data.accounts().back().insertCard("1218998165132318",md5("3201"));

    _data.cardToAmount().insert(pair<string,int>("1234567890123651",1500));
    _data.cardToAmount().insert(pair<string,int>("4984654351484864",0));
    _data.cardToAmount().insert(pair<string,int>("1218998165132318",210));

    Account ac1("Ivan","Ivanov","27.05.1975");
    _data.accounts().push_back(ac1);
    _data.accounts().back().insertCard("4327463724623746",md5("1234"));
    _data.accounts().back().insertCard("1334234234342212",md5("9368"));
    _data.accounts().back().insertCard("9456452312334123",md5("9057"));


    _data.cardToAmount().insert(pair<string,int>("4327463724623746",350));
    _data.cardToAmount().insert(pair<string,int>("1334234234342212",0));
    _data.cardToAmount().insert(pair<string,int>("9456452312334123",12000));

    Account ac2("Sergiy","Sergeev","22.11.1989");
    _data.accounts().push_back(ac2);
    _data.accounts().back().insertCard("1643234324234123",md5("1573"));
    _data.accounts().back().insertCard("9657433242341234",md5("9374"));
    _data.accounts().back().insertCard("1235234324124334",md5("2668"));


    _data.cardToAmount().insert(pair<string,int>("1643234324234123",20));
    _data.cardToAmount().insert(pair<string,int>("9657433242341234",150));
    _data.cardToAmount().insert(pair<string,int>("1235234324124334",90));

}
Example #8
0
bool Filemanager::segmentate(std::string file_path) {       

	char *buffer = new char[this->buffer_size];
    int start_read_byte = 0;
    Metaworker *mworker = new Metaworker();
    mworker->load(file_path.c_str());

    std::string chang_path;

    std::ifstream ifile( file_path.c_str(), std::ios::in | std::ios::binary);

    if(!ifile){ //отсутствие прав постучалось в двери
        std::cout << "cannot open input files\n";
        return false;
    }



    while (!ifile.eof()){

        ifile.read(buffer, this->buffer_size);
        if(ifile.gcount()) {

            const char* enc_buffer = this->scrambler->encode(buffer, ifile.gcount());
            std::string str_buffer(buffer, ifile.gcount());
            std::string enc_str_buffer(enc_buffer, ifile.gcount());

            mworker->set( md5(str_buffer), md5(enc_str_buffer), start_read_byte, start_read_byte + ifile.gcount() - 1);
            
            chang_path = this->output_dir + md5(enc_str_buffer);
            
            std::ofstream ofile( chang_path.c_str(), std::ios::binary);
            
            start_read_byte += ifile.gcount();  

            if(!ofile){ //ошибку открытия файлов стоит отслеживать, всякое бывает
                std::cout << "cannot open output files named \"" << md5(enc_str_buffer) << "\" \n";
                return false;
            }

        	ofile.write(enc_buffer, ifile.gcount());
        	ofile.close();

        } 
    }
    mworker->save();
    ifile.close();
 	
    delete[] buffer;
    return true;
}
Example #9
0
int main(int argc, char **argv) 
{
    int i = 0, rootid = 0, id = 0, j = 0, old = 0, data = 0, n = 0, count = 50000000;
    unsigned char digest[MD5_LEN];
    void *mmtree = NULL;
    void *timer = NULL;
    char line[1024];
    int64_t key = 0;

    if((mmtree = mmtree64_init("/tmp/test.mmtree64")))
    {
        rootid = mmtree64_new_tree(mmtree);
        TIMER_INIT(timer);
        for(j = 1; j <= count; j++)
        {
            n = sprintf(line, "http://www.demo.com/%d.html", j);
            md5(line, n, digest);
            key = *((int64_t *)digest);
            old = -1;
            data = j;
            id = mmtree64_insert(mmtree, rootid, key, data, &old);
            if(old > 0 || id <= 0) 
            {
                fprintf(stdout, "%d:{id:%d key:%d rootid:%d old:%d}\n", j, id, key, rootid, old);
            }
        }
        TIMER_SAMPLE(timer);
        fprintf(stdout, "%s::%d insert:%d time:%lld\n", __FILE__,__LINE__, count, PT_LU_USEC(timer));
        for(j = 1; j <= count; j++)
        {
            n = sprintf(line, "http://www.demo.com/%d.html", j);
            md5(line, n, digest);
            key = *((int64_t *)digest);
            old = -1;
            data = j;
            id = mmtree64_try_insert(mmtree, rootid, key, data, &old);
            if(old > 0 && old != j) 
            {
                fprintf(stdout, "%d:{id:%d key:%d rootid:%d old:%d}\n", j, id, key, rootid, old);
                _exit(-1);
            }
        }
        TIMER_SAMPLE(timer);
        fprintf(stdout, "%s::%d try_insert:%d time:%lld\n", __FILE__,__LINE__, count, PT_LU_USEC(timer));
        TIMER_CLEAN(timer);
        mmtree64_close(mmtree);
    }
}
Example #10
0
void Preferences::setUILockPassword(const QString &clear_password)
{
    QCryptographicHash md5(QCryptographicHash::Md5);
    md5.addData(clear_password.toLocal8Bit());
    QString md5_password = md5.result().toHex();
    setValue("Locking/password", md5_password);
}
Example #11
0
static uint16 Wechat_get_md5(void)
{
 	uint8 stat = SUCCESS;

	#if (defined EAM_md5AndNoEnrypt ) || ( defined EAM_md5AndAesEnrypt )
	char device_type[] = DEVICE_TYPE;
	char device_id[] = DEVICE_ID;
	char argv[sizeof(DEVICE_TYPE) + sizeof(DEVICE_ID) - 1];
	
	memcpy(argv,device_type,sizeof(DEVICE_TYPE));
	/*when add the DEVICE_ID to DEVICE_TYPE, the offset shuld -1 to overwrite '\0'  at the end of DEVICE_TYPE */
	memcpy(argv + sizeof(DEVICE_TYPE)-1,device_id,sizeof(DEVICE_ID));
	
	
	stat = md5(argv, md5_type_and_id);

#if 0
	NPI_Printf( "\r\nDEVICE_TYPE and DEVICE_ID: %s\r\n",argv);
	NPI_PrintString ( "\r\nMD5:");
	for ( uint8 i = 0; i < 16; i++ )
		NPI_Printf ( " %02x", md5_type_and_id[i] );
	NPI_PrintString( "\r\n" );
#endif

	#endif

	return stat;
}
Example #12
0
void BotUpdateSession()
{
	while(1)
	{
		char *Dropdatahttpquery = (char*)malloc(strlen("http://178.132.203.196/D3Bot/session.php?version=") + strlen(BotVersion) + strlen("&type=") + strlen(BotType) + strlen("&authkey=") + strlen(TestKey) + 1);
		sprintf(Dropdatahttpquery, "%s%s%s%s%s%s", "http://178.132.203.196/D3Bot/session.php?version=", BotVersion, "&type=", BotType, "&authkey=", TestKey);
		string Dropurls = Dropdatahttpquery;

		CURLcode Dropresult;
		string Dropbuffer;

		curl_easy_setopt(curl, CURLOPT_URL, Dropurls.c_str());
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 2);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &Dropbuffer);
		Dropresult = curl_easy_perform(curl);

		if(Dropbuffer == md5(mymd5))
		{
			noauthupdate = 0;
			noauth = 0;
			break;
		}
		else
		{
			noauth = 1;
			noauthupdate = 1;
			BotSleep(0,0,0,0,0,0,0,0,0,0,0,0,300);
			logprint("Ошибка соединения с сервером:", 0);
			logprint(Dropbuffer, 0);
		}
	}
}
Example #13
0
char* MD5Generator(char* challenge)
{
		char *msg = malloc(strlen(challenge));
		strcpy(msg, challenge);
     	size_t len = strlen(msg);
		// benchmark
		int i;
		for (i = 0; i < 1000000; i++) {
		    md5(msg, len);
		}

		//var char digest[16] := h0 append h1 append h2 append h3 //(Output is in little-endian)
		uint8_t *p;

		// display result
		char * md5 = malloc(sizeof(p));
		char * final = malloc(4 * sizeof(p));

		p=(uint8_t *)&h0;
		snprintf(md5, sizeof(p) + 1, "%02x%02x%02x%02x", p[0], p[1], p[2], p[3], h0);
		strcpy(final, md5);
		p=(uint8_t *)&h1;
		snprintf(md5, sizeof(p) + 1, "%02x%02x%02x%02x", p[0], p[1], p[2], p[3], h1);
		strcat(final, md5);
		p=(uint8_t *)&h2;
		snprintf(md5, sizeof(p) + 1, "%02x%02x%02x%02x", p[0], p[1], p[2], p[3], h2);
		strcat(final, md5);
		p=(uint8_t *)&h3;
		snprintf(md5, sizeof(p) + 1, "%02x%02x%02x%02x", p[0], p[1], p[2], p[3], h3);
		strcat(final, md5);

		free(md5);

		return final;
}
Example #14
0
void VideoData::copyToTemporary(QIODevice &device)
{
    delete d;
    d = new VideoDataPrivate();
    d->temporaryFile = new KTemporaryFile();
    d->refCount.ref();
    d->temporaryFile->setPrefix("KoVideoData");
    if (!d->temporaryFile->open()) {
        kWarning(30006) << "open temporary file for writing failed";
        d->errorCode = VideoData::StorageFailed;
        delete d;
        d = 0;
        return;
    }
    QCryptographicHash md5(QCryptographicHash::Md5);
    char buf[8192];
    while (true) {
        device.waitForReadyRead(-1);
        qint64 bytes = device.read(buf, sizeof(buf));
        if (bytes <= 0)
            break; // done!
        md5.addData(buf, bytes);
        do {
            bytes -= d->temporaryFile->write(buf, bytes);
        } while (bytes > 0);
    }
    d->key = VideoData::generateKey(md5.result());
    d->temporaryFile->close();

    QFileInfo fi(*(d->temporaryFile));
    d->dataStoreState = StateSpooled;
}
Example #15
0
void VideoData::setExternalVideo(const QUrl &location, bool saveInternal, VideoCollection *collection)
{
    if (collection) {
        // let the collection first check if it already has one. If it doesn't it'll call this method
        // again and we'll go to the other clause
        VideoData *other = collection->createExternalVideoData(location, saveInternal);
        this->operator=(*other);
        delete other;
    } else {
        delete d;
        d = new VideoDataPrivate();
        d->refCount.ref();

        d->videoLocation = location;
        d->saveVideoInZip = saveInternal;
        if (d->saveVideoInZip) {
            QFileInfo fileInfo(location.toLocalFile());
            d->setSuffix(fileInfo.fileName());
        } else {
            d->setSuffix(location.toEncoded());
        }

        QCryptographicHash md5(QCryptographicHash::Md5);
        md5.addData(location.toEncoded().append(saveInternal ? "true" : "false"));
        d->key = VideoData::generateKey(md5.result());
    }
}
Example #16
0
int main(int argc, char* argv[])
{
 if (argc != 3)
    {
     printf("Nieprawidlowe argumenty: \ntest sha1|md5 file\n");
     return 1;
    }
        
 FILE* f = fopen(argv[2], "r");
 
 if (!f)
    {
     printf("Nie udalo sie otworzyc pliku\n");
     return 1;
    }
        
 if (strcmp (argv[1], "sha1") == 0)
    sha1(f);
 else
     if (strcmp (argv[1], "md5") == 0)
        md5(f);
     else
         {
          printf("Nieprawidlowe argumenty: \ntest sha1|md5 file\n");
          return 1;
         }
 
 fclose(f);
 return 0;
}
Example #17
0
std::string Vivarium::calc_hash(const std::string& in)
{
  if(setting::md5_mode)
    return md5(in.c_str());
  else
    return in;//passthrough for now. No need for performance penalty
}
Example #18
0
int32 send_parse(int8 *buff, size_t* buffsize, sockaddr_in* from, map_session_data_t* map_session_data)
{
    // Модификация заголовка исходящего пакета
    // Суть преобразований:
    //  - отправить клиенту номер последнего полученного от него пакета
    //  - присвоить исходящему пакету номер последнего отправленного клиенту пакета +1
    //  - записать текущее время отправки пакета

    WBUFW(buff,0) = map_session_data->server_packet_id;
    WBUFW(buff,2) = map_session_data->client_packet_id;

    // сохранение текущего времени (32 BIT!)
    WBUFL(buff,8) = (uint32)time(NULL);

    //Сжимаем данные без учета заголовка
    //Возвращаемый размер в 8 раз больше реальных данных
    uint32 PacketSize = zlib_compress(buff+FFXI_HEADER_SIZE, *buffsize-FFXI_HEADER_SIZE, PTempBuff, *buffsize, zlib_compress_table);

    //Запись размера данных без учета заголовка
    WBUFL(PTempBuff,(PacketSize+7)/8) = PacketSize;

    //Расчет hash'a также без учета заголовка, но с учетом записанного выше размера данных
    PacketSize = (PacketSize+7)/8+4;
    uint8 hash[16];
    md5((uint8*)PTempBuff, hash, PacketSize);
    memcpy(PTempBuff+PacketSize, hash, 16);
    PacketSize += 16;

    if (PacketSize > map_config.buffer_size + 20)
    {
        ShowFatalError(CL_RED"%Memory manager: PTempBuff is overflowed (%u)\n"CL_RESET, PacketSize);
    }

    //making total packet
    memcpy(buff+FFXI_HEADER_SIZE, PTempBuff, PacketSize);

    uint32 CypherSize = (PacketSize/4)&-2;

    blowfish_t* pbfkey = &map_session_data->blowfish;

    for(uint32 j = 0; j < CypherSize; j += 2)
    {
        blowfish_encipher((uint32*)(buff)+j+7, (uint32*)(buff)+j+8, pbfkey->P, pbfkey->S[0]);
    }

    // контролируем размер отправляемого пакета. в случае,
    // если его размер превышает 1400 байт (размер данных + 42 байта IP заголовок),
    // то клиент игнорирует пакет и возвращает сообщение о его потере

    // в случае возникновения подобной ситуации выводим предупреждующее сообщение и
    // уменьшаем размер BuffMaxSize с шагом в 4 байта до ее устранения (вручную)

    *buffsize = PacketSize+FFXI_HEADER_SIZE;

    if (*buffsize > 1350)
    {
        ShowWarning(CL_YELLOW"send_parse: packet is very big <%u>\n"CL_RESET,*buffsize);
    }
    return 0;
}
Example #19
0
std::string LLAppViewerMacOSX::generateSerialNumber()
{
	char serial_md5[MD5HEX_STR_SIZE];		// Flawfinder: ignore
	serial_md5[0] = 0;

	// JC: Sample code from http://developer.apple.com/technotes/tn/tn1103.html
	CFStringRef serialNumber = NULL;
	io_service_t    platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,
																 IOServiceMatching("IOPlatformExpertDevice"));
	if (platformExpert) {
		serialNumber = (CFStringRef) IORegistryEntryCreateCFProperty(platformExpert,
																	 CFSTR(kIOPlatformSerialNumberKey),
																	 kCFAllocatorDefault, 0);		
		IOObjectRelease(platformExpert);
	}
	
	if (serialNumber)
	{
		char buffer[MAX_STRING];		// Flawfinder: ignore
		if (CFStringGetCString(serialNumber, buffer, MAX_STRING, kCFStringEncodingASCII))
		{
			LLMD5 md5( (unsigned char*)buffer );
			md5.hex_digest(serial_md5);
		}
		CFRelease(serialNumber);
	}

	return serial_md5;
}
Example #20
0
char *
cryMd5(const char *sInBuf, int iInLen, char sOutBuf[16])
{
	md5((const unsigned char *)sInBuf, iInLen, (unsigned char *)sOutBuf);

	return sOutBuf;
}
Example #21
0
/* Begin MD5 HMAC functions
*/
static void
hmac_md5_init(hmac_md5_ctx *ctx, const char *key, const int key_len)
{
    unsigned char  final_key[MAX_DIGEST_BLOCK_LEN] = {0};
    unsigned char  init_key[MAX_DIGEST_BLOCK_LEN]  = {0};
    int            final_len = key_len;

    if(key_len > MAX_DIGEST_BLOCK_LEN)
        final_len = MAX_DIGEST_BLOCK_LEN;

    memcpy(init_key, key, final_len);

    if(MD5_BLOCK_LEN < key_len)
    {
        /* Calculate the digest of the key
        */
        md5(final_key, init_key, final_len);
    }
    else
    {
        memcpy(final_key, init_key, key_len);
    }

    pad_init(ctx->block_inner_pad, ctx->block_outer_pad, final_key, final_len);

    MD5Init(&ctx->ctx_inside);
    MD5Update(&ctx->ctx_inside, ctx->block_inner_pad, MD5_BLOCK_LEN);

    MD5Init(&ctx->ctx_outside);
    MD5Update(&ctx->ctx_outside, ctx->block_outer_pad, MD5_BLOCK_LEN);

    return;
}
Example #22
0
void NetworkManager::loadMD5()
{
	md5_.clear();

	FILE* fis = fopen(md5filename_.c_str(), "rb");

	if (fis == NULL)
		return;

	int nfiles;
	fread(&nfiles, sizeof(int), 1, fis);

	for (int i = 0; i < nfiles; ++i)
	{
		int strlen;
		fread(&strlen, sizeof(int), 1, fis);

		char* buffer = (char*)malloc(strlen);
		fread(buffer, 1, strlen, fis);
		std::string filename(buffer, strlen);
		free(buffer);

		std::vector<unsigned char> md5(16);
		fread(&md5[0], 1, 16, fis);

		md5_[filename] = md5;
	}
}
Example #23
0
void Hook::connectToServer()
{
	this->sock = new NetworkBase();

	this->sock->socketInit();
	this->sock->connect("127.0.0.1", "5050");
	this->sock->send("CLIENT HELLO");

	char * response = (this->sock->recv(1024));
	if (strcmp(response, "SERVER HELLO") != 0)
	{
		// TODO: Try again
		// Cannot connect to server...
		return;
	}
	this->sock->send((string("1 ") + string(md5(string(this->createUid())))).c_str());
	network_message newResponse = this->fullRecv();
	if (newResponse.first != 3)
	{
		// TODO: Try again
		// Cannot connect to server...
		return;
	}

	return;
}
void ProjectorShutterBlock::onMessageReceived() {
    QByteArray data = m_tcpSocket->readAll();

    if (data.startsWith(QString("PJLINK 0").toUtf8())) {
        // -> connection established, no authentication required
        m_authenticationToken = "";
        m_authenticated = true;
        m_passwordIsWrong = false;
        sendCommand("%1NAME ?\r");

    } else if (data.startsWith(QString("PJLINK 1").toUtf8())) {
        // -> connection established, received random number for authentification
        if (data.size() < 18) {
            qWarning() << "Received invalid response from projector.";
            return;
        }
        QString randomNumber = data.mid(9, 8);
        m_authenticationToken = md5(randomNumber + m_password);
        m_authenticated = true;
        m_passwordIsWrong = false;
        sendCommand("%1NAME ?\r");

    } else if (data.startsWith(QString("PJLINK ERRA").toUtf8())) {
        m_authenticated = false;
        m_passwordIsWrong = true;

    } else if (data.startsWith(QString("%1NAME=").toUtf8())) {
        m_projectorName = QString::fromUtf8(data.mid(7, data.size() - 8));
        checkPower();

    } else if (data.endsWith(QString("=OK\r").toUtf8())) {
        // ignore
    } else if (data.endsWith(QString("=ERR1\r").toUtf8())) {
        qDebug() << "Projector reports undefined command.";
    } else if (data.endsWith(QString("=ERR2\r").toUtf8())) {
        qDebug() << "Projector reports out-of-parameter.";
    } else if (data.endsWith(QString("=ERR3\r").toUtf8())) {
        qWarning() << "Projector unavailable.";
    } else if (data.endsWith(QString("=ERR4\r").toUtf8())) {
        qWarning() << "Projector reports failure.";
    } else if (data.startsWith(QString("%1POWR=").toUtf8())) {
        if (data.size() < 9) {
            qWarning() << "Projector responded with invalid power status.";
            return;
        }
        m_powerStatus = QString(data.mid(7, 1)).toInt();

    } else if (data.startsWith(QString("%1AVMT=").toUtf8())) {
        if (data.size() < 10) {
            qWarning() << "Projector responded with invalid shutter status.";
            return;
        }
        m_shutterIsOpen = data.mid(7, 2) == QString("30").toUtf8() // audio and video mute OFF
                || data.mid(7, 2) == QString("21").toUtf8();  // audio mute ON video mute OFF

    } else {
        qDebug() << "Received response from projector:" << QString::fromUtf8(data);
    }
}
Example #25
0
/**
*  Hash function. Returns a hash for a given string.
*  @param message: arbitrary binary string.
*  @return  A 128-bit hash string.
*/
static int lmd5 (lua_State *L) {
  char buff[16];
  size_t l;
  const char *message = luaL_checklstring(L, 1, &l);
  md5(message, l, buff);
  lua_pushlstring(L, buff, 16L);
  return 1;
}
Example #26
0
void NetworkServerPassword( std::string password )
{
	if( !_is_network_server ) return;
	std::string md5password = md5( password );
	for( int i = 0; i < 32; i++ ) game_settings.network_settings.server_settings.ServerPassword[ i ] = md5password[ i ];
	game_settings.network_settings.server_settings.ServerPassword[ 32 ] = 0;
	CLog::Get().Write( LOG_SERVER, true, "Server pasword changed." );
}
Example #27
0
bool Filemanager::segmentate(std::string file_path, long begin, long end) {
    char *buffer = new char[this->buffer_size];
    int start_read_byte = begin;
    std::string chang_path;
    int readed;
    int ifile = open(file_path.c_str(), 0);

    if(!ifile){ //отсутствие прав постучалось в двери
        std::cout << "cannot open input files\n";
        return false;
    }

    int lost = end-start_read_byte;

    while ( lost > 0 ){

        if(lost >= this->buffer_size) {
            readed = this->buffer_size;
        } else {
            readed = lost + 1;
        }
        pread(ifile, buffer, readed, start_read_byte);
        const char* enc_buffer = this->scrambler->encode(buffer, readed);
        std::string str_buffer(buffer, readed);
        std::string enc_str_buffer(enc_buffer, readed);

        mworker->set( md5(str_buffer), md5(enc_str_buffer), start_read_byte, start_read_byte + readed - 1);
        
        chang_path = this->output_dir + md5(enc_str_buffer);
        
        std::ofstream ofile( chang_path.c_str(), std::ios::binary);
        start_read_byte += readed; 
        lost = end - start_read_byte;
        // std::cout << lost << std::endl;
        if(!ofile){ //ошибку открытия файлов стоит отслеживать, всякое бывает
            std::cout << "cannot open output files named \"" << md5(enc_str_buffer) << "\" \n";
            return false;
        }
        ofile.write(enc_buffer, readed);
        ofile.close();
    }
    close(ifile);
    delete[] buffer;
    return true;
}
Example #28
0
std::string md5_hex(const std::string &data)
{
	char md5buf[16], hexbuf[33];
	
	md5(data.c_str(), data.length(), md5buf);
	md5_hex_conv(md5buf, hexbuf);
	
	return std::string(hexbuf);
}
void CFileDescriptor::loadFile()
{
	std::ifstream file;

	struct stat fileStat;
	if(stat(fullFileName.c_str(), &fileStat) == 0)
	{
		fileSize 	= fileStat.st_size;
		etag 		= fileStat.st_ino;
	}
	else
	{
		CLog::getInstance()->addError("file load error");
		isValid = false;
		return;
	}

	try
	{
		file.open(fullFileName);
	}
	catch(std::exception& e)
	{
		CLog::getInstance()->addError(e.what());
		isValid = false;
		file.close();
		return;
	}

	data = new char[fileSize];
	file.read(data, fileSize);

	if(!file)
	{
		CLog::getInstance()->addError("file load error");
		isValid = false;
		delete [] data;
		file.close();
		return;
	}
	md5Cache = md5(data);

	size_t dotPos = fullFileName.find_last_of(".");
	if(dotPos == std::string::npos)
	{
		fileType = "none";
	}
	else
	{
		fileType = fullFileName.substr(dotPos + 1, std::string::npos);
	}
	MIME = MIMEType::getInstance()->get(fileType);

	isValid = true;
	file.close();
}
Example #30
0
File: md5.c Project: manish05/TCR
int main() {
  int i;
  uchar y[32];
  md5init();
	scanf("%1023s",s);
  md5((uchar *)s,1,y);
  for(i=0;i<16;i++) printf("%02x",y[i]);
  printf("\n");
  return 0;
}