[emilien-guilmineau.fr] PHP et la cryptographie
This file contains 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 | |
function show_int_values($string) { | |
$result = ''; | |
$chars = str_split($string); | |
foreach ($chars as $char) { | |
$result .= ord($char) . "-"; | |
} | |
return substr($result, 0, strlen($result) - 1); | |
} | |
function encrypt_decrypt($action, $string) | |
{ | |
// Initialisation d'une valeur de retour par défaut | |
$output = false; | |
// Méthode de chiffrement des données | |
$encrypt_method = "AES-256-CBC"; | |
// Clé de chiffrement | |
$secret_key = "S4a5Qy@pPv2Di2jz^*WMrxZM6@X5za/.ss24x"; | |
// Vecteur d'initialisation | |
$secret_iv = "i6qwQgZS&Q@CfPfb/.P2E"; | |
// Calcul de la signature numérique (via SHA256) de la clé secrète | |
$key = hash("sha256", $secret_key); | |
// Calcul de la signature numérique (via SHA256) du vecteur d'initialisation | |
$hashedIv = hash("sha256", $secret_iv); | |
// Puis troncation du résultat pour ne garder que 16 caractères, | |
// parce que la méthode de chiffrement AES-256-CBC s'attend à avoir | |
// un vecteur d'initialisation de 16 bytes | |
$iv = substr($hashedIv, 0, 16); | |
echo "Hash de la clé secrète : " . mb_detect_encoding($key) . " -> " . $key . "\r\n"; | |
echo "Hash du vecteur d'init : " . mb_detect_encoding($iv) . " -> " . $iv . "\r\n"; | |
echo show_int_values($iv) . "\r\n"; | |
// Options à passer à OpenSSL pour le chiffrement. La valeur 0 indique qu'aucune options n'est utilisée | |
$cipherOptions = 0; | |
// Contrôle de l'action à réaliser (chiffrement ou déchiffrement) | |
if ($action == "encrypt") { | |
// Appel à l'API OpenSSL pour chiffrer la donnée | |
$output = openssl_encrypt( $string, $encrypt_method, $key, $cipherOptions, $iv ); | |
// Affichage du résultat brut de chiffrement | |
echo "Résultat brut du chiffrement : " . $output . "\r\n"; | |
// Encodage en base64 du résultat de chiffrement | |
$output = base64_encode($output); | |
} elseif ($action == "decrypt") { | |
// On décode le texte (en base64) pour avoir le flux réel à décrypter | |
$encryptedValue = base64_decode($string); | |
// Appel à l'API OpenSSL pour déchiffrer la donnée | |
$output = openssl_decrypt( $encryptedValue, $encrypt_method, $key, 0, $iv ); | |
} | |
// Renvoi de la valeur chiffrée ou déchiffrée, sous forme de chaîne de caractères | |
return $output; | |
} | |
$texteAChiffrer = "Emilien GUILMINEAU"; | |
$action = "encrypt"; | |
$texteChiffré = encrypt_decrypt( $action, $texteAChiffrer ); | |
echo $texteAChiffrer . " -> " . $texteChiffré; | |
?> |
This file contains 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
using System.Security.Cryptography; | |
using System.Text; | |
// Clé de chiffrement | |
string secretKey = "S4a5Qy@pPv2Di2jz^*WMrxZM6@X5za/.ss24x"; | |
// Vecteur d'initialisation du chiffrement | |
string secretIv = "i6qwQgZS&Q@CfPfb/.P2E"; | |
// Transformation des secrets en tableau d'octets en vu de la signé numériquement via le mécanisme SHA256 | |
byte[] hashKey = SHA256.HashData(Encoding.ASCII.GetBytes(secretKey)); | |
byte[] hashIv = SHA256.HashData(Encoding.ASCII.GetBytes(secretIv)); | |
string texteAChiffrer = "Emilien GUILMINEAU"; | |
var texteChiffré = Encrypt(texteAChiffrer, hashKey, hashIv); | |
var texteChiffréBytes = Encoding.ASCII.GetBytes(texteChiffré); | |
var texteEncodé = Convert.ToBase64String(texteChiffréBytes, 0, texteChiffréBytes.Length); | |
Console.WriteLine($"{texteAChiffrer} -> {texteEncodé}"); | |
string Encrypt(string plainText, byte[] key, byte[] iv) | |
{ | |
// Création d'un nouvel objet AES pour effectuer un chiffrement symétrique | |
Aes encryptor = Aes.Create(); | |
encryptor.Mode = CipherMode.CBC; | |
// Affectation de la clé et du vecteur d'initialisation à l'objet AES | |
var hexKey = ToHexString(key); | |
if (hexKey.Length > 32) | |
hexKey = hexKey.Substring(0, 32); | |
encryptor.Key = Encoding.ASCII.GetBytes(hexKey); | |
Console.WriteLine($"Hash de la clé secrète : {ToHexString(key)}"); | |
var hexIv = ToHexString(iv); | |
if (hexIv.Length > 16) | |
hexIv = hexIv.Substring(0, 16); | |
encryptor.IV = Encoding.ASCII.GetBytes(hexIv); | |
Console.WriteLine($"Hash du vecteur d'init : {hexIv}"); | |
Console.WriteLine(encryptor.IV.Select(b => b.ToString()).Aggregate((left, right) => left + "-" + right )); | |
// Création des flux mémoire, outil de chiffrement et flux d'écriture des données à chiffrer | |
using MemoryStream memoryStream = new MemoryStream(); | |
using ICryptoTransform aesEncryptor = encryptor.CreateEncryptor(); | |
using CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write); | |
// Conversion du texte en clair, en un tableau d'octets | |
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText); | |
// Chiffrement du texte en clair | |
cryptoStream.Write(plainBytes, 0, plainBytes.Length); | |
// Terminaison du flux de chiffrement | |
cryptoStream.FlushFinalBlock(); | |
// Récupération du texte chiffré présenta dans le flux mémoire | |
byte[] cipherBytes = memoryStream.ToArray(); | |
// Fermeture du flux mémoire et du flux d'écriture des données à chiffrer | |
memoryStream.Close(); | |
cryptoStream.Close(); | |
Console.WriteLine($"Résultat brut du chiffrement : {ToHexString(cipherBytes)}"); | |
// Conversion en base64 et renvoi en sortie du texte chiffré | |
return Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length); | |
} | |
string ToHexString(byte[] hashedBytes) { | |
var result = new StringBuilder(); | |
for (int i = 0; i < hashedBytes.Length; i++) { | |
result.Append(hashedBytes[i].ToString("x2")); | |
} | |
return result.ToString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment