验证node.js中的php证书

时间:2013-02-20 15:21:58

标签: php node.js ssl rsa

我有以下用于验证证书的php函数:

<?php

function raven_check_sig($data, $sig) {
    $key_path = '/path/to/pubkey.crt';
    $key_crt = file_get_contents($key_path);
    $key = openssl_get_publickey($key_crt);

    $result = openssl_verify($data, base64_decode($sig), $key);

    openssl_free_key($key);

    if ($result == 1) {
        return TRUE;
    } else {
        return FALSE;
    }
}

我正在将我的应用程序移植到node.js,但我无法弄清楚如何实现此功能。

我试过了:

function checkSignature(data, sig, kid) {
  var keyPath = '/path/to/pubkey.crt';
  var key = fs.readFileSync(keyPath);

  var verifier = crypto.createVerify('RSA-SHA256');
  verifier.update(data);
  var res = verifier.verify(key, sig, 'base64');

  if (res) {
    return true;
  } else {
    return false;
  }
}

但似乎总是返回false。我有两个问题,我认为可能是导致失败的原因:

  1. 我不知道RSA-SHA256是否是验证证书的正确算法,因为我无法解决openssl_verify的问题。
  2. 我不知道调用openssl_get_publickey的等价是什么,假设我确实需要这样的东西。
  3. 文件pubkey.crt的内容是:

    -----BEGIN CERTIFICATE-----
    MIIDrTCCAxagAwIBAgIBADANBgkqhkiG9w0BAQQFADCBnDELMAkGA1UEBhMCR0Ix
    EDAOBgNVBAgTB0VuZ2xhbmQxEjAQBgNVBAcTCUNhbWJyaWRnZTEgMB4GA1UEChMX
    VW5pdmVyc2l0eSBvZiBDYW1icmlkZ2UxKDAmBgNVBAsTH0NvbXB1dGluZyBTZXJ2
    aWNlIFJhdmVuIFNlcnZpY2UxGzAZBgNVBAMTElJhdmVuIHB1YmxpYyBrZXkgMjAe
    Fw0wNDA4MTAxMzM1MjNaFw0wNDA5MDkxMzM1MjNaMIGcMQswCQYDVQQGEwJHQjEQ
    MA4GA1UECBMHRW5nbGFuZDESMBAGA1UEBxMJQ2FtYnJpZGdlMSAwHgYDVQQKExdV
    bml2ZXJzaXR5IG9mIENhbWJyaWRnZTEoMCYGA1UECxMfQ29tcHV0aW5nIFNlcnZp
    Y2UgUmF2ZW4gU2VydmljZTEbMBkGA1UEAxMSUmF2ZW4gcHVibGljIGtleSAyMIGf
    MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/9qcAW1XCSk0RfAfiulvTouMZKD4j
    m99rXtMIcO2bn+3ExQpObbwWugiO8DNEffS7bzSxZqGp7U6bPdi4xfX76wgWGQ6q
    Wi55OXJV0oSiqrd3aOEspKmJKuupKXONo2efAt6JkdHVH0O6O8k5LVap6w4y1W/T
    /ry4QH7khRxWtQIDAQABo4H8MIH5MB0GA1UdDgQWBBRfhSRqVtJoL0IfzrSh8dv/
    CNl16TCByQYDVR0jBIHBMIG+gBRfhSRqVtJoL0IfzrSh8dv/CNl16aGBoqSBnzCB
    nDELMAkGA1UEBhMCR0IxEDAOBgNVBAgTB0VuZ2xhbmQxEjAQBgNVBAcTCUNhbWJy
    aWRnZTEgMB4GA1UEChMXVW5pdmVyc2l0eSBvZiBDYW1icmlkZ2UxKDAmBgNVBAsT
    H0NvbXB1dGluZyBTZXJ2aWNlIFJhdmVuIFNlcnZpY2UxGzAZBgNVBAMTElJhdmVu
    IHB1YmxpYyBrZXkgMoIBADAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBAUAA4GB
    AFciErbr6zl5i7ClrpXKA2O2lDzvHTFM8A3rumiOeauckbngNqIBiCRemYapZzGc
    W7fgOEEsI4FoLOjQbJgIrgdYR2NIJh6pKKEf+9Ts2q/fuWv2xOLw7w29PIICeFIF
    hAM+a6/30F5fdkWpE1smPyrfASyXRfWE4Ccn1RVgYX9u
    -----END CERTIFICATE-----
    

1 个答案:

答案 0 :(得分:3)

证明正确的算法是SHA1:

function checkSignature(data, sig) {
  var keyPath = '/path/to/pubkey.crt';
  var key = fs.readFileSync(keyPath);

  var verifier = crypto.createVerify('SHA1');
  verifier.update(data);
  var res = verifier.verify(key, sig, 'base64');

  if (res) {
    return true;
  } else {
    return false;
  }
}

所以现在一切正常:)