Search code examples
ccryptographyxor

XOR certain bytes in c


I am wondering if anyone can help me. I am new to c and only learning. So this questain may seem confused. I have an unsigned int value that I need to split into bytes then xor certain bytes together and then get the result. I want represent the value as (0, a0 ⊕ a1,a2 ⊕a3,0).

Decimal value = 62910759 or Hex value = 3BFF127;

unsigned int value = 62910759;

// W = (0, a0 ⊕ a1,a2 ⊕a3,0);

unsigned int L = 0x04000000L^ W ;

Solution

  • I don't know if this helps you, but i calculate the bytes first and then XOR some of them:

    unsigned int value = 62910759;
    unsigned char a = value >> 24 & 0xFF; // First byte/ high byte
    unsigned char b = value >> 16 & 0xFF;
    unsigned char c = value >> 8 & 0xFF;
    unsigned char d = value & 0xFF; // Last byte/ smallest byte
    printf("%.2X %.2X %.2X %.2X\n", a,b,c,d);
    
    unsigned char aXORb = a^b; // a XOR b
    unsigned char bXORc = b^c;
    unsigned char cXORd = c^d;
    unsigned char dXORa = d^a;
    
    printf("%.2X %.2X %.2X %.2X\n", aXORb,bXORc,cXORd,dXORa);
    

    Try it here.

    Output:

    03 BF F1 27
    BC 4E D6 24
    

    Note: I think uint8_t would be more "C-like" but the result will be the same anyway.

    @Jimbo Jones Here is the last step. The zeros are unnecessary, but i included them for better understanding the code.

    unsigned int result = (0x00 << 24) + (aXORb << 16) + (cXORd << 8) + 0x00;
    Method(0x02000000L^ result);
    

    If you mean with W = (0, a0 ⊕ a1,a2 ⊕a3,0) that the first 8 bit are 0 and the next 8 a XOR b and so on.