Skip to content

Commit c8552be

Browse files
authored
Update RSA.php
1 parent 057ef70 commit c8552be

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

src/Utils/RSA.php

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,57 @@ public static function generate($config = [])
2121
'privateKey' => $privateKey,
2222
];
2323
}
24+
25+
public static function normalPublicKey($publicKey)
26+
{
27+
$fKey = "-----BEGIN PUBLIC KEY-----\n";
28+
$len = strlen($publicKey);
29+
for($i = 0; $i < $len; ) {
30+
$fKey = $fKey . substr($publicKey, $i, 64) . "\n";
31+
$i += 64;
32+
}
33+
$fKey .= "-----END PUBLIC KEY-----";
34+
return $fKey;
35+
}
36+
37+
public static function normalPrivateKey($privateKey)
38+
{
39+
$fKey = "-----BEGIN PRIVATE KEY-----\n";
40+
$len = strlen($privateKey);
41+
for($i = 0; $i < $len; ) {
42+
$fKey = $fKey . substr($privateKey, $i, 64) . "\n";
43+
$i += 64;
44+
}
45+
$fKey .= "-----END PRIVATE KEY-----";
46+
return $fKey;
47+
}
48+
49+
public static function encrypt($data, $privateKey)
50+
{
51+
// $privateKey = RSA::normalPrivateKey($privateKey); // 格式化私钥为标准的 private key
52+
53+
$res = openssl_private_encrypt($data, $encrypted, $privateKey);
54+
55+
if(!$res) {
56+
return false;
57+
}
58+
59+
return Str::stringToHex($encrypted);
60+
}
61+
62+
public function decrypt($data, $publicKey)
63+
{
64+
// $publicKey = RSA::normalPublicKey($publicKey); // 格式化公钥为标准的 public key
65+
66+
// $openssl_pub = openssl_pkey_get_public($publicKey); // 不知道作用,未使用
67+
68+
// 验签
69+
$resArr = openssl_public_decrypt(Str::hexToString($data), $decrypted, $publicKey);
70+
71+
if(!$resArr){
72+
return false;
73+
}
74+
75+
return $decrypted;
76+
}
2477
}

0 commit comments

Comments
 (0)