仰望星辰工作室

better-staridc-MNBT

better-staridc-MNBT/ wp_seller_plugin/includes/class-crypto.php 1.6 KB · 73 行 原始文件
Z zfhsh first commit 1 天前
1<?php
2/**
3 * 密钥加解密工具:基于 WordPress 盐派生密钥,AES-256-CBC 加密。
4 *
5 * @package MnbtWp
6 */
7
8namespace MnbtWp;
9
10if ( ! defined( 'ABSPATH' ) ) {
11 exit;
12}
13
14/**
15 * 密钥加解密。
16 */
17class Crypto {
18
19 /**
20 * 派生 32 字节 AES 密钥(基于 wp_salt('auth'),站点级唯一)。
21 *
22 * @return string
23 */
24 private static function key() {
25 return substr( hash( 'sha256', wp_salt( 'auth' ) ), 0, 32 );
26 }
27
28 /**
29 * 加密明文。
30 *
31 * @param string $plain 明文。
32 * @return string 密文(base64),空串原样返回。
33 */
34 public static function encrypt( $plain ) {
35 $plain = (string) $plain;
36 if ( '' === $plain ) {
37 return '';
38 }
39 if ( ! function_exists( 'openssl_encrypt' ) ) {
40 return base64_encode( $plain );
41 }
42 $iv = openssl_random_pseudo_bytes( 16 );
43 $cipher = openssl_encrypt( $plain, 'AES-256-CBC', self::key(), 0, $iv );
44 if ( false === $cipher ) {
45 return '';
46 }
47 return base64_encode( $iv . $cipher );
48 }
49
50 /**
51 * 解密密文。
52 *
53 * @param string $enc 密文(base64)。
54 * @return string 明文,失败返回空串。
55 */
56 public static function decrypt( $enc ) {
57 $enc = (string) $enc;
58 if ( '' === $enc ) {
59 return '';
60 }
61 $raw = base64_decode( $enc, true );
62 if ( false === $raw || strlen( $raw ) < 16 ) {
63 return '';
64 }
65 $iv = substr( $raw, 0, 16 );
66 $cipher = substr( $raw, 16 );
67 if ( ! function_exists( 'openssl_decrypt' ) ) {
68 return '';
69 }
70 $plain = openssl_decrypt( $cipher, 'AES-256-CBC', self::key(), 0, $iv );
71 return ( false === $plain ) ? '' : $plain;
72 }
73}