查詢

openssl_sign()函式—用法及示例

「 對資料進行簽名,使用指定的私鑰進行加密 」


函式名:openssl_sign()

適用版本:PHP 4 >= 4.0.4, PHP 5, PHP 7

用法:openssl_sign()函式用於對資料進行簽名,使用指定的私鑰進行加密。簽名後的資料可以透過openssl_verify()函式進行驗證。

語法: bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, mixed $signature_alg = OPENSSL_ALGO_SHA256 ] )

引數:

  • $data:要簽名的資料,可以是字串或二進位制資料。
  • $signature:簽名後的資料將被儲存在此變數中。
  • $priv_key_id:私鑰識別符號,可以是由openssl_pkey_get_private()函式返回的私鑰資源,或者是PEM格式的私鑰字串。
  • $signature_alg:簽名演算法,預設為OPENSSL_ALGO_SHA256。可以使用openssl_get_md_methods()函式獲取可用的簽名演算法列表。

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

示例:

// 載入私鑰
$privateKey = openssl_pkey_get_private(file_get_contents('private_key.pem'));

// 要簽名的資料
$data = "Hello, world!";

// 簽名資料
if (openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256)) {
    echo "簽名成功!\n";
    echo "簽名資料:" . base64_encode($signature) . "\n";
} else {
    echo "簽名失敗!\n";
}

// 驗證簽名
$publicKey = openssl_pkey_get_public(file_get_contents('public_key.pem'));
if (openssl_verify($data, $signature, $publicKey, OPENSSL_ALGO_SHA256)) {
    echo "簽名驗證透過!\n";
} else {
    echo "簽名驗證失敗!\n";
}

// 釋放資源
openssl_free_key($privateKey);
openssl_free_key($publicKey);

注意事項:

  1. 私鑰和公鑰需要透過openssl_pkey_get_private()和openssl_pkey_get_public()函式載入。
  2. 簽名演算法可以根據具體需求選擇,常見的演算法有OPENSSL_ALGO_SHA1、OPENSSL_ALGO_SHA256等。
  3. 在實際使用中,私鑰應該妥善保管,不能洩露給他人。
補充糾錯
上一個函式: openssl_spki_export()函式
下一個函式: openssl_seal()函式
熱門PHP函式
分享連結