简体   繁体   中英

Importing RSA keys in PHP

I wanted to encrypt/decrypt/sign... and so on and I found this code:

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;
}

The only problem is that I got a private.pem (or .key dosnt matter) format and the question:

How should I import my private.pem file in this code?

Use the openssl_pkey_get_public() function: http://php.net/manual/en/function.openssl-pkey-get-public.php

It decrypt the .pem format and extracts the keys necessary for the work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM