openssl_sign

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_signGera assinatura

Descrição

openssl_sign(
    string $data,
    string &$signature,
    #[\SensitiveParameter] OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
    string|int $algorithm = OPENSSL_ALGO_SHA1
): bool

openssl_sign() calcula uma assinatura para os dados informados em data gerando uma assinatura digital criptográfica usando a chave privada associada a private_key. Observe que os dados em si não são criptografados.

Parâmetros

data

A string de dados a ser assinada.

signature

Se a chamada for bem-sucedida, a assinatura será retornada em signature.

private_key

OpenSSLAsymmetricKey - uma chave, retornada por openssl_get_privatekey()

string - uma chave no formato PEM

algorithm

int - um destes Algoritmos de Assinatura.

string - uma string válida retornada por openssl_get_md_methods(), por exemplo, "sha256WithRSAEncryption" ou "sha384".

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Registro de Alterações

Versão Descrição
8.0.0 private_key agora aceita uma instância de OpenSSLAsymmetricKey ou OpenSSLCertificate; anteriormente, um resource do tipo OpenSSL key ou OpenSSL X.509 era aceito.

Exemplos

Exemplo #1 Exemplo de openssl_sign()

<?php
// Presume-se que $data contenha os dados a serem assinados

// busca a chave privada do arquivo e a prepara
$pkeyid = openssl_pkey_get_private("file://src/openssl-0.9.6/demos/sign/key.pem");

// calcula assinatura
openssl_sign($data, $signature, $pkeyid);

// libera a chave da memória
openssl_free_key($pkeyid);
?>

Exemplo #2 Exemplo de openssl_sign()

<?php
// dados a serem assinados
$data = 'my data';

// cria nova chave pública e privada
$new_key_pair = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
openssl_pkey_export($new_key_pair, $private_key_pem);

$details = openssl_pkey_get_details($new_key_pair);
$public_key_pem = $details['key'];

// cria assinatura
openssl_sign($data, $signature, $private_key_pem, OPENSSL_ALGO_SHA256);

// grava para mais tarde
file_put_contents('private_key.pem', $private_key_pem);
file_put_contents('public_key.pem', $public_key_pem);
file_put_contents('signature.dat', $signature);

// verifica assinatura
$r = openssl_verify($data, $signature, $public_key_pem, "sha256WithRSAEncryption");
var_dump($r);
?>

Veja Também

adicione uma nota

Notas Enviadas por Usuários (em inglês) 2 notes

up
11
edmarw at yahoo dot com
17 years ago
This may help if you just want a real-simple private/public key pair:<?php$data = "Beeeeer is really good.. hic...";// You can get a simple private/public key pair using:// openssl genrsa 512 >private_key.txt// openssl rsa -pubout <private_key.txt >public_key.txt// IMPORTANT: The key pair below is provided for testing only. // For security reasons you must get a new key pair// for production use, obviously.$private_key = <<<EOD-----BEGIN RSA PRIVATE KEY-----MIIBOgIBAAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6zxqlVzz0wy2j4kQVUC4ZRZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQJAL151ZeMKHEU2c1qdRKS9sTxCcc2pVwoAGVzRccNX16tfmCf8FjxuM3WmLdsPxYoHrwb1LFNxiNk1MXrxjH3R6QIhAPB7edmcjH4bhMaJBztcbNE1VRCEi/bisAwiPPMq9/2nAiEA3lyc5+f6DEIJh1y6BWkdVULDSM+jpi1XiV/DevxuijMCIQCAEPGqHsF+4v7Jj+3HAgh9PU6otj2nY79nJtCYmvhoHwIgNDePaS4inApN7omp7WdXyhPZhBmulnGDYvEoGJN66d0CIHraI2SvDkQ5CmrzkW5qPaE2oO7BSqAhRZxiYpZFb5CI-----END RSA PRIVATE KEY-----EOD;$public_key = <<<EOD-----BEGIN PUBLIC KEY-----MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6zxqlVzz0wy2j4kQVUC4ZRZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQ==-----END PUBLIC KEY-----EOD;$binary_signature = "";// At least with PHP 5.2.2 / OpenSSL 0.9.8b (Fedora 7)// there seems to be no need to call openssl_get_privatekey or similar.// Just pass the key as defined aboveopenssl_sign($data, $binary_signature, $private_key, OPENSSL_ALGO_SHA1);// Check signature$ok = openssl_verify($data, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);echo "check #1: ";if ($ok == 1) {    echo "signature ok (as it should be)\n";} elseif ($ok == 0) {    echo "bad (there's something wrong)\n";} else {    echo "ugly, error checking signature\n";}$ok = openssl_verify('tampered'.$data, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);echo "check #2: ";if ($ok == 1) {    echo "ERROR: Data has been tampered, but signature is still valid! Argh!\n";} elseif ($ok == 0) {    echo "bad signature (as it should be, since data has beent tampered)\n";} else {    echo "ugly, error checking signature\n";}?>
up
4
tim at remitone dot com
2 years ago
It should be noted that the default signature algorithm used by openssl_sign() and openssl_verify (OPENSSL_ALGO_SHA1) is no longer supported by default in OpenSSL Version 3 series.With an up to date OpenSSL library, one has to run"update-crypto-policies --set LEGACY"on the server where the library resides in order to allow these functions to work without the optional alternative algorithm argument.
To Top