Skip to content

Instantly share code, notes, and snippets.

@ar
Created January 23, 2011 00:42
Show Gist options
  • Save ar/791674 to your computer and use it in GitHub Desktop.
Save ar/791674 to your computer and use it in GitHub Desktop.
Adjust parity
public class Util {
/**
* DES Keys use the LSB as the odd parity bit. This method can
* be used enforce correct parity.
*
* @param bytes the byte array to set the odd parity on.
*/
public static void adjustDESParity (byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
int b = bytes[i];
bytes[i] = (byte)((b & 0xfe) | ((((b >> 1) ^ (b >> 2) ^ (b >> 3) ^ (b >> 4) ^ (b >> 5) ^ (b >> 6) ^ (b >> 7)) ^ 0x01) & 0x01));
}
}
/**
* DES Keys use the LSB as the odd parity bit. This method checks
* whether the parity is adjusted or not
*
* @param bytes the byte[] to be checked
* @return true if parity is adjusted else returns false
*/
public static boolean isDESParityAdjusted (byte[] bytes) {
byte[] correct = (byte[])bytes.clone();
adjustDESParity(correct);
return Arrays.equals(bytes, correct);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment