查詢

openssl_spki_verify()函式—用法及示例

「 驗證一個SPKI(Subject Public Key Info)結構的簽名 」


函式名稱:openssl_spki_verify()

函式描述:該函式用於驗證一個SPKI(Subject Public Key Info)結構的簽名。

適用版本:PHP 5 >= 5.6.0, PHP 7

語法:bool openssl_spki_verify(resource $spki, string $algorithm, string $signature)

引數:

  • $spki:SPKI結構的資源控制代碼,可以透過openssl_spki_new()函式建立。
  • $algorithm:簽名演算法,如"sha256"、"sha384"、"sha512"等。
  • $signature:要驗證的簽名。

返回值:

  • 如果簽名驗證成功,則返回true。
  • 如果簽名驗證失敗,則返回false。

示例:

// 建立SPKI結構
$spki = openssl_spki_new();

// 生成金鑰對
$privateKey = openssl_pkey_new();
$details = openssl_pkey_get_details($privateKey);
$publicKey = $details['key'];

// 將公鑰新增到SPKI結構中
openssl_spki_export($spki, $spkiout);
$spkiWithPublicKey = openssl_spki_add_publickey($spkiout, $publicKey);

// 對SPKI結構進行簽名
openssl_spki_sign($spkiWithPublicKey, $privateKey, $spkisigned);

// 驗證簽名
$isValid = openssl_spki_verify($spkiWithPublicKey, "sha256", $spkisigned);
if ($isValid) {
    echo "簽名驗證成功!";
} else {
    echo "簽名驗證失敗!";
}

注意事項:

  1. 在使用openssl_spki_verify()函式之前,需要先建立一個SPKI結構,可以透過openssl_spki_new()函式建立。
  2. 必須使用相同的簽名演算法和金鑰對對SPKI結構進行簽名和驗證。
  3. 在示例中,生成了一個隨機的金鑰對,並將公鑰新增到SPKI結構中,然後對SPKI結構進行簽名並驗證簽名的有效性。
  4. 可以根據實際需求選擇不同的簽名演算法,如"sha256"、"sha384"、"sha512"等。
  5. 如果簽名驗證成功,將返回true;如果簽名驗證失敗,將返回false。
補充糾錯
上一個函式: openssl_verify()函式
熱門PHP函式
分享連結