初始化
This commit is contained in:
112
BooliveMQTT_Auth/Common/BaiduAPI.cs
Normal file
112
BooliveMQTT_Auth/Common/BaiduAPI.cs
Normal file
@@ -0,0 +1,112 @@
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using RestSharp;
|
||||
|
||||
namespace IotManager.Common
|
||||
{
|
||||
public class BaiduAPI
|
||||
{
|
||||
/// <summary>
|
||||
/// 百度api
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetBaiduIp(string ip)
|
||||
{
|
||||
string location = "";
|
||||
try
|
||||
{
|
||||
string url = $"https://sp0.baidu.com";
|
||||
//WebClient client = new WebClient();
|
||||
RestSharp.RestClient client1 = new RestSharp.RestClient(url);
|
||||
RestSharp.RestRequest request = new RestSharp.RestRequest($"/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={ip}&co=&resource_id=6006&oe=utf8", Method.Get);
|
||||
var buffer = client1.DownloadData(request);
|
||||
//var buffer = client.DownloadData(url);
|
||||
string jsonText = Encoding.UTF8.GetString(buffer);
|
||||
JObject jo = JObject.Parse(jsonText);
|
||||
|
||||
Root root = JsonConvert.DeserializeObject<Root>(jo.ToString());
|
||||
foreach (var item in root.data)
|
||||
{
|
||||
location = item.location;
|
||||
}
|
||||
return location;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//Console.WriteLine(ex);
|
||||
return location;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public class Root
|
||||
{
|
||||
public List<DataItem> data { get; set; }
|
||||
}
|
||||
public class DataItem
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string ExtendedLocation { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string OriginQuery { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string appinfo { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int disp_type { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string fetchkey { get; set; }
|
||||
/// <summary>
|
||||
/// 本地局域网
|
||||
/// </summary>
|
||||
public string location { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string origip { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string origipquery { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string resourceid { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int role_id { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int shareImage { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public int showLikeShare { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string showlamp { get; set; }
|
||||
/// <summary>
|
||||
/// IP地址查询
|
||||
/// </summary>
|
||||
public string titlecont { get; set; }
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public string tplt { get; set; }
|
||||
}
|
||||
}
|
||||
134
BooliveMQTT_Auth/Common/Base64.cs
Normal file
134
BooliveMQTT_Auth/Common/Base64.cs
Normal file
@@ -0,0 +1,134 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace IotManager.Common
|
||||
{
|
||||
public class Base64
|
||||
{
|
||||
public static void MainTest()
|
||||
{
|
||||
// 要加密的原始字符串
|
||||
string originalText = "Hello, World!";
|
||||
|
||||
// 加密成Base64字符串
|
||||
string base64EncodedText = EncodeBase64(originalText);
|
||||
Console.WriteLine("Base64 编码结果: " + base64EncodedText);
|
||||
|
||||
// 解密Base64字符串
|
||||
string decodedText = DecodeBase64(base64EncodedText);
|
||||
Console.WriteLine("Base64 解码结果: " + decodedText);
|
||||
}
|
||||
|
||||
// 使用Base64编码字符串
|
||||
public static string EncodeBase64(string text)
|
||||
{
|
||||
byte[] bytesToEncode = Encoding.UTF8.GetBytes(text);
|
||||
string encodedText = Convert.ToBase64String(bytesToEncode);
|
||||
return encodedText;
|
||||
}
|
||||
|
||||
// 使用Base64解码字符串
|
||||
public static string DecodeBase64(string encodedText)
|
||||
{
|
||||
byte[] decodedBytes = Convert.FromBase64String(encodedText);
|
||||
string decodedText = Encoding.UTF8.GetString(decodedBytes);
|
||||
return decodedText;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 使用3DES-MAC签名消息
|
||||
public static string Sign3DESMAC(string key, string message)
|
||||
{
|
||||
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
|
||||
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
|
||||
|
||||
using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
|
||||
{
|
||||
des.Key = keyBytes;
|
||||
des.Mode = CipherMode.ECB; // 3DES-MAC通常使用ECB模式
|
||||
des.Padding = PaddingMode.PKCS7; // PKCS7填充
|
||||
|
||||
using (HMACMD5 hmac = new HMACMD5(des.Key))
|
||||
{
|
||||
byte[] hashBytes = hmac.ComputeHash(messageBytes);
|
||||
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 验证3DES-MAC签名
|
||||
public static bool Verify3DESMAC(string key, string message, string macToVerify)
|
||||
{
|
||||
string calculatedMAC = Sign3DESMAC(key, message);
|
||||
return string.Equals(calculatedMAC, macToVerify, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 取前16个字节
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
public static byte[] ComputeHMACSHA256Short(string message, string key)
|
||||
{
|
||||
using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
|
||||
{
|
||||
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
|
||||
byte[] fullHash = hmac.ComputeHash(messageBytes);
|
||||
|
||||
// 对完整哈希再做一次SHA256并取前16字节
|
||||
using (SHA256 sha = SHA256.Create())
|
||||
{
|
||||
byte[] rehashed = sha.ComputeHash(fullHash);
|
||||
byte[] result = new byte[16];
|
||||
Array.Copy(rehashed, result, 16);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] ComputeHMACSHA256(string message, string key)
|
||||
{
|
||||
using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
|
||||
{
|
||||
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
|
||||
return hmac.ComputeHash(messageBytes);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static bool VerifyHMACSHA256(byte[] message, byte[] key, byte[] expectedMac)
|
||||
{
|
||||
using (HMACSHA256 hmac = new HMACSHA256(key))
|
||||
{
|
||||
byte[] computedMac = hmac.ComputeHash(message);
|
||||
return CryptographicOperations.FixedTimeEquals(computedMac, expectedMac); // 防止时间攻击
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void Test()
|
||||
{
|
||||
string key = "ThisIsASecretKey"; // 密钥长度必须是24字节(192位)
|
||||
string message = "Hello, World!";
|
||||
|
||||
// 使用3DES-MAC签名消息
|
||||
string mac = Sign3DESMAC(key, message);
|
||||
Console.WriteLine("3DES-MAC 签名: " + mac);
|
||||
|
||||
// 验证3DES-MAC签名
|
||||
bool isVerified = Verify3DESMAC(key, message, mac);
|
||||
if (isVerified)
|
||||
{
|
||||
Console.WriteLine("消息验证成功!");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("消息验证失败!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
211
BooliveMQTT_Auth/Common/Crypto.cs
Normal file
211
BooliveMQTT_Auth/Common/Crypto.cs
Normal file
@@ -0,0 +1,211 @@
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
|
||||
|
||||
namespace CryptoHelper;
|
||||
|
||||
/// <summary>
|
||||
/// Provides helper methods for hashing/salting and verifying passwords.
|
||||
/// </summary>
|
||||
public static class Crypto
|
||||
{
|
||||
/* =======================
|
||||
* HASHED PASSWORD FORMATS
|
||||
* =======================
|
||||
*
|
||||
* Version 3:
|
||||
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 600.000 iterations.
|
||||
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
|
||||
* (All UInt32s are stored big-endian.)
|
||||
*/
|
||||
|
||||
private const int PBKDF2IterCount = 600_000;
|
||||
private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
|
||||
private const int SaltSize = 128 / 8; // 128 bits
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Returns a hashed representation of the specified <paramref name="password"/>.
|
||||
/// </summary>
|
||||
/// <param name="password">The password to generate a hash value for.</param>
|
||||
/// <returns>The hash value for <paramref name="password" /> as a base-64-encoded string.</returns>
|
||||
/// <exception cref="System.ArgumentNullException"><paramref name="password" /> is null.</exception>
|
||||
public static string HashPassword(string password)
|
||||
{
|
||||
if (password == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(password));
|
||||
}
|
||||
|
||||
return HashPasswordInternal(password);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the specified RFC 2898 hash and password are a cryptographic match.
|
||||
/// </summary>
|
||||
/// <param name="hashedPassword">The previously-computed RFC 2898 hash value as a base-64-encoded string.</param>
|
||||
/// <param name="password">The plaintext password to cryptographically compare with hashedPassword.</param>
|
||||
/// <returns>true if the hash value is a cryptographic match for the password; otherwise, false.</returns>
|
||||
/// <remarks>
|
||||
/// <paramref name="hashedPassword" /> must be of the format of HashPassword (salt + Hash(salt+input).
|
||||
/// </remarks>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// <paramref name="hashedPassword" /> or <paramref name="password" /> is null.
|
||||
/// </exception>
|
||||
public static bool VerifyHashedPassword(string hashedPassword, string password)
|
||||
{
|
||||
if (hashedPassword == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(hashedPassword));
|
||||
}
|
||||
if (password == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(password));
|
||||
}
|
||||
|
||||
return VerifyHashedPasswordInternal(hashedPassword, password);
|
||||
}
|
||||
|
||||
private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
|
||||
|
||||
private static string HashPasswordInternal(string password)
|
||||
{
|
||||
var bytes = HashPasswordInternal(password, KeyDerivationPrf.HMACSHA256, PBKDF2IterCount, SaltSize, PBKDF2SubkeyLength);
|
||||
return Convert.ToBase64String(bytes);
|
||||
}
|
||||
|
||||
private static byte[] HashPasswordInternal(
|
||||
string password,
|
||||
KeyDerivationPrf prf,
|
||||
int iterCount,
|
||||
int saltSize,
|
||||
int numBytesRequested)
|
||||
{
|
||||
// Produce a version 3 (see comment above) text hash.
|
||||
var salt = new byte[saltSize];
|
||||
_rng.GetBytes(salt);
|
||||
var subkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, numBytesRequested);
|
||||
|
||||
var outputBytes = new byte[13 + salt.Length + subkey.Length];
|
||||
|
||||
// Write format marker.
|
||||
outputBytes[0] = 0x01;
|
||||
|
||||
// Write hashing algorithm version.
|
||||
WriteNetworkByteOrder(outputBytes, 1, (uint)prf);
|
||||
|
||||
// Write iteration count of the algorithm.
|
||||
WriteNetworkByteOrder(outputBytes, 5, (uint)iterCount);
|
||||
|
||||
// Write size of the salt.
|
||||
WriteNetworkByteOrder(outputBytes, 9, (uint)saltSize);
|
||||
|
||||
// Write the salt.
|
||||
Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length);
|
||||
|
||||
// Write the subkey.
|
||||
Buffer.BlockCopy(subkey, 0, outputBytes, 13 + saltSize, subkey.Length);
|
||||
return outputBytes;
|
||||
}
|
||||
|
||||
private static bool VerifyHashedPasswordInternal(string hashedPassword, string password)
|
||||
{
|
||||
var decodedHashedPassword = Convert.FromBase64String(hashedPassword);
|
||||
|
||||
if (decodedHashedPassword.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Verify hashing format.
|
||||
if (decodedHashedPassword[0] != 0x01)
|
||||
{
|
||||
// Unknown format header.
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read hashing algorithm version.
|
||||
var prf = (KeyDerivationPrf)ReadNetworkByteOrder(decodedHashedPassword, 1);
|
||||
|
||||
// Read iteration count of the algorithm.
|
||||
var iterCount = (int)ReadNetworkByteOrder(decodedHashedPassword, 5);
|
||||
|
||||
// Read size of the salt.
|
||||
var saltLength = (int)ReadNetworkByteOrder(decodedHashedPassword, 9);
|
||||
|
||||
// Verify the salt size: >= 128 bits.
|
||||
if (saltLength < 128 / 8)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read the salt.
|
||||
var salt = new byte[saltLength];
|
||||
Buffer.BlockCopy(decodedHashedPassword, 13, salt, 0, salt.Length);
|
||||
|
||||
// Verify the subkey length >= 128 bits.
|
||||
var subkeyLength = decodedHashedPassword.Length - 13 - salt.Length;
|
||||
if (subkeyLength < 128 / 8)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Read the subkey.
|
||||
var expectedSubkey = new byte[subkeyLength];
|
||||
Buffer.BlockCopy(decodedHashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length);
|
||||
|
||||
// Hash the given password and verify it against the expected subkey.
|
||||
var actualSubkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, subkeyLength);
|
||||
return ByteArraysEqual(actualSubkey, expectedSubkey);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// This should never occur except in the case of a malformed payload, where
|
||||
// we might go off the end of the array. Regardless, a malformed payload
|
||||
// implies verification failed.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static uint ReadNetworkByteOrder(byte[] buffer, int offset)
|
||||
{
|
||||
return ((uint)(buffer[offset + 0]) << 24)
|
||||
| ((uint)(buffer[offset + 1]) << 16)
|
||||
| ((uint)(buffer[offset + 2]) << 8)
|
||||
| ((uint)(buffer[offset + 3]));
|
||||
}
|
||||
|
||||
private static void WriteNetworkByteOrder(byte[] buffer, int offset, uint value)
|
||||
{
|
||||
buffer[offset + 0] = (byte)(value >> 24);
|
||||
buffer[offset + 1] = (byte)(value >> 16);
|
||||
buffer[offset + 2] = (byte)(value >> 8);
|
||||
buffer[offset + 3] = (byte)(value >> 0);
|
||||
}
|
||||
|
||||
// Compares two byte arrays for equality.
|
||||
// The method is specifically written so that the loop is not optimized.
|
||||
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
|
||||
private static bool ByteArraysEqual(byte[] a, byte[] b)
|
||||
{
|
||||
if (ReferenceEquals(a, b))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (a == null || b == null || a.Length != b.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var areSame = true;
|
||||
for (var i = 0; i < a.Length; i++)
|
||||
{
|
||||
areSame &= (a[i] == b[i]);
|
||||
}
|
||||
return areSame;
|
||||
}
|
||||
}
|
||||
192
BooliveMQTT_Auth/Common/ExcelHelper.cs
Normal file
192
BooliveMQTT_Auth/Common/ExcelHelper.cs
Normal file
@@ -0,0 +1,192 @@
|
||||
using System.Data;
|
||||
using NPOI.HSSF.UserModel;
|
||||
using NPOI.SS.UserModel;
|
||||
using NPOI.XSSF.UserModel;
|
||||
|
||||
namespace IotManager.Common
|
||||
{
|
||||
public class ExcelHelper
|
||||
{
|
||||
public static DataTable ReadExcelToDataTable(string filePath)
|
||||
{
|
||||
DataTable dataTable = new DataTable();
|
||||
|
||||
// 打开 Excel 文件
|
||||
IWorkbook workbook;
|
||||
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
|
||||
{
|
||||
if (filePath.EndsWith(".xlsx"))
|
||||
workbook = new XSSFWorkbook(fileStream); // 读取 .xlsx 文件
|
||||
else if (filePath.EndsWith(".xls"))
|
||||
workbook = new HSSFWorkbook(fileStream); // 读取 .xls 文件
|
||||
else
|
||||
throw new Exception("文件格式不支持,只支持 .xls 和 .xlsx");
|
||||
}
|
||||
|
||||
// 读取第一个工作表
|
||||
var sheet = workbook.GetSheetAt(0);
|
||||
if (sheet == null)
|
||||
throw new Exception("工作表为空!");
|
||||
|
||||
// 获取表头
|
||||
var headerRow = sheet.GetRow(0);
|
||||
if (headerRow == null)
|
||||
throw new Exception("未找到表头行!");
|
||||
|
||||
for (int i = 0; i < headerRow.LastCellNum; i++)
|
||||
{
|
||||
var columnName = headerRow.GetCell(i)?.ToString() ?? $"Column{i}";
|
||||
dataTable.Columns.Add(columnName);
|
||||
}
|
||||
|
||||
// 读取数据行
|
||||
for (int i = 1; i <= sheet.LastRowNum; i++) // 从第 1 行(索引为 1)开始读取
|
||||
{
|
||||
var row = sheet.GetRow(i);
|
||||
if (row == null) continue;
|
||||
|
||||
var dataRow = dataTable.NewRow();
|
||||
for (int j = 0; j < row.LastCellNum; j++)
|
||||
{
|
||||
var cell = row.GetCell(j);
|
||||
dataRow[j] = cell != null ? GetCellValue(cell) : DBNull.Value;
|
||||
}
|
||||
dataTable.Rows.Add(dataRow);
|
||||
}
|
||||
|
||||
return dataTable;
|
||||
}
|
||||
|
||||
static object GetCellValue(ICell cell)
|
||||
{
|
||||
switch (cell.CellType)
|
||||
{
|
||||
case CellType.Numeric:
|
||||
return DateUtil.IsCellDateFormatted(cell) ? cell.DateCellValue : cell.NumericCellValue;
|
||||
case CellType.String:
|
||||
return cell.StringCellValue;
|
||||
case CellType.Boolean:
|
||||
return cell.BooleanCellValue;
|
||||
case CellType.Formula:
|
||||
return cell.CellFormula;
|
||||
case CellType.Blank:
|
||||
return string.Empty;
|
||||
default:
|
||||
return cell.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void CreateNewExcel(string filePath, DataTable dataTable)
|
||||
{
|
||||
IWorkbook workbook;
|
||||
if (filePath.EndsWith(".xlsx"))
|
||||
workbook = new XSSFWorkbook(); // 创建 .xlsx 文件
|
||||
else
|
||||
workbook = new HSSFWorkbook(); // 创建 .xls 文件
|
||||
|
||||
var sheet = workbook.CreateSheet("Sheet1");
|
||||
|
||||
// 写入表头
|
||||
var headerRow = sheet.CreateRow(0);
|
||||
for (int i = 0; i < dataTable.Columns.Count; i++)
|
||||
{
|
||||
headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
|
||||
}
|
||||
|
||||
// 写入数据
|
||||
for (int i = 0; i < dataTable.Rows.Count; i++)
|
||||
{
|
||||
var dataRow = sheet.CreateRow(i + 1);
|
||||
for (int j = 0; j < dataTable.Columns.Count; j++)
|
||||
{
|
||||
dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());
|
||||
}
|
||||
}
|
||||
|
||||
// 保存文件
|
||||
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
|
||||
{
|
||||
workbook.Write(stream);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void SetColumnWidthAndRowHeight(IWorkbook workbook, int sheetIndex, int columnIndex, int rowIndex)
|
||||
{
|
||||
var sheet = workbook.GetSheetAt(sheetIndex);
|
||||
|
||||
// 设置列宽(单位是 1/256 字符宽度)
|
||||
sheet.SetColumnWidth(columnIndex, 20 * 256); // 设置第 1 列宽度为 20
|
||||
|
||||
// 设置行高(单位是点数)
|
||||
var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
|
||||
row.HeightInPoints = 25; // 设置行高为 25 点
|
||||
}
|
||||
|
||||
public void SetCellStyle(IWorkbook workbook, int sheetIndex, int rowIndex, int colIndex)
|
||||
{
|
||||
var sheet = workbook.GetSheetAt(sheetIndex);
|
||||
var cell = sheet.GetRow(rowIndex).GetCell(colIndex) ?? sheet.GetRow(rowIndex).CreateCell(colIndex);
|
||||
|
||||
var style = workbook.CreateCellStyle();
|
||||
|
||||
// 设置字体
|
||||
var font = workbook.CreateFont();
|
||||
font.FontHeightInPoints = 12;
|
||||
font.FontName = "Arial";
|
||||
font.IsBold = true;
|
||||
style.SetFont(font);
|
||||
|
||||
// 设置边框
|
||||
style.BorderBottom = BorderStyle.Thin;
|
||||
style.BorderLeft = BorderStyle.Thin;
|
||||
style.BorderRight = BorderStyle.Thin;
|
||||
style.BorderTop = BorderStyle.Thin;
|
||||
|
||||
// 设置背景颜色
|
||||
style.FillForegroundColor = IndexedColors.LightBlue.Index;
|
||||
style.FillPattern = FillPattern.SolidForeground;
|
||||
|
||||
cell.CellStyle = style;
|
||||
cell.SetCellValue("示例文本");
|
||||
}
|
||||
public void FullExample(string filePath, DataTable dataTable)
|
||||
{
|
||||
IWorkbook workbook = filePath.EndsWith(".xlsx") ? (IWorkbook)new XSSFWorkbook() : new HSSFWorkbook();
|
||||
var sheet = workbook.CreateSheet("Sheet1");
|
||||
|
||||
// 设置表头
|
||||
var headerRow = sheet.CreateRow(0);
|
||||
for (int i = 0; i < dataTable.Columns.Count; i++)
|
||||
{
|
||||
headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
|
||||
}
|
||||
|
||||
// 写入数据
|
||||
for (int i = 0; i < dataTable.Rows.Count; i++)
|
||||
{
|
||||
var dataRow = sheet.CreateRow(i + 1);
|
||||
for (int j = 0; j < dataTable.Columns.Count; j++)
|
||||
{
|
||||
dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());
|
||||
}
|
||||
}
|
||||
|
||||
// 设置列宽和行高
|
||||
SetColumnWidthAndRowHeight(workbook, 0, 1, 1);
|
||||
|
||||
|
||||
// 设置单元格样式
|
||||
SetCellStyle(workbook, 0, 1, 1);
|
||||
|
||||
// 保存文件
|
||||
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
|
||||
{
|
||||
workbook.Write(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
25
BooliveMQTT_Auth/Common/HttpRequest.cs
Normal file
25
BooliveMQTT_Auth/Common/HttpRequest.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
using RestSharp;
|
||||
|
||||
namespace IotManager.Common
|
||||
{
|
||||
public class HttpRequest
|
||||
{
|
||||
public static string BaseUrl = "";
|
||||
public bool SendHttpRequest(string Url,List<string> paramlist)
|
||||
{
|
||||
var options = new RestClientOptions(BaseUrl);
|
||||
var client = new RestClient(options);
|
||||
|
||||
var request = new RestRequest("api/login/Helloooo");
|
||||
request.AddParameter("key", "j76R2968V^aw%2;2");
|
||||
|
||||
RestResponse response = client.ExecutePost(request);
|
||||
string? allow_or_deny = response.Content;
|
||||
if (allow_or_deny.Equals("allow"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
44
BooliveMQTT_Auth/Common/IdGenerate.cs
Normal file
44
BooliveMQTT_Auth/Common/IdGenerate.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using Sqids;
|
||||
|
||||
namespace IotManager.Common
|
||||
{
|
||||
public class IdGenerate
|
||||
{
|
||||
public void AAA()
|
||||
{
|
||||
// 使用默认选项创建 SqidsEncoder 实例
|
||||
var sqids = new SqidsEncoder<int>();
|
||||
|
||||
// 编码单个数字
|
||||
var id = sqids.Encode(99);
|
||||
Console.WriteLine($"编码单个数字: {id}"); // 输出:Q8P
|
||||
|
||||
// 解码单个 ID
|
||||
var number = sqids.Decode(id).Single();
|
||||
Console.WriteLine($"解码单个 ID '{id}': {number}"); // 输出:99
|
||||
|
||||
// 编码多个数字
|
||||
var ids = sqids.Encode(7, 8, 9);
|
||||
Console.WriteLine($"编码多个数字 7, 8, 9: {ids}"); // 输出:ylrR3H
|
||||
|
||||
// 解码多个 ID
|
||||
var numbers = sqids.Decode(ids);
|
||||
Console.WriteLine($"解码多个 ID '{ids}': {string.Join(", ", numbers)}"); // 输出:7, 8, 9
|
||||
|
||||
// 使用自定义选项创建 SqidsEncoder 实例
|
||||
var customSqids = new SqidsEncoder<int>(new SqidsOptions
|
||||
{
|
||||
Alphabet = "mTHivO7hx3RAbr1f586SwjNnK2lgpcUVuG09BCtekZdJ4DYFPaWoMLQEsXIqyz",//自定义字母表(注意:字母表至少需要 3 个字符)
|
||||
MinLength = 5,//最小长度,默认情况下,Sqids 使用尽可能少的字符来编码给定的数字。但是,如果你想让你的所有 ID 至少达到一定的长度(例如,为了美观),你可以通过 MinLength 选项进行配置:
|
||||
BlockList = { "whatever", "else", "you", "want" } //自定义黑名单,Sqids 自带一个大的默认黑名单,这将确保常见的诅咒词等永远不会出现在您的 ID 中。您可以像这样向这个默认黑名单添加额外项:
|
||||
});
|
||||
|
||||
// 使用自定义 SqidsEncoder 编码和解码
|
||||
var customId = customSqids.Encode(8899);
|
||||
Console.WriteLine($"使用自定义 SqidsEncoder 编码: {customId}"); // 输出:i1uYg
|
||||
|
||||
var customNumber = customSqids.Decode(customId).Single();
|
||||
Console.WriteLine($"使用自定义 SqidsEncoder 解码: {customNumber}"); // 输出:8899
|
||||
}
|
||||
}
|
||||
}
|
||||
75
BooliveMQTT_Auth/Common/JiaJieMi.cs
Normal file
75
BooliveMQTT_Auth/Common/JiaJieMi.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace IotManager.Common
|
||||
{
|
||||
public class JiaJieMi
|
||||
{
|
||||
private static byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };
|
||||
|
||||
public static string encryptKey = "20su#pe1r%boolive";
|
||||
/// <summary>
|
||||
/// DES加密字符串
|
||||
/// </summary>
|
||||
/// <param name="encryptString">待加密的字符串</param>
|
||||
/// <param name="encryptKey">加密密钥,要求为8位</param>
|
||||
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
|
||||
public static string EncryptString(string encryptString)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
|
||||
byte[] rgbIV = Keys;
|
||||
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
|
||||
var dCSP = new DESCryptoServiceProvider();
|
||||
using MemoryStream mStream = new MemoryStream();
|
||||
using CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
|
||||
cStream.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cStream.FlushFinalBlock();
|
||||
return Convert.ToBase64String(mStream.ToArray());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return encryptString;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DES解密字符串
|
||||
/// </summary>
|
||||
/// <param name="decryptString">待解密的字符串</param>
|
||||
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
|
||||
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
|
||||
public static string DecryptString(string decryptString)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
|
||||
byte[] rgbIV = Keys;
|
||||
byte[] inputByteArray = Convert.FromBase64String(decryptString);
|
||||
var DCSP = new DESCryptoServiceProvider();
|
||||
using MemoryStream mStream = new MemoryStream();
|
||||
using CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
|
||||
cStream.Write(inputByteArray, 0, inputByteArray.Length);
|
||||
cStream.FlushFinalBlock();
|
||||
return Encoding.UTF8.GetString(mStream.ToArray());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return decryptString;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static string HashPassword(string pwd)
|
||||
{
|
||||
string v = CryptoHelper.Crypto.HashPassword(pwd);
|
||||
return v;
|
||||
}
|
||||
public static bool VerifyHashedPassword(string encrypwd, string original_pwd)
|
||||
{
|
||||
bool v = CryptoHelper.Crypto.VerifyHashedPassword(encrypwd, original_pwd);
|
||||
return v;
|
||||
}
|
||||
}
|
||||
}
|
||||
29
BooliveMQTT_Auth/Common/MsgSend.cs
Normal file
29
BooliveMQTT_Auth/Common/MsgSend.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using RestSharp;
|
||||
|
||||
namespace IotManager.Common
|
||||
{
|
||||
public class MsgSend
|
||||
{
|
||||
public static string BaseUrl = "http://blv-rd.tech:19041";
|
||||
public static async Task SendMsg(MsgData data)
|
||||
{
|
||||
var options = new RestClientOptions(BaseUrl);
|
||||
var client = new RestClient(options);
|
||||
|
||||
var request = new RestRequest("/api/CallAndMsg/SendToPhone");
|
||||
request.AddBody(data, ContentType.Json);
|
||||
|
||||
RestResponse response = await client.ExecuteAsync(request, Method.Post);
|
||||
string? allow_or_deny = response.Content;
|
||||
}
|
||||
}
|
||||
public class MsgData
|
||||
{
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? CallerName { get; set; }
|
||||
public string? Content { get; set; }
|
||||
public string? StartingPoint { get; set; }
|
||||
public string? DeadLine { get; set; }
|
||||
public string? Type { get; set; }
|
||||
}
|
||||
}
|
||||
13
BooliveMQTT_Auth/Common/MyMemoryCache.cs
Normal file
13
BooliveMQTT_Auth/Common/MyMemoryCache.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
|
||||
namespace BLW_Log.Models
|
||||
{
|
||||
public class MyMemoryCache
|
||||
{
|
||||
public MemoryCache Cache { get; } = new MemoryCache(
|
||||
new MemoryCacheOptions
|
||||
{
|
||||
SizeLimit = 1024
|
||||
});
|
||||
}
|
||||
}
|
||||
36
BooliveMQTT_Auth/Common/PasswordGenerator.cs
Normal file
36
BooliveMQTT_Auth/Common/PasswordGenerator.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace IotManager.Common
|
||||
{
|
||||
public class PasswordGenerator
|
||||
{
|
||||
//private const string ValidChars = "!@#$%^&*()-+={}';.?<>:{}|ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
private const string ValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
public static string Generate(int length)
|
||||
{
|
||||
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
|
||||
{
|
||||
char[] chars = new char[length];
|
||||
byte[] values = new byte[length * sizeof(char)];
|
||||
|
||||
rng.GetBytes(values);
|
||||
Buffer.BlockCopy(values, 0, chars, 0, values.Length);
|
||||
|
||||
return new string(chars.Select(c => ValidChars[c % ValidChars.Length]).ToArray());
|
||||
}
|
||||
}
|
||||
public static string GenerateRandomKey(int length)
|
||||
{
|
||||
byte[] key = new byte[length];
|
||||
|
||||
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
|
||||
{
|
||||
rng.GetBytes(key); // 填充随机字节
|
||||
}
|
||||
|
||||
string mykey = Convert.ToBase64String(key);
|
||||
return mykey;
|
||||
}
|
||||
}
|
||||
}
|
||||
28
BooliveMQTT_Auth/Common/StaticData.cs
Normal file
28
BooliveMQTT_Auth/Common/StaticData.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using System.Reflection;
|
||||
using IronPython.Hosting;
|
||||
using Microsoft.Scripting.Hosting;
|
||||
|
||||
namespace IotManager.Common
|
||||
{
|
||||
public class StaticData
|
||||
{
|
||||
public static ScriptEngine eng = Python.CreateEngine();
|
||||
public static ScriptScope scope1 = eng.CreateScope();
|
||||
public static ScriptScope scope2 = eng.CreateScope();
|
||||
public static ScriptScope scope3 = eng.CreateScope();
|
||||
|
||||
public static void GetWebAPIMethod()
|
||||
{
|
||||
eng.Runtime.LoadAssembly(Assembly.GetExecutingAssembly());
|
||||
eng.ExecuteFile("script\\webapi.py", scope1);
|
||||
}
|
||||
public static void GetWebAPIMethod1()
|
||||
{
|
||||
eng.ExecuteFile("script\\CommonData.py", scope2);
|
||||
}
|
||||
public static void GetWebAPIMethod2()
|
||||
{
|
||||
eng.ExecuteFile("script\\b.py", scope1);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user