在PHP中导入RSA密钥

时间:2014-12-31 16:20:18

标签: php encryption rsa public-key-encryption private-key

我想加密/解密/签署......依此类推,我找到了这段代码:

public $pubkey = '...public key here...';
public $privkey = '...private key here...';

public function encrypt($data)
{
    if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
        $data = base64_encode($encrypted);
    else
        throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');

    return $data;
}

public function decrypt($data)
{
    if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
        $data = $decrypted;
    else
        $data = '';

    return $data;
}

唯一的问题是我有一个private.pem(或.key dosnt)格式和问题:

如何在此代码中导入private.pem文件?

1 个答案:

答案 0 :(得分:1)

使用openssl_pkey_get_public()功能:http://php.net/manual/en/function.openssl-pkey-get-public.php

它解密.pem格式并提取工作所需的密钥。