大刘的 iOS 自学笔记

字符串异或

2022-06-25  本文已影响0人  大刘

Created by 大刘 liuxing8807@126.com

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSString (UTIL)

+ (nonnull NSString *)simpleXor:(nonnull NSString *)info key:(nonnull NSString *)key;

@end

NS_ASSUME_NONNULL_END
#import "NSString+UTIL.h"

@implementation NSString (UTIL)

+ (nonnull NSString *)simpleXor:(nonnull NSString *)info key:(nonnull NSString *)key {
    const char *infoBytes = [info UTF8String];
    const char *keyBytes = [key UTF8String];
    
    int i = 0, j = 0;
    char *bytes = malloc(strlen(infoBytes));
    for (i = 0; i < strlen(infoBytes); i++) {
        bytes[i] = (char) (infoBytes[i] ^ keyBytes[j]);
        
        j++;
        j = j % (key.length);
    }
    
    // 使用strlen(infoBytes), 而不是strlen(bytes)
    // 因为bytes里面有\0,而strlen只计算\0之前数,所以最终的长度偏小
    NSData *data = [NSData dataWithBytes:bytes length:strlen(infoBytes)];
    free(bytes);
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return str;
}

@end
#import <Foundation/Foundation.h>
#import "NSString+UTIL.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        /**
         这就是异或运算⊕的特征:
         0⊕x=x
         1⊕x=x'(x'表示取反)
         x⊕x=0
         所以有:y⊕x⊕x=y
         */
        NSString *str = [NSString simpleXor:@"DALIU" key:@"123456"];
        NSLog(@"%@", str); // us\^?}`
        str = [NSString simpleXor:str key:@"123456"];
        NSLog(@"%@", str); // DALIU
    }
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读