2 个 NSString 之间的异或给出了错误的结果

发布于 2024-12-10 21:12:42 字数 808 浏览 2 评论 0原文

我有这个方法可以在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

老旧海报 2024-12-17 21:12:42

您是否正确设置了 pBytesInputpBytesKey 变量?目前,您有 unsigned char* pBytesInput = (unsigned char*)[stringKey bytes]; (即输入是“密钥”),而 pBytesKey 是设备 ID。这看起来很奇怪。

另外,使用 UTF-8 编码时要小心。 UTF-8 使用字符串中任何字节的高位来指示多字节字符“延续”到下一个字节。通过将加密中最后一个字节的高位设置为您的编码,可能会生成无效的 UTF-8。

不仅如此,您还必须说出“错误结果”是什么。

Are you setting your pBytesInput and pBytesKey variables correctly? At the moment, you have unsigned char* pBytesInput = (unsigned char*)[stringKey bytes]; (i.e. the input is the "key"), and pBytesKey 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文