php rsa签名公钥加密私钥解密 aes加解密 函数

杜茂
2023-12-01
//rsa私钥签名
public function getSign($content, $privateKey){

        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
            wordwrap($privateKey, 64, "\n", true) .
            "\n-----END RSA PRIVATE KEY-----";

        $key = openssl_get_privatekey($privateKey);

        openssl_sign($content, $signature, $key, OPENSSL_ALGO_SHA512);//OPENSSL_ALGO_SHA512 OPENSSL_ALGO_SHA256
        openssl_free_key($key);

        $sign = base64_encode($signature);

        return $sign;
    }

//rsa公钥加密
public function encrypt($content, $publicKey)
    {
        $publicKey= "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($publicKey, 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";

        openssl_public_encrypt($content, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);

        return base64_encode($encrypted);
    }
//rsa私钥解密
public function decrypt($content, $privateKey = '')
    {
        $privateKey = "-----BEGIN PRIVATE KEY-----\n" .
            wordwrap($privateKey , 64, "\n", true) .
            "\n-----END PRIVATE KEY-----";

        $res = openssl_private_decrypt(base64_decode($content), $encrypted, $privateKey , OPENSSL_PKCS1_PADDING);

        return $encrypted;
    }

//rsa公钥加密
public function public_encrypt($content, $publicKey = '')
{
        $publicKey = "-----BEGIN PUBLIC KEY-----\n" .
            wordwrap($publicKey , 64, "\n", true) .
            "\n-----END PUBLIC KEY-----";

        $crypto = '';

        foreach (str_split($content, 117) as $chunk)
        {
            $res = openssl_public_encrypt($chunk, $encryptData, $publicKey );

            $crypto .= $encryptData;
        }
        return base64_encode($crypto);
    }
//rsa私钥解密
public function private_decrypt($data, $rsaPublicKey = '') 
{

        $privateKey = "-----BEGIN PRIVATE KEY-----\n" .
            wordwrap($privateKey , 64, "\n", true) .
            "\n-----END PRIVATE KEY-----";

        $crypto = '';
        foreach (str_split(base64_decode($data), 128) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, $privateKey );
            $crypto .= $decryptData;
        }

        return $crypto;
    }

//AES加密
public  function getAesEncryption($aesString,$key)
    {
        $mothed ='AES-128-CBC';
        $new_key = self::_sha1prng($key);//
        $iv=$key;
        $ret = base64_encode(openssl_encrypt($aesString, $mothed,$new_key, OPENSSL_RAW_DATA, $iv));

        return $ret;
    }
//AES解密
public  function decodeAes($data,$key)
    {
        $mothed ='AES-128-CBC';
        $new_key = self::_sha1prng($key);//
        $iv=$key;
        $ret = openssl_decrypt(base64_decode($data), $mothed, $new_key, OPENSSL_RAW_DATA, $iv);

        return $ret;
    }

//SHA1PRNG算法
public function _sha1prng($key)
    {
        return substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
    }

 类似资料: