XOR encryption

XOR operation

XOROperation, Chinese called "exclusive OR operation."

It is defined as: two values are the same, returns false, otherwise it returns true. That is to say, XORcan be used to determine whether the two values are different.

Corresponding to the following truth table:

Enter
AB
Output
A XOR B
0 0 0
0 1 1
1 0 1
1 1 0

XOR application

XOR operation has a wonderful feature: If a value do it twice XOR, will return the value itself.

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

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

Encrypted data

iOS encrypted data as follows:

Loop through each of the data bytes, each data corresponding to the encryption key value corresponding XOR operation, the XOR data with the original data and then do the exchange.

-(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;
    
}

 

reference

Guess you like

Origin www.cnblogs.com/Free-Thinker/p/11445702.html
XOR