I used the polarssl base64.c file to decode some data.
int base64_decode( unsigned char *dst, size_t *dlen,
const unsigned char *src, size_t slen ){
size_t i, n=0;
uint32_t j, x;
unsigned char *p;
for( i = n = j = 0; i < slen; i++ )
{
if( ( slen - i ) >= 2 &&
src[i] == '\r' && src[i + 1] == '\n' )
continue;
if( src[i] == '\n' )
continue;
if( src[i] == '=' && ++j > 2 )
return( POLARSSL_ERR_BASE64_INVALID_CHARACTER );
if( src[i] > 127 || base64_dec_map[src[i]] == 127 )
return( POLARSSL_ERR_BASE64_INVALID_CHARACTER );
if( base64_dec_map[src[i]] < 64 && j != 0 )
return( POLARSSL_ERR_BASE64_INVALID_CHARACTER );
n++;
}
n = ((n * 6) + 7) >> 3;
if( dst == NULL || *dlen < n )
{
*dlen = n;
return( POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL );
}
for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ ){
if( *src == '\r' || *src == '\n' )
continue;
j -= ( base64_dec_map[*src] == 64 );
x = (x << 6) | ( base64_dec_map[*src] & 0x3F );
if( ++n == 4 )
{
n = 0;
if( j > 0 ) *p++ = (unsigned char)( x >> 16 );
if( j > 1 ) *p++ = (unsigned char)( x >> 8 );
if( j > 2 ) *p++ = (unsigned char)( x );
}
}
*dlen = p - dst;
return( 0 );
}
When my data comes to this part of the code, "n" is more than "* dlen"; but when I do this part, as the comment function also works well.
if( dst == NULL || *dlen < n )
{
*dlen = n;
return( POLARSSL_ERR_BASE64_BUFFER_TOO_SMALL );
}
Is it possible that this piece of code is not needed? I mean, if I remove this part from the function, would I skip the part in the business logic?
Edit:
For instance:
src: A7ViV8hpIon0lisFRCvQpw ==
dlen: 18
dst: 3 b5 62 57 c8 69 22 89 f4 96 2b 5 44 2b d0 a7 0 0
in fact, the last two zeros in 'dst' should not be in the correct result when I send 'dlen' as 16 and comment that if the statement, I get the correct result. I think n the calculation is wrong or I missed something.