Reputation: 277
I want to encrypt a message to string(text) format but I don't know the function which can convert Hex to String:
here is my page :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
// on commence par définir la fonction Cryptage que l'on utilisera ensuite
function Cryptage($TEXT, $Clef) {
$LClef = strlen($Clef);
$LTEXT = strlen($TEXT);
if ($LClef < $LTEXT) {
$Clef = str_pad($Clef, $LTEXT, $Clef, STR_PAD_RIGHT);
} elseif ($LClef > $LTEXT) {
$diff = $LClef - $LTEXT;
$_Clef = substr($Clef, 0, -$diff);
}
return bin2hex($TEXT ^ $Clef);
}
/* On vérifie l’existence de $_POST['TEXT'] et de $_POST['Clef'].
Ça revient au même que isset($_POST['TEXT']) AND isset($_POST['Clef']) */
if (isset($_POST['TEXT'], $_POST['Clef'])) {
$resultat = Cryptage($_POST['TEXT'], $_POST['Clef']);
}
// on a fini les traitement en PHP, on passe à l'affichage :
if (isset($resultat)) {
echo "Chaîne cryptée/décryptée : " . $resultat;
}
?>
<!-- on affiche le formulaire pour que l'utilisateur puisse directement refaire un cryptage/décryptage -->
<form method="post">
<input type="text" name="TEXT" style="width:500px" value="Cliquez ici pour ajouter un texte." onFocus="javascript:this.value=''" />
<input type="text" name="Clef" style="width:500px" value="Cliquez ici pour ajouter un masque." onFocus="javascript:this.value=''" />
<input type="submit" value="Crypter/Décrypter" />
</form>
</body>
</html>
I tested this function but it doesn't return anything (it returns an empty string)
function hextostr($hex)
{
$str='';
for ($i=0; $i < strlen($hex)-1; $i+=2)
{
$str .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $str;
}
do you have any idea, thanks
Upvotes: 2
Views: 14428
Reputation: 3647
function hex2str($hex) {
for($i=0;$i<strlen($hex);$i+=2)
$str .= chr(hexdec(substr($hex,$i,2)));
return $str;
}
Will do the trick
Upvotes: 4
Reputation: 848
Try this function
function hex2str($func_string) {
$func_retVal = '';
$func_length = strlen($func_string);
for($func_index = 0; $func_index < $func_length; ++$func_index) $func_retVal .= chr(hexdec($func_string{$func_index} . $func_string{++$func_index}));
return $func_retVal;
}
I use this one a lot personally so it should work.
Upvotes: 2