Beispiel #1
0
/**
 * @brief	Read Firmware Version
 * @param	command	: Firmware version for ascii
 * @param	size	: Frimware version string size
 * @return	0 of the successful, error code if else
 * @note	ex) 2.00<0x0d>  ->
 */
uint32_t FV_Command(uint8_t *command, uint32_t size) {
	uint8_t tmp[5];
	memset(tmp,0,5);

	tmp[0] = hex2ascii(VER_MAJOR);
	tmp[1] = '.';
	tmp[2] = hex2ascii(VER_MINER / 10);
	tmp[3] = hex2ascii(VER_MINER % 10);

	tmp[4] = 0x0D;
	memcpy(command, tmp, 5);
	return 1;
}
Beispiel #2
0
char *
evalue(char *ptr)
{
	char *modv, *str, *ev;
	int modv_len;
	size_t len;

	/*
	 * if not cleartext, return a copy of what ptr
	 * points to as that is what evalue does below.
	 */
	if (FALSE == is_cleartext(ptr)) {
		str = strdup(ptr);
		return (str);
	}

	modv = modvalue(ptr, strlen(ptr), &modv_len);
	str = hex2ascii(modv, modv_len);
	free(modv);
	modv = NULL;
	len = strlen(str) + strlen(CRYPTMARK) + 1;
	ev = malloc(len);
	if (ev == NULL) {
		free(str);
		return (NULL);
	}
	(void) snprintf(ev, len, CRYPTMARK "%s", str);
	free(str);
	str = NULL;
	return (ev);
}
int Cmotor_control::step_1()			//转动1度
{
	unsigned char sendbuffer[5];
	unsigned char revbuffer[5];
	unsigned long ltemp;
	unsigned long i;
	//UpdateData(TRUE);                 //mfc函数 更新数据
	ltemp = rstep;
	if(ltemp > 999999)
	{
		return -1;
	}
	angle = angle + 1;
	realstep = realstep + ((float)ltemp / 360);
	ltemp = (unsigned long)(realstep - nowstep + 0.5);
	nowstep = nowstep + ltemp;
	if(angle >= 360)
	{
		nowstep = nowstep - rstep;
		angle = angle - 360;
		realstep = realstep - rstep;
	}

	sendbuffer[0] = 0x02;
	sendbuffer[1] = 0x00;
	hex2ascii(&(sendbuffer[2]),ltemp);//rstep
	if(FALSE == WriteFile(hCom,sendbuffer,5,&i,NULL)|| (i == 0))
	{
		return -1;
	}
	Sleep(100); 
	if(FALSE == ReadFile(hCom,revbuffer,5,&i,NULL)|| (i == 0))
	{
		return -1;
	}
	if(revbuffer[0] != 0x01)
	{
		return -1;
	}
	sendbuffer[0] = 0x01;
	sendbuffer[1] = 0x00;
	sendbuffer[2] = 0x00;
	sendbuffer[3] = 0x00;
	sendbuffer[4] = 2;
	if(FALSE == WriteFile(hCom,sendbuffer,5,&i,NULL)|| (i == 0))
	{
		return -1;
	}
	Sleep(100); 
	if(FALSE == ReadFile(hCom,revbuffer,5,&i,NULL)|| (i == 0))
	{
		return -1;
	}
	if(revbuffer[0] != 0x01)
	{
		return -1;
	}
	return 1;
}
Beispiel #4
0
/**
 * @brief	Read CAN Setting function
 * @param	command	: Serial command buffer without command header
 * @param	size	: Serial command buffer size without command header
 * @return	0 of the successful, error code if else
 * @note	ex) A,500,700,000,1<0x0d>  -> baudrate 500, Spec A, ID: 0x700, Mask: 0x000, function: 1
 *
 * 				function 0000 00xx
 * 				1 bit: DAR(Disable Automatic Retransmit)
 * 				2 bit: ABOR(Auto Bus-Off Recorvery)
 *
 */
uint32_t RC_Command(uint8_t *command, uint32_t size) {
	volatile uint32_t len;
	uint8_t tmp[30];
	volatile uint32_t ind;
	volatile uint8_t function;
	function =0;

	memset(tmp, 0, 30);
	switch (can.Spec) {
	case CAN_A:
		tmp[0] = 'A';
		tmp[1] = ',';
		break;
	case CAN_B:
		tmp[0] = 'B';
		tmp[1] = ',';
		break;
	default:
		return 0;
	}

	len = int2ascii(can.Baudrate, &tmp[2], 4);
	if (len == 0) {
		return 0;
	}
	tmp[len + 2] = ',';
	ind = len + 3;
	len = hex2ID(can.ID, can.Spec, &tmp[ind], 8);
	if (len == 0) {
		return 0;
	}
	tmp[can.Spec + ind] = ',';
	ind = can.Spec + ind + 1;

	len = hex2ID(can.Mask, can.Spec, &tmp[ind], 8);
	if (len == 0) {
		return 0;
	}

	tmp[len + ind] = ',';
	ind = can.Spec + ind;
	ind = ind + 1;

	if(can.DAR)
		SETDAR(function);
	if(can.ABOR)
		SETABOR(function);

	tmp[ind++] = hex2ascii(function);
	tmp[ind++] = 0x0d;


	memcpy(ReadSetting, tmp, ind);

	return 1;
}
Beispiel #5
0
///////////////////////////////////////////////////////////////////////////////
// SHA256 of file
//	Input:
//		lpFileName	: full path of plugin
//	Output:
//		sha256		: SHA256 in plain-text (lower case)
//
BOOL SHA256_Plugin(char *lpFileName, char *lpOutChecksum, BOOL isOld)
{
	if (lpFileName == NULL || lpOutChecksum == NULL)
		return FALSE;


	HANDLE hFile = CreateFile(lpFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

	if (hFile == INVALID_HANDLE_VALUE)
		return FALSE;

	SHA256Context context;

	Sha256_Init(&context);

	void *buffer = malloc(64000);

	DWORD dwBytesRead = 0;

	while(ReadFile(hFile, buffer, 64000, &dwBytesRead, NULL) == TRUE)
	{
		if (dwBytesRead == 0)	// end of file?
			break;

		Sha256_Update(&context, (byte *) buffer, (size_t) dwBytesRead);
	}

	CloseHandle(hFile);
	free(buffer);

	unsigned char sha256_digest[32];

	Sha256_Final(&context, sha256_digest);

	wchar_t unicodesha[32];
	if (isOld) {
		MultiByteToWideChar(CP_ACP, 0, (LPCSTR) sha256_digest, sizeof(sha256_digest), unicodesha, 32);
		hex2ascii(lpOutChecksum, unicodesha, 32);
	} else {
		hex2ascii(lpOutChecksum, (char *)sha256_digest, 32);
	}
	return TRUE;
}
Beispiel #6
0
///////////////////////////////////////////////////////////////////////////////
// MD5 of file
//	Input:
//		lpFileName	: full path of plugin
//	Output:
//		sha256		: md5 in plain-text (lower case)
//
BOOL MD5_Array(char *lpOutChecksum, char *array, int size)
{
	MD5_CTX context;

	MD5Init(&context);

	MD5Update(&context, (byte *) array, (size_t) size);

	MD5Final(&context);
	hex2ascii(lpOutChecksum, (char *) context.digest, sizeof(context.digest));

	return TRUE;
}
Beispiel #7
0
int main(int argc, char *argv[]) {
	// expect one argument atleast.
	if( argc < 2 ) {
		fprintf(stderr,"usage: %s <input-file>", argv[0]);
		exit(-1);
	}

	char *input_file = argv[1];
	FILE *fp = fopen(input_file, "rb");
	int numchunks = get_numchunks(input_file), i = 0;

	// check for sanity.
	if( numchunks < 0 || fp == NULL) {
		fprintf(stderr, "Can't stat the file %s: %s\n", input_file, strerror(errno));
		exit(-1);
	}

	// create the array. 
	uint8_t **hashes = (uint8_t **) malloc(numchunks * sizeof(uint8_t *));
	if( hashes == NULL ) {
		fprintf(stderr, "Out of memory!!!");
		exit(-1);
	}

	// allocate the individual elements.
	for(i=0;i<numchunks;i++) {
		hashes[i] = malloc((SHA1_HASH_SIZE)*sizeof(uint8_t));
		if( hashes[i] == NULL ) {
			fprintf(stderr, "Out of memory!!!");
			exit(-1);
		}
	}

	int chunks = make_chunks(fp, hashes);
	char ascii[SHA1_HASH_SIZE*2+1]; // the ascii string.
	for(i=0;i<chunks;i++) {
		hex2ascii(hashes[i], SHA1_HASH_SIZE, ascii);
		printf("%d %s\n",i,ascii);
		free(hashes[i]);
	}

	// free the memory.
	free(hashes);
	// close file.
	fclose(fp);

	// return success.
	return 0;
}
Beispiel #8
0
///////////////////////////////////////////////////////////////////////////////
// SHA256 of file
//	Input:
//		lpFileName	: full path of plugin
//	Output:
//		sha256		: SHA256 in plain-text (lower case)
//
BOOL SHA256_Array(char *lpOutChecksum, void *array, int size)
{
	SHA256Context context;

	Sha256_Init(&context);

	Sha256_Update(&context, (byte *) array, (size_t) size);

	unsigned char sha256_digest[32];

	Sha256_Final(&context, sha256_digest);

	hex2ascii(lpOutChecksum, (char *) sha256_digest, sizeof(sha256_digest));

	return TRUE;
}
int Cmotor_control::set_round(unsigned long step)		//设置一圈的步数
{
	unsigned char sendbuffer[5];
	unsigned char revbuffer[5];
	unsigned long ltemp;
	unsigned long i;
	ltemp = step;
	if(ltemp > 9999)
	{
		return -1;
	}
	sendbuffer[0] = 0x05;
	sendbuffer[1] = 0x00;
	hex2ascii(&(sendbuffer[2]),step);
	if(FALSE == WriteFile(hCom,sendbuffer,5,&i,NULL)|| (i == 0))
	{
		return -1;
	}
	Sleep(100); 
	if(FALSE == ReadFile(hCom,revbuffer,5,&i,NULL)|| (i == 0))
	{
		return -1;
	}
	if(revbuffer[0] != 0x01)
	{
		return -1;
	}
	FILE *fl;
	fl = fopen("dataset.ini","wb");
	if(fl == NULL)
	{
		return -1;
	}
	fwrite(&rstep,sizeof(step),1,fl);
	fclose(fl);
	rstep = step;
	return 1;
}
Beispiel #10
0
static char *HEX(va_list ap)
{
	int mem_size = MAX_STR_LEN;
	char *result = (char *)nmalloc(mem_size + 1);
	unsigned int data;
	int threshold;
	int nibble;
	int i, j;

	i = 0;
	VA_LOOP_BEGIN(ap, current)
	{
		data = (unsigned int)current->val.i;

		/* Simulate %02X specifier */
		threshold = 7;
		j = 1;
		do {
			nibble = data >> 28;

			if (nibble != 0 && threshold == 7)
				threshold = j;

			if (j >= threshold) {
				if (i >= mem_size) {
					mem_size *= 2;
					result = (char *)nrealloc(result,
							mem_size + 1);
				}
				result[i++] = hex2ascii(nibble);
			}

			data <<= 4;
			++j;
		} while (j <= 8);
	}
Beispiel #11
0
///////////////////////////////////////////////////////////////////////////////
// MD5 of file
//	Input:
//		lpFileName	: full path of plugin
//	Output:
//		sha256		: SHA256 in plain-text (lower case)
//
BOOL MD5_Plugin(char *lpFileName, char *lpOutChecksum)
{
	if (lpFileName == NULL || lpOutChecksum == NULL)
		return FALSE;


	HANDLE hFile = CreateFile(lpFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);

	if (hFile == INVALID_HANDLE_VALUE)
		return FALSE;

	MD5_CTX context;

	MD5Init(&context);

	void *buffer = malloc(64000);

	DWORD dwBytesRead = 0;

	while(ReadFile(hFile, buffer, 64000, &dwBytesRead, NULL) == TRUE)
	{
		if (dwBytesRead == 0)	// end of file?
			break;

		MD5Update(&context, (byte *) buffer, (size_t) dwBytesRead);
	}

	CloseHandle(hFile);
	free(buffer);


	MD5Final(&context);
	hex2ascii(lpOutChecksum, (char *) context.digest, sizeof(context.digest));

	return TRUE;
}
Beispiel #12
0
TEST(UTIL, hex2ascii) {
  EXPECT_EQ('0', hex2ascii(0x0));
  EXPECT_EQ('9', hex2ascii(0x9));
  EXPECT_EQ('A', hex2ascii(0xA));
  EXPECT_EQ('F', hex2ascii(0xF));
}
Beispiel #13
0
/**
 * @brief	Read Option Setting function
 * @param	command	: Serial command buffer without command header
 * @param	size	: Serial command buffer size without command header
 * @return	0 of the successful, error code if else
 * @note	ex) C,10,tTeE --> Converter Mode: deley: 10, Setting to the command header of active mode
 * 				first parameter: Select for active mode
 * 				                 C--> Converter Mode
 * 				                 P--> Pair Mode (not yet supported)
 * 				second parameter: delay,,,	"delay" mean is can to serial, serial to can of delay
 * 				third parameter: Change the command header
 *
 */
uint32_t RO_Command(uint8_t *command, uint32_t size) {
	volatile uint32_t len;
	uint8_t tmp[30];
	volatile uint32_t ind;

	memset(tmp, 0, 30);
	switch (option.ActiveMode) {
	case ACTIVE_CONVERTER_MODE:
		tmp[0] = 'C';
		tmp[1] = ',';
		break;
	case ACTIVE_PAIR_MODE:
		tmp[0] = 'P';
		tmp[1] = ',';
		break;
	default:
		return 0;
	}
	len = int2ascii(option.intDelay, &tmp[2], 3);
	if (len == 0) {
		return 0;
	}
	tmp[len + 2] = ',';
	ind = len + 3;



#ifdef dd
	len = int2ascii(can.Baudrate, &tmp[2], 4);
	if (len == 0) {
		return 0;
	}
	tmp[len + 2] = ',';
	ind = len + 3;
	len = hex2ID(can.ID, can.Spec, &tmp[ind], 8);
	if (len == 0) {
		return 0;
	}
	tmp[can.Spec + ind] = ',';
	ind = can.Spec + ind + 1;

	len = hex2ID(can.Mask, can.Spec, &tmp[ind], 8);
	if (len == 0) {
		return 0;
	}

	tmp[len + ind] = ',';
	ind = can.Spec + ind;
	ind = ind + 1;

	if(can.DAR)
		SETDAR(function);
	if(can.ABOR)
		SETABOR(function);

	tmp[ind++] = hex2ascii(function);
	tmp[ind++] = 0x0d;
#endif

	memcpy(ReadSetting, tmp, ind);

	return 1;
}
Beispiel #14
0
// read parameters
void readParseCGI()
{
  char* params;
  char* value;
  char *valuepairs[MAX_GA];
  char *cgistr;
  int i=0,j=0;
  cgistr = parseRequest();
  if(cgistr == NULL)
    cgidie ("No data");
  hex2ascii(cgistr);
  params=strtok(cgistr,"&");
  while( params != NULL && i < MAX_GA)
  {
      valuepairs[i] = (char *)malloc(strlen(params)+1);
      if(valuepairs[i] == NULL)
         return;
      valuepairs[i] = params;
      params=strtok(NULL,"&");
      i++;
  }
  while (i > j)
  {
      value=strtok(valuepairs[j],"=");
      if ( value != NULL )
      {
          if (strcmp (value,"url") == 0)
          {
            value=strtok(NULL,"=");
#ifdef BETA
            if ( value != NULL )
                 *eiburl = (char *) strdup(value);
/* FIXME: Security - define url from ENV - Parameter only for devel */
#endif
          }
          else if (strcmp (value,"a") == 0)
          {
            value=strtok(NULL,"=");
            if (value==NULL)
        	break;
            if (isNumeric(value))
              gadest=atoi(value);
            else
              gadest=readgaddr(value);
          }
          else if (strcmp (value,"d") == 0)
          {
            value=strtok(NULL,"=");
            if (isNumeric(value))
            {
              dpt=atoi(value);
            }
          }
          else if (strcmp (value,"v") == 0)
          {
            value=strtok(NULL,"=");
            if ( value != NULL && strlen(value)<50 )
              strcpy(data,value);
          }
          else
          {
            //printf ("Unknown param %s\n",value); //debug
          }

      }
      j++;
  }
}
Beispiel #15
0
void ReadCANFrame(uint8_t *Buf, uint32_t *BufSize) {

	uint8_t tmpStr[30];
	uint32_t ind = 0;
	uint32_t format = FORMAT;
	uint32_t ID;
	uint8_t DLC;
	uint8_t dataTmp;
	uint32_t j;
	uint8_t tmp;
	uint32_t idCount;
	memset(tmpStr,0,30);

	if (rx_can_msg[RX_CAN_READ_BUFFER_POINT].mode_id & CAN_MSGOBJ_EXT)
		format |= EXT_FRAME;
	else
		format |= STD_FRAME;
	if (rx_can_msg[RX_CAN_READ_BUFFER_POINT].mode_id & CAN_MSGOBJ_RTR)
		format |= REMOTE_FRAME;
	else
		format |= DATA_FRAME;

	switch (format) {
	case STD_DATA:
		tmpStr[ind++] = STD_DAT;
		ID = rx_can_msg[RX_CAN_READ_BUFFER_POINT].mode_id & 0x7FF;
		idCount = 3;
		break;
	case STD_REMOTE:
		tmpStr[ind++] = STD_RET;
		ID = rx_can_msg[RX_CAN_READ_BUFFER_POINT].mode_id & 0x7FF;
		idCount = 3;
		break;
	case EXT_DATA:
		tmpStr[ind++] = EXT_DAT;
		ID = rx_can_msg[RX_CAN_READ_BUFFER_POINT].mode_id & 0x1FFFFFFF;
		idCount = 8;
		break;
	case EXT_REMOTE:
		tmpStr[ind++] = EXT_RET;
		ID = rx_can_msg[RX_CAN_READ_BUFFER_POINT].mode_id & 0x1FFFFFFF;
		idCount = 8;
		break;
	default:
		return;
	}

	for (j = idCount; j > 0; ind++, j--) {
		tmp = ID & 0xf;
		ID = ID >> 4;
		tmpStr[j] = hex2ascii(tmp);
	}

	DLC = rx_can_msg[RX_CAN_READ_BUFFER_POINT].dlc;
	tmpStr[ind++] = hex2ascii(DLC);

	if ((format & REMOTE_FRAME) != REMOTE_FRAME) {
		for (j = 0; j < (DLC * 2); j++) {
			if (j % 2) {
				dataTmp = rx_can_msg[RX_CAN_READ_BUFFER_POINT].data[j / 2]
						& 0x0f;
				tmpStr[ind++] = hex2ascii(dataTmp);
			} else {
				dataTmp = (rx_can_msg[RX_CAN_READ_BUFFER_POINT].data[j / 2]
						& 0xf0) >> 4;
				tmpStr[ind++] = hex2ascii(dataTmp);
			}
		}
	}


	tmpStr[ind++] = 0x0d;
	memcpy(Buf, tmpStr, ind);

	*BufSize = ind;

}
Beispiel #16
0
int main(int argc, char *argv[])
{
	// stir depth and nonce length
	ub4 dep, sdep = MAXM, lnce = NLEN;
	ub4 rounds = 7;
	#ifdef MOTE-REPO
	enum CSPRNG rng = MOTE8;
	enum CSPRNG hasher = BB512;
	#else
	#ifdef BB-REPO
	enum CSPRNG rng = BB128;
	enum CSPRNG hasher = MOTE32;	
	#else
	enum CSPRNG rng = MOTE32;
	enum CSPRNG hasher = BB512;
	#endif
	#endif
	enum ciphermode cmode   = cmNone;
	enum ciphertype ctype	= ctNone;
	enum outputform oform	= ofASC;
	// input: message & key-phrase
	char msg[MAXM] = ""; 
	char key[MAXM] = "";
	// ciphertext & plaintext
	char ctx[MAXM], ptx[MAXM];
	// derived & stretched key
	char kdf[MAXK] = "";
	// IV/nonce
	char nce[MAXK] = "";
	// check the command line
	if (argc >= 5) {
		if ((argc>=2) && strlen(argv[1])<MAXM) strcpy(msg,argv[1]);
		if ((argc>=3) && strlen(argv[1])<MAXK) strcpy(key,argv[2]);
		if (argc>=4)
			if ((strcmp(argv[3],"d")==0) || (strcmp(argv[3],"D")==0))
				 cmode = cmDecipher; else
			if ((strcmp(argv[3],"e")==0) || (strcmp(argv[3],"E")==0)) 
				 cmode = cmEncipher; else cmode = cmNone;
		if (argc>=5)
			#ifdef NEVER
			if ((strcmp(argv[4],"v")==0) || (strcmp(argv[4],"V")==0))
				 ctype = ctVernam; else
			#endif
			if ((strcmp(argv[4],"c")==0) || (strcmp(argv[4],"C")==0))
				 ctype = ctCaesar; else
			if ((strcmp(argv[4],"m")==0) || (strcmp(argv[4],"M")==0)) 
				ctype = ctCaesarM; else ctype = ctNone;
		if (argc>=6) 
			if ((strcmp(argv[5],"a")==0) || (strcmp(argv[5],"A")==0))
				oform = ofASC; else oform = ofHEX;
		if (argc>=7) rng = (enum CSPRNG)(atoi(argv[6]) % 7);
	}
	// sanity checks
	if (TRUE) {
		if ((strlen(msg)<MINM) || (strlen(key)<MINK)) { info(); exit(0); }
		if ((cmode==cmNone) || (ctype==ctNone))       { info(); exit(0); }
		// only hex output available for Vernam
		if (ctype==ctVernam) oform=ofHEX;
		// output mode MOD 26? (not possible with Vernam)
		if ((oform==ofASC) && (ctype!=ctVernam)) { MOD=26; START='A'; }
		// no nonce scrambling or mixing available with hex output
		if (oform==ofHEX) SCRAMBLER=NONCE=MIX=FALSE;
	}
	// B E G I N  P R E P A R A T I O N
	// preliminary seeding
	rSeedAll(key,rounds);
	
	if (SCRAMBLER) {
		sdep = SetDepth(rng,strlen(key));
		#ifdef LOG
		char tmp[12]=""; sprintf(tmp,"%d",sdep);
		log_add("RNG",rName(rng));
		log_add("HSH",rName(hasher));
		log_add("DEP",tmp);
		#endif
	}
	
	if (NONCE) {
		// obtain nonce/IV hash of fixed or random length
		strcpy(nce,rNonce(hasher,FALSE));
		// note nonce length for later
		lnce = strlen(nce);
	}

	// Key-derivation starts:
	if (TRUE) {
		// 1) seed MOTE with a key-derived hash
		strcpy(kdf,rHash(hasher,key,rStateSize(rng)*4));
		rSeed(rng,kdf,rounds);
		// 2) calculate stir-depth
		dep = rDepth(rng,kdf);
		// 3) warm up MOTE with <dep> rounds
		rStir(rng,dep); 
	}
	#ifdef TEST
		#ifdef LOG
		log_add("DKY",leftstr(kdf,LINE));
		#endif
	#endif
	// Key-derivation ends.
	
	if (SCRAMBLER) {
		// prepare scrambler's random pool
		RandPool_Fill(rng);
	}
	// E N D  P R E P A R A T I O N.
	
	// B E G I N  M A I N  C I P H E R  S E Q U E N C E
	// Mode: Encipher
	if (cmode==cmEncipher) {
		// pre-process message if output is mod 26
		if (oform==ofASC) strcpy(msg, PreProcessText(msg));
			#ifdef LOG
			if (oform==ofASC) log_add("MSG",msg);
			#endif
		// Encrypt: Vernam XOR
		if (ctype==ctVernam)  strcpy(ctx, Vernam(rng,msg));
		// Encrypt: Caesar MOD
		if (ctype==ctCaesar)  strcpy(ctx, rCaesarStr(rng, cmEncipher, msg, MOD, START));
		// Encrypt: Caesar MIX
		if (ctype==ctCaesarM) strcpy(ctx, rmCaesarStr(rng, cmEncipher, msg, MOD, START));
		// convert to hexadecimal as appropriate
		if (oform==ofHEX) strcpy(ctx,ascii2hex(ctx));
			#ifdef LOG
			log_add(" CT",ctx);
			#endif
		if (MIX) {
			// Mix: Vigenere-cipher the ciphertext on the nonce
			strcpy(ctx,Vig(rng,cmode,ctx,nce,MOD,START,FALSE));
				#ifdef LOG
				log_add("NCE",nce);
				log_add("VCT",ctx);
				#endif
		}
		if (NONCE) {
			// append ciphertext to nonce
			strcat(nce,ctx); strcpy(ctx,nce);
				#ifdef LOG
				log_add("NCT",ctx);
				#endif
		}
		if (SCRAMBLER) {
			// prepare scrambler context & scramble ciphertext
			InitRandPairs(rng,sdep,strlen(ctx));
			strcpy(ctx,Scrambled(ctx,sdep));
				#ifdef LOG
				log_add("SCT",ctx);
				#endif
		}
	}
	// Mode: Decipher
	if (cmode==cmDecipher) {
		// Convert hexadecimal ciphertext to ASCII (not in mod 26)
		if (oform==ofHEX) strcpy(ctx, hex2ascii(msg)); else strcpy(ctx, msg);
		if (SCRAMBLER) {
				#ifdef LOG
				log_add("SCT",ctx);
				#endif
			// prepare scrambler context & unscramble ciphertext
			InitRandPairs(rng,sdep,strlen(ctx));
			strcpy(ctx,unScrambled(ctx,sdep));
				#ifdef LOG
				log_add("UST",ctx);
				#endif
		}
		if (NONCE) {
			// detach ciphertext from nonce
			strcpy(nce,leftstr(ctx,lnce));
			strcpy(ctx,rightstr(ctx,strlen(msg)-lnce));
				#ifdef LOG
				log_add("VCT",ctx);
				log_add("NCE",nce);
				#endif
		}
		if (MIX) {
			// Un-mix: Vigenere-decipher the ciphertext on the nonce
			strcpy(ctx,Vig(rng,cmode,ctx,nce,MOD,START,FALSE));
				#ifdef LOG
				log_add("UVC",ctx);
				#endif
		}
		// Decrypt: Vernam XOR
		if (ctype==ctVernam) strcpy(ptx, Vernam(rng,ctx));
		// Decrypt: Caesar MOD
		if (ctype==ctCaesar)  strcpy(ptx, rCaesarStr(rng, cmDecipher, ctx, MOD, START));
		// Decrypt: Caesar MIX
		if (ctype==ctCaesarM) strcpy(ptx, rmCaesarStr(rng, cmDecipher,ctx, MOD, START));
		// post-process plaintext if output is mod 26
		if (oform==ofASC) strcpy(ptx, PostProcessText(ptx));
	}  
	// E N D  M A I N  C I P H E R  S E Q U E N C E .
	#ifdef LOG
	log_show ();
	log_clear();
	#endif
	// P R O G R A M  O U T P U T
	if ((strcmp(ptx,"") != 0) || (strcmp(ctx,"") != 0)) {
		// Mode: Encipher
		if (cmode==cmEncipher) puts(ctx);
		// Mode: Decipher
		if (cmode==cmDecipher) puts(ptx);
		
		// belt'n'braces memory wipe
		if (TRUE) {
			rResetAll(); rResetAll();
			memset(msg,0,sizeof(msg));memset(msg,0xFF,sizeof(msg));memset(msg,0,sizeof(msg));
			memset(key,0,sizeof(key));memset(key,0xFF,sizeof(key));memset(key,0,sizeof(key));
			memset(kdf,0,sizeof(kdf));memset(kdf,0xFF,sizeof(kdf));memset(kdf,0,sizeof(kdf));
			memset(ctx,0,sizeof(ctx));memset(ctx,0xFF,sizeof(ctx));memset(ctx,0,sizeof(ctx));
			memset(ptx,0,sizeof(ptx));memset(ptx,0xFF,sizeof(ptx));memset(ptx,0,sizeof(ctx));
			dep=0;
		}
		
	} else info();

	return 0;
}
Beispiel #17
0
TEST(UTIL, hex2ascii_out_of_range) {
  EXPECT_EQ('0', hex2ascii(0x2A));
}
Beispiel #18
0
static void rsp_pass_through_command ( const rsp_buf * const buf, const int cmd_str_pos )
{
  static const std::string HELP_PREFIX( "help" );
  static const std::string READSPR_PREFIX ( "readspr" );
  static const std::string WRITESPR_PREFIX( "writespr" );
  static const std::string RESET_PREFIX( "reset" );

  try
  {
    // The actual command follows the "qRcmd," RSP request in ASCII encoded in hex.

    std::string cmd = hex2ascii( &(buf->data[ cmd_str_pos ]) );
    ltrim( &cmd );
    rtrim( &cmd );

    if ( cmd.empty() )
      throw std::runtime_error( "No target-specific command specified." );

    // printf( "Monitor cmd: %s\n", cmd.c_str() );

    if ( str_remove_prefix( &cmd, &HELP_PREFIX ) )
    {
      remove_cmd_separator( &cmd );

      if ( ! cmd.empty() )
      {
        throw std::runtime_error( "Error parsing the target-specific 'help' command: this command does not take any arguments." );
      }

      std::string help_text = "\nAvailable target-specific commands:\n\n";
      help_text += "- monitor help\n";
      help_text += "  Displays this help text.\n";
      help_text += "\n";
      help_text += "- monitor readspr <16-bit Special Purpose Register number in hex>\n";
      help_text += "  The register value is printed in hex.\n";
      help_text += "  This example reads the Debug Stop Register (DSR), whose number is\n";
      help_text += "  (6 << 11) [0x3000] + 20 = 0x3014:\n";
      help_text += "    monitor readspr 3014\n";
      help_text += "\n";
      help_text += "- monitor writespr <register number in hex> <register value in hex>\n";
      help_text += "\n";
      help_text += "- monitor reset\n";
      help_text += "  Resets the CPU.\n";
      help_text += "\n";

      send_pass_through_command_text_reply( rsp.client_fd, help_text.c_str() );
    }
    else if ( str_remove_prefix( &cmd, &READSPR_PREFIX ) )
    {
      remove_cmd_separator( &cmd );
      unsigned int regno;

      // Parse and return error if we fail.
      if ( 1 != sscanf( cmd.c_str(), "%x", &regno ) )
      {
        throw std::runtime_error( "Error parsing the target-specific 'readspr' command." );
      }

      if ( regno >= MAX_SPRS )
      {
        throw std::runtime_error( format_msg( "Error parsing the target-specific 'readspr' command: SPR number %u is out of range.", regno ) );
      }

      uint32_t reg_val;
      dbg_cpu0_read_spr_e( uint16_t( regno ), &reg_val );

      const std::string reply_str = format_msg( "%08x\n", reg_val );

      send_pass_through_command_text_reply( rsp.client_fd, reply_str.c_str() );
    }
    else if ( str_remove_prefix( &cmd, &WRITESPR_PREFIX ) )
    {
      remove_cmd_separator( &cmd );
      unsigned int       regno;
      unsigned long int  val;

      if ( 2 != sscanf( cmd.c_str(), "%x %lx", &regno, &val ) )
      {
        throw std::runtime_error( "Error parsing the target-specific 'writespr' command." );
      }

      if ( regno >= MAX_SPRS )
      {
        throw std::runtime_error( format_msg( "Error parsing the target-specific 'writespr' command: SPR number %u is out of range.", regno ) );
      }

      dbg_cpu0_write_spr_e( uint16_t( regno ), val );

      send_ok_packet( rsp.client_fd );
    }
    else if ( str_remove_prefix( &cmd, &RESET_PREFIX ) )
    {
      remove_cmd_separator( &cmd );

      if ( ! cmd.empty() )
      {
        throw std::runtime_error( "Error parsing the target-specific 'reset' command: this command does not take any arguments." );
      }

      // In order to save FPGA resources, there is no reset signal or command in the Debug Unit.
      // We reset the CPU here by manually writing all necessary SPRs.

      const uint32_t RESET_SPR_SR = 0x8001;  // See the RESET_SPR_SR constant in the CPU Verilog source code.
      const uint32_t RESET_VECTOR = 0x0100;  // See the RESET_VECTOR constant in the CPU Verilog source code.

      dbg_cpu0_write_spr_e( SPR_SR , RESET_SPR_SR );
      dbg_cpu0_write_spr_e( SPR_NPC, RESET_VECTOR );

      dbg_cpu0_write_spr_e( SPR_EPCR_BASE, 0 );
      dbg_cpu0_write_spr_e( SPR_EEAR_BASE, 0 );
      dbg_cpu0_write_spr_e( SPR_ESR_BASE, 0 );

      // The CPU uses another initial value for the GPRs, namely 0x12345678, which is fine.
      // According to the OpenRISC specification, it is not necessary to initialise these registers.
      const uint32_t INITIAL_GPR_VALUE = 0xABCDEF01;

      for ( int i = 0; i < MAX_GPRS; ++i )
      {
        dbg_cpu0_write_spr_e( SPR_GPR_BASE + i, INITIAL_GPR_VALUE );
      }

      std::string msg( "The basic CPU core was reset.\n" );

      if ( rsp.spr_upr & SPR_UPR_PICP )
      {
        dbg_cpu0_write_spr_e( SPR_PICMR, 0 );
        msg += "The CPU PIC unit (Programmable Interrupt Controller) was reset.\n";
      }

      if ( rsp.spr_upr & SPR_UPR_TTP )
      {
        dbg_cpu0_write_spr_e( SPR_TTMR, 0 );
        dbg_cpu0_write_spr_e( SPR_TTCR, 0 );
        msg += "The CPU Tick Timer unit was reset.\n";
      }

      send_pass_through_command_text_reply( rsp.client_fd, msg.c_str() );
    }
    else
      throw std::runtime_error( "Unknown target-specific command." );
  }
  catch ( const std::exception & e )
  {
    std::string err_msg( e.what() );
    err_msg += "\n";

    send_pass_through_command_text_reply( rsp.client_fd, err_msg.c_str() );
  }
}
int Cmotor_control::init_system()
{
	comflag = 0;				
	hCom = NULL;	

	long ret0;
	HKEY rhandle;
	int nCount = 0;
	TCHAR ValueName[_MAX_PATH];     //
	TCHAR ValueData[_MAX_PATH];   
	DWORD nValueSize = _MAX_PATH;   
	DWORD nDataSize = _MAX_PATH;  
	CString strtemp;				//
	DWORD nType; 
	unsigned char sendbuffer[5];
	unsigned char revbuffer[5];
	unsigned long ltemp;
	unsigned long i;
	//取得串口
	ret0 = (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Hardware\\DeviceMap\\SerialComm"), 0, KEY_READ,&rhandle));
	if(ret0!=ERROR_SUCCESS) 
		return -1;  
	if(::RegEnumValue(rhandle, nCount, ValueName, &nValueSize, NULL, &nType,(LPBYTE)ValueData, &nDataSize) ==ERROR_NO_MORE_ITEMS)
		return -1;
	//打开串口
	strtemp = ValueData;
	strtemp.Insert(0,_T("\\\\.\\"));
	hCom=CreateFile(strtemp,				//多功能函数,可以创建以下对象,并返回访问句柄:控制台,通信资源,目录(只读打开),磁盘驱动器,文件,邮槽,管道
		GENERIC_READ|GENERIC_WRITE, 
		0, 
		NULL,
		OPEN_EXISTING, 
		0, 
		NULL);
	if(hCom==(HANDLE)-1)
	{
		AfxMessageBox(TEXT("打开COM失败!"));
		//DWORD x = GetLastError();
		//x = x;
		return -1;
	}
	SetupComm(hCom,1024,1024);		//初始化一个指定的通信设备的通信参数

	COMMTIMEOUTS TimeOuts;			//在用ReadFile和WriteFile读写串行口时,需要考虑超时问题

	TimeOuts.ReadIntervalTimeout=MAXDWORD;
	TimeOuts.ReadTotalTimeoutMultiplier=1;
	TimeOuts.ReadTotalTimeoutConstant=5;


	TimeOuts.WriteTotalTimeoutMultiplier=100;
	TimeOuts.WriteTotalTimeoutConstant=500;
	SetCommTimeouts(hCom,&TimeOuts);				//设定通讯设备读写时的超时参数
	DCB dcb;										//串口通讯的DCB结构
	DWORD errret;
	GetCommState(hCom,&dcb);
	//设置通讯参数
	dcb.BaudRate=9600; 
	dcb.ByteSize=8;							//指定端口当前使用的数据位
	dcb.Parity=NOPARITY;					//指定端口当前使用的奇偶校验方法
	dcb.StopBits=ONESTOPBIT;				//指定端口当前使用的停止位数
	if(!SetCommState(hCom,&dcb))
		errret = GetLastError();

	PurgeComm(hCom,PURGE_TXCLEAR|PURGE_RXCLEAR);		//清空缓冲区
	comflag = 1;
	//载入配置
	FILE *fl;
	fl = fopen("dataset.ini","rb");
	if(fl == NULL)
	{
		return 0;
	}
	fread(&rstep,sizeof(rstep),1,fl);
	fclose(fl);
	//配置下载到设备
	ltemp = rstep;
	if(ltemp > 9999)
	{
		return 0;
	}
	sendbuffer[0] = 0x05;
	sendbuffer[1] = 0x00;
	hex2ascii(&(sendbuffer[2]),rstep);
	if(FALSE == WriteFile(hCom,sendbuffer,5,&i,NULL)|| (i == 0))
	{
		return 0;
	}
	Sleep(100); 
	if(FALSE == ReadFile(hCom,revbuffer,5,&i,NULL)|| (i == 0))
	{
		return 0;
	}
	if(revbuffer[0] != 0x01)
	{
		return 0;
	}
	return 1;
}