$bits, 'private_key_type' => OPENSSL_KEYTYPE_RSA, ]; // 生成密钥对 $resource = openssl_pkey_new($config); if (!$resource) { throw new \Exception('生成密钥对失败: ' . openssl_error_string()); } // 导出私钥 openssl_pkey_export($resource, $privateKey); // 获取公钥 $details = openssl_pkey_get_details($resource); $publicKey = $details['key']; // 转换为BASE64格式(去除PEM头尾) $privateKey = str_replace(['-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----', "\n"], '', $privateKey); $publicKey = str_replace(['-----BEGIN PUBLIC KEY-----', '-----END PUBLIC KEY-----', "\n"], '', $publicKey); return [ 'public_key' => $publicKey, 'private_key' => $privateKey ]; } }