Created
January 15, 2020 11:01
-
-
Save dusterio/f61104b39291c97a76cd5f61935579fb to your computer and use it in GitHub Desktop.
Add parity bits to a 7 byte DES encryption key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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