server/app/Kernel/Str.php

133 lines
3.3 KiB
PHP

<?php
/**
* Author: cfn <cfn@leapy.cn>
*/
namespace App\Kernel;
use Hyperf\HttpServer\Contract\RequestInterface;
use function Hyperf\Config\config;
class Str
{
/**
* 获取UUID
* @param string $prefix
* @return string
*/
static function uuid(string $prefix = ''): string
{
$chars = md5(uniqid(mt_rand(), true));
$uuid = substr($chars, 0, 8) . '-';
$uuid .= substr($chars, 8, 4) . '-';
$uuid .= substr($chars, 12, 4) . '-';
$uuid .= substr($chars, 16, 4) . '-';
$uuid .= substr($chars, 20, 12);
return $prefix . $uuid;
}
/**
* 公钥加密
* Author: cfn <cfn@leapy.cn>
* @param $data
* @return string
*/
public static function public_encrypt($data)
{
$pubKey = "-----BEGIN PUBLIC KEY-----\n" .
wordwrap(config("app.public"), 64, "\n", true) .
"\n-----END PUBLIC KEY-----";
openssl_public_encrypt($data, $encrypted, $pubKey);
return base64_encode($encrypted);
}
/**
* 私钥解密
* Author: cfn <cfn@leapy.cn>
* @param $data
* @return string
*/
public static function private_decrypt($data)
{
$priKey = "-----BEGIN PRIVATE KEY-----\n" .
wordwrap(config("app.private"), 64, "\n", true) .
"\n-----END PRIVATE KEY-----";
openssl_private_decrypt(base64_decode($data), $decrypted, $priKey);
return $decrypted;
}
/**
* 加密
* Author: cfn <cfn@leapy.cn>
* @param $data
* @return string
*/
public static function encrypt($data)
{
return base64_encode(openssl_encrypt($data,"DES-ECB",config("app.key")));
}
/**
* 解密
* Author: cfn <cfn@leapy.cn>
* @param $data
* @return false|string
*/
public static function decrypt($data)
{
return openssl_decrypt(base64_decode($data),"DES-ECB",config("app.key"));
}
/**
* 获取随机字符串
* @param int $num
* @param string $prefix
* @return string
*/
static function randStr(int $num, string $prefix = ""): string
{
$str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$_str = "";
while ($num > 0) {
$_str .= substr($str, rand(0, strlen($str) - 1), 1);
$num--;
}
return $prefix . $_str;
}
/**
* @param int $num
* @param string $prefix
* @return string
*/
static function randInt(int $num, string $prefix = ""): string
{
$str = "1234567890";
$_str = "";
while ($num > 0) {
$_str .= substr($str, rand(0, strlen($str) - 1), 1);
$num--;
}
return $prefix . $_str;
}
/**
* 返回ip
* @param RequestInterface $request
* @return string
*/
static function ip(RequestInterface $request): string
{
$res = $request->getHeaders();
if (isset($res['http_client_ip'])) {
return $res['http_client_ip'][0];
} elseif (isset($res['x-real-ip'])) {
return $res['x-real-ip'][0];
} elseif (isset($res['x-forwarded-for'])) {
return $res['x-forwarded-for'][0];
} else {
$serverParams = $request->getServerParams();
return $serverParams['remote_addr'][0];
}
}
}