2 个 NSString 之间的异或给出了错误的结果
我有这个方法可以在 2 个 NSString 之间进行异或,我在 NSLog 上打印结果,但这不是预期的。 无法弄清楚我做错了什么。
(void)XorSecretKeyDeviceId
{
NSString* secretKey = @"123";//
NSString* deviceId = @"abcdef";//
NSData* stringKey = [secretKey dataUsingEncoding:NSUTF8StringEncoding];
NSData* stringDeviceId = [deviceId dataUsingEncoding:NSUTF8StringEncoding];
unsigned char* pBytesInput = (unsigned char*)[stringKey bytes]; //Bytes
unsigned char* pBytesKey = (unsigned char*)[stringDeviceId bytes];
unsigned int vlen = [secretKey length]; //Keys Length
unsigned int klen = [deviceId length];
unsigned int v;
unsigned int k = vlen % klen;
unsigned char c;
for(v = 0; v < vlen; v++)
{
c = pBytesInput[v] ^ pBytesKey[k];
pBytesInput[v] = c;
NSLog(@"%c", c);
k = (++k < klen ? k : 0);
}
}
I have this method to make a xor between 2 NSStrings, i´m printing the result on NSLog but it isn´t the expect.
Can´t figure out what i´m doing wrong.
(void)XorSecretKeyDeviceId
{
NSString* secretKey = @"123";//
NSString* deviceId = @"abcdef";//
NSData* stringKey = [secretKey dataUsingEncoding:NSUTF8StringEncoding];
NSData* stringDeviceId = [deviceId dataUsingEncoding:NSUTF8StringEncoding];
unsigned char* pBytesInput = (unsigned char*)[stringKey bytes]; //Bytes
unsigned char* pBytesKey = (unsigned char*)[stringDeviceId bytes];
unsigned int vlen = [secretKey length]; //Keys Length
unsigned int klen = [deviceId length];
unsigned int v;
unsigned int k = vlen % klen;
unsigned char c;
for(v = 0; v < vlen; v++)
{
c = pBytesInput[v] ^ pBytesKey[k];
pBytesInput[v] = c;
NSLog(@"%c", c);
k = (++k < klen ? k : 0);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否正确设置了
pBytesInput
和pBytesKey
变量?目前,您有unsigned char* pBytesInput = (unsigned char*)[stringKey bytes];
(即输入是“密钥”),而pBytesKey
是设备 ID。这看起来很奇怪。另外,使用 UTF-8 编码时要小心。 UTF-8 使用字符串中任何字节的高位来指示多字节字符“延续”到下一个字节。通过将加密中最后一个字节的高位设置为您的编码,可能会生成无效的 UTF-8。
不仅如此,您还必须说出“错误结果”是什么。
Are you setting your
pBytesInput
andpBytesKey
variables correctly? At the moment, you haveunsigned char* pBytesInput = (unsigned char*)[stringKey bytes];
(i.e. the input is the "key"), andpBytesKey
is the device ID. This seems odd.Also, be careful using UTF-8 encoding. UTF-8 uses the high bit on any byte in the string to indicate a "continuation" of a multi-byte character into the next byte. Your encoding could plausibly generate invalid UTF-8 by giving the setting the high bit of the final byte in the encryption.
For more than that, you'll have to say what the "wrong result" is.