openssl_sign():提供的密钥参数不能被强制转换为私钥

时间:2014-03-24 12:09:43

标签: openssl rsa digital-signature php-openssl

我已经google搜索这些问题的答案。但是我无法找到适合我问题的解决方案,因为很多答案都与问题相关。

当我尝试使用XMLSecurityKeyopenssl_sign创建内容的数字签名时,我收到警告并且未创建签名。

openssl_sign将错误抛出为:

Warning: openssl_sign(): supplied key param cannot be coerced into a private key in /var/www/git/ta_client/accessService.php on line 105

我的代码是:

public function _signMessage($encData, $configValues)
    {
$decode = 'decode';
    $token = $encData['token'];
    $cipherValue = $encData['cipherValue'];
    $clientId = $encData['ClientId'];
    $grpCustNum = $encData['grpCustNum'];

    // Sign the concatenated string
    $toSign = $token . $cipherValue . $clientId . $grpCustNum;

    // Encrypt the token with the public key from vendor
    $cipher = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type'=>'private')); // Reference to XMLSecLibs
    $cipher->loadKey($configValues['privkey'], true);
    try{
    if (! openssl_sign ($toSign, $signature, $cipher->key, OPENSSL_ALGO_MD5)) {
        openssl_error_string();
        throw new Exception();
    }
    }catch(Exception $e){
    print_r($e);
    die;
}
    // append the decode values
    $encData['sign'] = urlencode(base64_encode($signature)) . $decode;
    $encData['token'] = urlencode($token) . $decode;
    $encData['cipherValue'] = urlencode($cipherValue) . $decode;

    return $encData;
}

我的$configValues['privkey']是xml格式。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

openssl不支持XML格式。我的建议是使用phpseclib。即

<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();
$rsa->loadKey('...'); // private key

$plaintext = '...';

$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
$signature = $rsa->sign($plaintext);

我假设你尝试加载的私钥是这种格式吗?:

<RSAKeyValue>
  <Modulus>AKoYq6Q7UN7vOFmPr4fSq2NORXHBMKm8p7h4JnQU+quLRxvYll9cn8OBhIXq9SnCYkbzBVBkqN4ZyMM4vlSWy66wWdwLNYFDtEo1RJ6yZBExIaRVvX/eP6yRnpS1b7m7T2Uc2yPq1DnWzVI+sIGR51s1/ROnQZswkPJHh71PThln</Modulus>
  <Exponent>AQAB</Exponent>
  <P>AN4DDp+IhBca6QEjh4xlm3iexzLajXYrJid6vdWmh4T42nar5nem8Ax39o3ND9b1Zoj41F9zFQmuZ8/AgabreKU=</P>
  <Q>AMQi+R0G9m0K+AcqK3DFpv4RD9jGc0Tle98heNYT7EQvZuuiq4XjvRz0ybqN//bOafrKhsTpRS9DQ7eEpKLI4Bs=</Q>
  <DP>FklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5kX6zk7S0ljKtt2jny2+00VsBerQ==</DP>
  <DQ>AJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2eplU9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhM=</DQ>
  <InverseQ>EaiK5KhKNp9SFXuLVwQalvzyHk0FhnNZcZnfuwnlCxb6wnKg117fEfy91eHNTt5PzYPpf+xzD1FnP7/qsIninQ==</InverseQ>
  <D>Fijko56+qGyN8M0RVyaRAXz++xTqHBLh3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxE=</D>
</RSAKeyValue>

答案 1 :(得分:0)

如果您使用格式错误的私钥或尝试使用公钥签名,则会生成相同的错误...

答案 2 :(得分:0)

此错误消息有多种原因,并且可能极具误导性!

当然,如果您的PEM文件以某种方式损坏或不包含私钥,则会出现此错误消息。

但是当根本无法读取文件时也会出现此错误消息,例如因为没有权限。不幸的是,该消息没有提及。