Skip to content

Instantly share code, notes, and snippets.

@dusterio
Created January 15, 2020 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dusterio/f61104b39291c97a76cd5f61935579fb to your computer and use it in GitHub Desktop.
Save dusterio/f61104b39291c97a76cd5f61935579fb to your computer and use it in GitHub Desktop.
Add parity bits to a 7 byte DES encryption key
<?php
/**
* @param string $key - Input 7 byte DES key, without parity bits, in hex format
* @return string - Output 8 byte DES key, with parity bits, in hex format
*/
function addParityBitsToDESKey($key) {
$binary = base_convert($key, 16, 2);
$bytes = str_split($binary, 7);
foreach ($bytes as $key => $byte) {
$ones = substr_count($byte, '1');
$bytes[$key] .= ($ones % 2 == 0 ? '1' : '0');
}
$characters = array_map(function($byte) {
return chr(base_convert($byte, 2, 10));
}, $bytes);
$string = implode('', $characters);
return bin2hex($string);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment