Example #1
0
int base64_binlength(char* str, uint8_t strict){
	int l=0;
	uint8_t term=0;
	for(;;){
		if(*str=='\0')
			break;
		if(*str=='\n' || *str=='\r'){
			str++;
			continue;
		}
		if(*str=='='){
			term++;
			str++;
			if(term==2){
				break;
			}
			continue;
		}
		if(term)
			return -1;
		if(ascii2bit6(*str)==-1){
			if(strict)
				return -1;
		} else {
			l++;
		}
		str++;
	}
	switch(term){
		case 0:
			if(l%4!=0)
				return -1;
			return l/4*3;
		case 1:
			if(l%4!=3)
				return -1;
			return (l+1)/4*3-1;
		case 2:
			if(l%4!=2)
				return -1;
			return (l+2)/4*3-2;
		default:
			return -1;
	}
}
Example #2
0
int base64dec(void *dest, const char *b64str, uint8_t strict){
	uint8_t buffer[4];
	uint8_t idx=0;
	uint8_t term=0;
	for(;;){
//		cli_putstr_P(PSTR("\r\n  DBG: got 0x"));
//		cli_hexdump(b64str, 1);
		buffer[idx]= ascii2bit6(*b64str);
//		cli_putstr_P(PSTR(" --> 0x"));
//		cli_hexdump(buffer+idx, 1);
		
		if(buffer[idx]==0xFF){
			if(*b64str=='='){
				term++;
				b64str++;
				if(term==2)
					goto finalize; /* definitly the end */
			}else{
				if(*b64str == '\0'){
					goto finalize; /* definitly the end */
				}else{
					if(*b64str == '\r' || *b64str == '\n' || !(strict)){
						b64str++; /* charcters that we simply ignore */
					}else{
						return -1;
					}
				}
			}
		}else{
			if(term)
				return -1; /* this happens if we get a '=' in the stream */
			idx++;
			b64str++;
		}
		if(idx==4){
			((uint8_t*)dest)[0] = buffer[0]<<2 | buffer[1]>>4;
			((uint8_t*)dest)[1] = buffer[1]<<4 | buffer[2]>>2;
			((uint8_t*)dest)[2] = buffer[2]<<6 | buffer[3];
			dest = (uint8_t*)dest +3;
			idx=0;
		}
	}