Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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