查詢

openssl_pkcs7_encrypt()函式—用法及示例

「 使用PKCS#7標準對資料進行加密 」


函式名稱:openssl_pkcs7_encrypt()

函式描述:該函式用於使用PKCS#7標準對資料進行加密。

用法:

bool openssl_pkcs7_encrypt(
    string $input,
    string $output,
    mixed $certificate,
    array $headers,
    int $flags = 0,
    int $cipher = OPENSSL_CIPHER_RC2_40
): bool

引數:

  • $input:要加密的資料,可以是字串或檔案路徑。
  • $output:加密後的資料輸出路徑。
  • $certificate:加密使用的證書。可以是證書的檔案路徑(字串),也可以是證書的資源識別符號(resource)。
  • $headers:加密後的資料頭部資訊。是一個關聯陣列,用於設定頭部欄位,如Content-Type、Content-Disposition等。
  • $flags(可選):加密標誌位。預設為0,表示不使用標誌位。
  • $cipher(可選):加密演算法。預設為OPENSSL_CIPHER_RC2_40。

返回值:成功返回true,失敗返回false。

示例:

// 加密資料
$input = "This is a secret message.";
$output = "encrypted.txt";
$certificate = "certificate.pem";

$headers = array(
    "Content-Type" => "application/octet-stream",
    "Content-Disposition" => "attachment; filename=encrypted.txt"
);

if (openssl_pkcs7_encrypt($input, $output, $certificate, $headers)) {
    echo "Data encrypted successfully.";
} else {
    echo "Encryption failed.";
}

注意事項:

  • 在使用該函式之前,必須先載入OpenSSL擴充套件。
  • $certificate引數可以是公鑰證書或者包含公鑰的證書鏈。
  • $headers引數是一個關聯陣列,用於設定加密後資料的頭部資訊,可以根據需要自定義。
  • $output引數指定加密後的資料輸出路徑,可以是檔案路徑或者URL。
  • 加密演算法可以透過$cipher引數進行自定義,如果不指定,預設使用OPENSSL_CIPHER_RC2_40演算法。
補充糾錯
上一個函式: openssl_pkcs7_read()函式
下一個函式: openssl_pkcs7_decrypt()函式
熱門PHP函式
分享連結