Byte array in objective c with ascii encoding

安稳与你 提交于 2021-02-19 08:37:52

问题


I am trying to get a byte array from an NSString in objective c using ascii encoding. I need to this array to calculate the SHA256 hash of that string and then compare the result to the SHA256 encoding generated in Windows.

    NSString *myString = @"123456¥";
const char *string = (const unsigned char *) [myString cStringUsingEncoding:NSASCIIStringEncodin];

this always gives nil since it contains the ¥ character.

the problem is I cannot use UTF8Encoding since the hash generated by windows uses ASCII encoding like so:

string text ="123456¥";
byte[] arrSHA = System.Text.Encoding.ASCII.GetBytes(text);

although using UTF8 Encoding in objective c does work, I cannot use it as it will give a different byte array than the one generated in .Net which will result a completely different SHA for that string.

Any suggestions on how to make this work?

UPDATE:

reading the documentation about ASCII encoding in .Net it seems that it convert every non ASCII character to ?. Can I detect these characters in objective c and manually replace them with ?

Regards


回答1:


The best solution would be if the server used UTF-8 instead of ASCII encoding. If that is not an option, you can use the following code for the conversion, where all non-ASCII characters are substituted by a question mark (error-checking omitted for brevity):

NSString *myString = @"ä123€456¥";

CFIndex asciiLength;
// Determine length of converted data:
CFStringGetBytes((__bridge CFStringRef)(myString), CFRangeMake(0, [myString length]),
                 kCFStringEncodingASCII, '?', false, NULL, 0, &asciiLength);
// Allocate buffer:
uint8_t *asciiBuffer = malloc(asciiLength);
// Do the conversion:
CFStringGetBytes((__bridge CFStringRef)(myString), CFRangeMake(0, [myString length]),
                 kCFStringEncodingASCII, '?', false, asciiBuffer, asciiLength, NULL);

// Check the result:
printf("%.*s\n", (int)asciiLength, asciiBuffer);
// Output: ?123?456?

There is (as far as I know) no equivalent NSString method, therefore you have to use the "toll-free bridge" from NSString to CFStringRef and a Core Foundation function.



来源:https://stackoverflow.com/questions/20031873/byte-array-in-objective-c-with-ascii-encoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!