如何使用PHP解密bash中openssl以AES-256-CBC+PBKDF2加密的文件
三个参数的获取方法
openssl_pbkdf2的salt参数:你使用openssl enc默认生成的加密文件,头部8字节为固定标识Salted__,紧随其后的8字节就是所需的salt,直接从文件内容截取即可。openssl_pbkdf2的key_length参数:AES-256算法要求密钥长度为32字节(256位),加上AES-CBC模式所需的16字节IV,你可以一次性派生48字节的衍生数据,因此该参数填48即可;如果仅单独派生密钥,填32即可。openssl_decrypt的iv参数:从上述pbkdf2生成的48字节衍生数据中,截取后16字节即为IV。
完整解密示例代码
<?php $cryptFilePath = './crypt'; $encryptPassword = 'MYPASSWORD'; // 读取加密文件内容 $cryptContent = file_get_contents($cryptFilePath); if (!$cryptContent) { die('读取加密文件失败'); } // 校验加密文件格式 if (substr($cryptContent, 0, 8) !== 'Salted__') { die('非标准openssl enc加密格式文件'); } // 提取salt $salt = substr($cryptContent, 8, 8); // 派生密钥+IV $derivedData = openssl_pbkdf2( $encryptPassword, $salt, 48, // 32字节密钥 + 16字节IV总长度 10000, // 对应加密命令中的-iter 10000参数 'sha3-256' // 对应加密命令中的-md sha3-256参数 ); if (!$derivedData) { die('密钥派生失败:' . openssl_error_string()); } // 拆分密钥和IV $key = substr($derivedData, 0, 32); $iv = substr($derivedData, 32, 16); // 提取密文内容(跳过前16字节的头+salt) $ciphertext = substr($cryptContent, 16); // 执行解密 $plaintext = openssl_decrypt( $ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, // 密文为原始二进制格式 $iv ); if (!$plaintext) { die('解密失败:' . openssl_error_string()); } // 输出解密结果(示例中为hello world+换行) echo $plaintext;
内容的提问来源于stack exchange,提问作者allan.simon
相关产品推荐
相关产品推荐

