Encrypt and Decrypt String With Key PHP [duplicate

2020-04-06 03:04发布

I'm looking for some functions to encrypt and decrypt strings in php using a key specified.

Thanks!

4条回答
趁早两清
2楼-- · 2020-04-06 03:47
Luminary・发光体
3楼-- · 2020-04-06 03:49

A basic openssl implementation I've used before:

class MyEncryption
{

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

You would need to generate the RSA key pair. See here for information on how to do that. Storing the private key in the file itself is a bad idea. This is just an example. Ideally you would want the user to supply the private key at decryption time

查看更多
该账号已被封号
4楼-- · 2020-04-06 03:52

I assume you meant symmetric key encryption. mcrypt does support several algorithms (Like AES, Tripel DES). There is one catch though, it doesn't support any padding algorithm so you wouldn't be able to get the original length back. You have 2 options to get around this issue,

  1. Add a length field in front of your clear-text. Say use first 4 bytes as length.

  2. Do PKCS#5 padding yourself. There are code examples on this page: http://www.php.net/manual/en/function.mcrypt-encrypt.php

查看更多
ゆ 、 Hurt°
5楼-- · 2020-04-06 03:57

have you tried mcrypt?

查看更多
登录 后发表回答