• XOR 加密


    XOR运算

    XOR运算,中文称为“异或运算”。

    它的定义是:两个值相同时,返回false,否则返回true。也就是说,XOR可以用来判断两个值是否不同。

    对应的真值表如下:

    输入
    A B
    输出
    A XOR B
    0 0 0
    0 1 1
    1 0 1
    1 1 0

    XOR 应用

    XOR 运算有一个很奇妙的特点:如果对一个值连续做两次 XOR,会返回这个值本身。

    // 第一次 XOR
    1010 ^ 1111 // 0101
    
    // 第二次 XOR
    0101 ^ 1111 // 1010
    

    加密数据

    iOS加密数据如下:

    循环遍历数据中的每一个字节,每个字节对应的数据与加密key对应的值做异或运算,然后把异或后的数据与原数据做交换。

    -(NSString *)obfuscate:(NSString *)string withKey:(NSString *)key
    {
        
        NSData* bytes = [string dataUsingEncoding:NSUTF8StringEncoding];
        
        Byte  *myByte = (Byte *)[bytes bytes];
        
        NSData* keyBytes = [key dataUsingEncoding:NSUTF8StringEncoding];
        
        Byte  *keyByte = (Byte *)[keyBytes bytes];
        
        int keyIndex = 0;
        
        for (int x = 0; x < [bytes length]; x++)
        {
            myByte[x]  = myByte[x] ^ keyByte[keyIndex];
                                       
            if (++keyIndex == [keyBytes length])
                {
                    keyIndex = 0;
                }
        }
    
    
    //可以直接返回NSData
        NSData *newData = [[NSData alloc] initWithBytes:myByte length:[bytes length]];
        NSString *aString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
    
        return aString;
        
    }

    参考

  • 相关阅读:
    Python2 cmp() 函数
    Python round() 函数
    Python floor() 函数
    Python ceil() 函数
    Python abs() 函数
    Python oct() 函数
    Python ord() 函数
    Python hex() 函数
    Python2 unichr() 函数
    Android--------工具类StatusBarUtil实现完美状态栏
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/11445702.html
Copyright © 2020-2023  润新知