1. 程式人生 > >php rsa非對稱加密

php rsa非對稱加密

class Rsa {

private static $PRIVATE_KEY = '-----BEGIN RSA PRIVATE KEY-----MIICXgIBAAKBgQCoZZ8iUBprOIc0kGckr5ax6/Fd9IKKMc/XHayKEAvqpS0oz0b1ojEkpkdZBk0OWNhp73YNV+YLKBwwxOwb3u3hl8nBLoG/RilEbBMdCf55cUzNsfn/XF5CiLr/aci/OHuTe6ULvXs280T5M+nUh3iKdiT6z9XrFbH69C+xFoNInwIDAQABAoGAe+ape7msdo+VC5vkCB4ZprePVC3/jmawIfr3ZG4CFpeJ7qjz8O9xcSHXBS2ZrKC6Otex6Idv/213sHpzrt4L7+rSrgMOauWNjSVjr4T4Z168uvsnNocn+3GWfzbBPQj3PhjE64R/MkWDvuq2UK945WYtqFaC6LT1mJAXhjxqpiECQQDYGWYbCsUgQS0LnDzReyotkb9Eyr5UGlI8Nzn3PvwwkIS3N3yUsm2t3UokOw02DlhkC4f1aT097fM1w0FruSNNAkEAx31taitIGwgJg+yPmvwTs8AENm0wxi/V6loEXPBPxX2R4NjSG+ExYzA7/daDq//McKsX0EcYcsFN0E3HwSANmwJBAJUXGOHpUU1Kiihrd25TWissVdjBRATEUB4pP/2738QlwNqjFnmEjLUaak+KyjeUOBl19ywymkUCyPw7pQQMLDUCQQC84DKSDPyuK0PnFjk5QmXdEHZsmaFOY8gjpKrw286La8KMonz8TJCYGvkR8uKkHQMRwcxANLAfJopoKNxyK8j1AkEAwcY3EHeKe4i3FhCjGSqAGAzFFBS1jzTNZxw/cxMMCbfxFH4WvhowqoC1iAKDyZ7HF7V+RcxcfuhoBJi/3+ImEg==-----END RSA PRIVATE KEY-----';    
    private static $PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCoZZ8iUBprOIc0kGckr5ax6/Fd9IKKMc/XHayKEAvqpS0oz0b1ojEkpkdZBk0OWNhp73YNV+YLKBwwxOwb3u3hl8nBLoG/RilEbBMdCf55cUzNsfn/XF5CiLr/aci/OHuTe6ULvXs280T5M+nUh3iKdiT6z9XrFbH69C+xFoNInwIDAQAB-----END PUBLIC KEY-----';   


    /**
     * 獲取私鑰
     * @return bool|resource
     */
    private static function getPrivateKey()
    {
//引入資料夾或直接使用祕鑰key
        $path = "D:\wamp\www\smartSPACE\web\key";
        $privKey = file_get_contents($path.'/rsa_private_key.pem');
//        $privKey = self::$PRIVATE_KEY;
        return openssl_pkey_get_private($privKey);
    }

    /**
     * 獲取公鑰
     * @return bool|resource
     */
    private static function getPublicKey()
    {
        $path = "D:\wamp\www\smartSPACE\web\key";
        $publicKey = file_get_contents($path.'/rsa_public_key.pem');
//        $publicKey = self::$PUBLIC_KEY;
        return openssl_pkey_get_public($publicKey);
    }

    /**
     * 私鑰加密
     * @param string $data
     * @return null|string
     */
    public static function privEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_private_encrypt($data,$encrypted,self::getPrivateKey()) ? base64_encode($encrypted) : null;
    }

    /**
     * 公鑰加密
     * @param string $data
     * @return null|string
     */
    public static function publicEncrypt($data = '')
    {
        if (!is_string($data)) {
            return null;
        }
        return openssl_public_encrypt($data,$encrypted,self::getPublicKey()) ? base64_encode($encrypted) : null;
    }

    /**
     * 私鑰解密
     * @param string $encrypted
     * @return null
     */
    public static function privDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::getPrivateKey())) ? $decrypted : null;
    }

    /**
     * 公鑰解密
     * @param string $encrypted
     * @return null
     */
    public static function publicDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }
        return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, self::getPublicKey())) ? $decrypted : null;
    }
}

上面是類

呼叫

 public function actionRsa()
    {
        $rsa = new \app\services\Rsa();
        $data['mobile'] = '18146721110';
        $data['password'] = '123456';
        $privEncrypt = $rsa->privEncrypt(json_encode($data));
        echo '私鑰加密後:' . $privEncrypt . '<br>';

        $publicDecrypt = $rsa->publicDecrypt($privEncrypt);
        echo '公鑰解密後:' . $publicDecrypt . '<br>';

        $publicEncrypt = $rsa->publicEncrypt(json_encode($data));
        echo '公鑰加密後:' . $publicEncrypt . '<br>';

        $privDecrypt = $rsa->privDecrypt($publicEncrypt);
        echo '私鑰解密後:' . $privDecrypt . '<br>';
        echo '私鑰解密後:' . $privDecrypt . '<br>';

    }

生成公私祕鑰方法不寫了,生成個測試的到這裡http://tools.jb51.net/password/rsa_encode

預處理防範抓包:1.生成隨機串,後臺校驗隨機串出現的次數

                           2. 時間有效期校驗

例子

if ($key != null){
            $rsa = new \app\services\Rsa();
            $publicDecrypt = $rsa->publicDecrypt($key);
            $publicDecrypt = json_decode($publicDecrypt,true);
            $mobile = isset($publicDecrypt['mobile']) ? $publicDecrypt['mobile'] : "";
            $password = isset($publicDecrypt['password']) ? $publicDecrypt['password'] : "";
        }else{
            return $this->returnData('', -1, '手機號和密碼必傳');
        }

        if ( $time != null) {
            $last_time = $time+20;
            if($last_time < $x_time){
                return $this->returnData('', -1, '請求超時');
            }
        } else {
            return $this->returnData('', -1, '請求異常');
        }