开发者

Comparing Strings in MATLAB Problem

I've been fiddling around with my program and I've b开发者_C百科een using a modified version of urlread that allows for BASIC authentication. The problem is that I have to include the following line of code to the base urlread function:

urlConnection.setRequestProperty('Authorization', 'Basic passphrase');

...where passphrase is the a base64 encoded string of 'user:pass'. If I place the passphrase directly into the string on that line the program will work just fine, the trouble starts when I try to concatenate to get that resulting 'Basic passphrase' string. Initially I just had:

['Basic', ' ', passphrase]

After that did not work I did some exploring and experimenting around in the command window.:

passphrase = 'somerandompassphrase';
teststr1 = ['Basic', ' ', passphrase];
teststr2 = ['Basic', ' ', 'somerandompassphrase'];
teststr3 = 'Basic somerandompassphrase';
strcmp(teststr1, teststr2)
strcmp(teststr1, teststr3)
strcmp(teststr2, teststr3)

The output is 1, or true for each one (as expected). However if I take the base64encode of 'somerandompassphrase' (which is 'c29tZXJhbmRvbXBhc3NwaHJhc2U='):

encoded = base64encode(passphrase);
teststr1 = ['Basic', ' ', encoded];
teststr2 = ['Basic', ' ', 'c29tZXJhbmRvbXBhc3NwaHJhc2U='];
strcmp(teststr1, teststr2)

The output is 0, or false. Shouldn't it be true though? The base64encode function can be found here.

Even from a quick test of:

strcmp(encoded, 'c29tZXJhbmRvbXBhc3NwaHJhc2U=')

The output is still 0.

Please help, I have no idea what's going on.


As shown here, you can also use the base64 encoder from the the Apache Commons Codec Java library which comes bundled with MATLAB and is available on the classpath:

encoder = org.apache.commons.codec.binary.Base64();
b64str = char( encoder.encode(passphrase-0) )';


I actually figured this out right before I posted the question, but I figured I'd go ahead and leave it up in case people run into the same problem as I did.

The problem is from the base64encode function. It automatically adds a newline character to the end of the string, causing the strcmp function to return false. To fix this you can include a parameter for the optional parameter to the base64encode function, if you put in a blank string it won't add a newline character to the end of it causing it to work.

encoded = base64encode(passphrase, '');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜