Struggling with DES implementation in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Mog1992
    New Member
    • Jul 2014
    • 2

    #1

    Struggling with DES implementation in C

    I am trying to encrypt a plaintext using DES in C. I read about the algorithm and how it works, but when i came to write the code i struggled. I hope that you could help me by answering the following questions for me:

    How to locate the lowest 8-bits in a 64-bit key ?

    How to shuffle the plaintext according to the algorithm description ?
    (I read about bitwise operations, but i still cannot understand how i can use them to transfer for example the 5th bit to the location of the 30th bit)

    Left shifting the key would not wrap the bits, so i just bitwise or with a mask that will add the bits that did not wrap around ?

    Any information would be appreciated, thanks.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    ...transfer for example the 5th bit to the location of the 30th bit...

    To get the 5th bit (count from 0 moving left) use a mask and the AND the mask to the data:

    00100000 mask
    11100110 data
    AND
    00100000 result

    If the 5th bit is set the result is true. If not set, the result is false. Use this to set to reset the 30th bit.

    I will use the 2nd bit rather than 30 to avoid big typing.

    00000100 2nd bit (count from 0 moving left)

    To set the 2nd bit use a mask and OR the data

    00000100 2nd bit
    00011100 data with 2nd bit already set
    OR
    00011100 data result

    00000100 2nd bit
    00011000 data with 2nd bit currently not set
    OR
    00011100 data result

    To reset the 2nd bit use an inverted mask and AND the data:

    11111011 mask
    00011100 data with 2nd bit already set
    AND
    00011000 result

    You can use bit shft operators to create your mask:

    1 << 2 is 00000100

    if you NOT this mask you get the inverted mask:

    ~(1 << 2) is 11111011.

    So your real code might look like:

    Reset the 2nd bit:

    Code:
    data = data & ~(1<<2);
    which is usually written as:

    Code:
    data &= ~(1<<2);

    Comment

    • Mog1992
      New Member
      • Jul 2014
      • 2

      #3
      Thank you very much.

      Comment

      Working...