由于 GDPR,我試圖找到一種加密/解密資料的好方法。但是由于我的應用程式同時具有 Delphi 和 PHP 端點,因此我需要具有強大加密功能并在兩者上都可以使用的函式。
搜索SO 我發現了以下一個,但我不知道如何在 Delphi 上執行相同的功能:
function encryptString($plaintext, $password, $encoding = null) {
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}
function decryptString($ciphertext, $password, $encoding = null) {
$ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}
uj5u.com熱心網友回復:
您找到的代碼不是最佳的。一旦確定重復的內容并根據使用常量而不是文字的原則對其進行豐富,就會出現以下 PHP 代碼:
define( 'ALGO_SECRET', 'sha256' ); // SHA-256 = 32 bytes; https://en.wikipedia.org/wiki/SHA-2
define( 'ALGO_MSGAUTH', 'sha256' );
define( 'ALGO_SSL', 'aes-256-cbc' );
define( 'SALT', 'Bedrock Hordes Staples' ); // https://en.wikipedia.org/wiki/Salt_(cryptography)
function encrypt( $plainbytes, $secretkey ) {
// Preparations
$hash= hash( ALGO_SECRET, $secretkey. SALT, true ); // true = return bytes
$iv= openssl_random_pseudo_bytes( 16 ); // 16 bytes; https://en.wikipedia.org/wiki/Initialization_vector
// Actual encryption of the payload
$cipherbytes= openssl_encrypt( $plainbytes, ALGO_SSL, $hash, OPENSSL_RAW_DATA, $iv );
// Adding a modification detection to the encrypted data in front of it; https://en.wikipedia.org/wiki/HMAC
$hmac= hash_hmac( ALGO_MSGAUTH, $cipherbytes. $iv, $hash, true ); // true = return bytes
return $iv. $hmac. $cipherbytes; // 16 32 ? = 48 bytes minimum
}
function decrypt( $allbytes, $secretkey ) {
// Preparations
$hash= hash( ALGO_SECRET, $secretkey. SALT, true ); // Same as in encryption
$iv= substr( $allbytes, 0, 16 ); // Cut into 3 pieces again
$hmac= substr( $allbytes, 16, 32 );
$cipherbytes= substr( $allbytes, 48 );
// Both extracted and recalculated modification detection values must match
$hmac_recalc= hash_hmac( ALGO_MSGAUTH, $cipherbytes. $iv, $hash, true ); // Same as in encryption
if( !hash_equals( $hmac_recalc, $hmac ) ) return null; // Not equal? Payload must be considered tampered/modified/corrupted.
// Actual decryption of the payload
return openssl_decrypt( $cipherbytes, ALGO_SSL, $hash, OPENSSL_RAW_DATA, $iv );
}
我認為這可以輕松區分所有單個專案以及加密和解密程序中有多少是相同的。在 Delphi 或其他語言中執行相同的步驟應該不會那么困難 - 它也可以在兩端沒有 OpenSSL 的情況下作業。
對于現成的示例以及為什么從不處理文本而是只有位元組讀取的解釋:
- 使用 OpenSSL 在 PHP 中加密和解密 在 D7 中使用 DEC5.2 解密和
- 使用 DEC5.2 在 D7 中加密
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315596.html
