Hướng dẫn php encrypt/decrypt with salt - php mã hóa / giải mã với muối

Bạn muốn sử dụng một số loại thuật toán mã hóa bí mật được chia sẻ như AES. Cả OpenSSL và McRypt nên hỗ trợ điều này. Tôi muốn giới thiệu OpenSSL vì McRypt là EOL.

Ví dụ sau đây đến trực tiếp từ php.net. Bạn có thể không cần HMAC vì bạn muốn truy xuất dữ liệu gốc.

Tệp này chứa văn bản unicode hai chiều có thể được giải thích hoặc biên dịch khác với những gì xuất hiện dưới đây. Để xem xét, hãy mở tệp trong một trình soạn thảo cho thấy các ký tự Unicode ẩn. Tìm hiểu thêm về các ký tự unicode hai chiều

functionEncrypt ($ data, $ password) { encrypt($data, $password){
$ iv = chuỗi con (sha1 (mt_rand ()), 0, 16);iv = substr(sha1(mt_rand()), 0, 16);
$ Mật khẩu = sha1 ($ Mật khẩu);password = sha1($password);
$ muối = sha1 (mt_rand ());salt = sha1(mt_rand());
$ SaltWithPassword = Hash ('SHA256', $ Mật khẩu. $ Salt);saltWithPassword = hash('sha256', $password.$salt);
$ được mã hóa = openSSL_encrypt (encrypted = openssl_encrypt(
"$ data", 'AES-256-cbc', "$ saltwithPassword", null, $ iv$data", 'aes-256-cbc', "$saltWithPassword", null, $iv
);
$ msg_encrypted_bundle = "$ iv: $ Salt: $ được mã hóa";msg_encrypted_bundle = "$iv:$salt:$encrypted";
trả về $ msg_encrypted_bundle; $msg_encrypted_bundle;
}
functionDecrypt ($ msg_encrypted_bundle, $ password) { decrypt($msg_encrypted_bundle, $password){
$ Mật khẩu = sha1 ($ Mật khẩu);password = sha1($password);
$ muối = sha1 (mt_rand ());components = explode( ':', $msg_encrypted_bundle );
$ SaltWithPassword = Hash ('SHA256', $ Mật khẩu. $ Salt);iv = $components[0];
$ được mã hóa = openSSL_encrypt (salt = hash('sha256', $password.$components[1]);
"$ data", 'AES-256-cbc', "$ saltwithPassword", null, $ ivencrypted_msg = $components[2];
);decrypted_msg = openssl_decrypt(
$ msg_encrypted_bundle = "$ iv: $ Salt: $ được mã hóa";encrypted_msg, 'aes-256-cbc', $salt, null, $iv
);
$ msg_encrypted_bundle = "$ iv: $ Salt: $ được mã hóa"; ( $decrypted_msg === false )
trả về $ msg_encrypted_bundle; false;
} $decrypted_msg;
}
functionDecrypt ($ msg_encrypted_bundle, $ password) {d = encrypt('this is message', 'secret key');
echo giải mã ($ d, 'khóa bí mật'); decrypt($d,'secret key');