<?php
namespace App\Http\Controllers\Utils;
use App\Http\Controllers\Controller;
/**
 * Class Rsa
 * @author <fl140125@gmail.com>
 * @package App\Http\Controllers\Utils
 */
class Rsa extends Controller
{
    
    protected static $instance;
    
    protected $publicKey = '';
    
    protected $privateKey = '';
    private function __clone()
    {
           }
    
    public static function getInstance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new static();
        }
        return self::$instance;
    }
    
    public function __construct()
    {
        $this->privateKey = file_get_contents(public_path(config('app.rsa_private')));
        $this->publicKey  = file_get_contents(public_path(config('app.rsa_public')));
    }
    
    protected function getPrivateKey()
    {
        return openssl_pkey_get_private($this->privateKey);
    }
    
    protected function getPublicKey()
    {
        return openssl_pkey_get_public($this->publicKey);
    }
    
    public function privateEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_private_encrypt($data, $encrypted, self::getPrivateKey()) ? base64_encode($encrypted) : null;
    }
    
    public function publicEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_public_encrypt($data, $encrypted, self::getPublicKey()) ? base64_encode($encrypted) : null;
    }
    
    public function privateDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::getPrivateKey()))
            ? $decrypted : null;
    }
    
    public function publicDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, self::getPublicKey()))
            ? $decrypted : null;
    }
    
    public function makeSign($data)
    {
        if (!is_string($data)) {
            return null;
        }
               $digestAlgo = 'sha512';
        $algo = OPENSSL_ALGO_SHA1;
               $digest = openssl_digest($data, $digestAlgo);
               $signature = '';
               openssl_sign($digest, $signature, self::getPrivateKey(), $algo);
        $signature = base64_encode($signature);
        return $signature;
    }
    
    public function checkSign($data, $signature)
    {
        if (!is_string($data)) {
            return null;
        }
               $digestAlgo = 'sha512';
        $algo = OPENSSL_ALGO_SHA1;
               $digest = openssl_digest($data, $digestAlgo);
               return openssl_verify($digest, base64_decode($signature), self::getPublicKey(), $algo);
    }
}