初始化

This commit is contained in:
2025-11-20 09:14:00 +08:00
commit 611f7cbaf5
98 changed files with 15987 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ViewModels.Common
{
public class CacheKey
{
public static string RoomIP_Port_Prefix = "Log_IP_Port";
public static string Key = "monitor_host";
public static string MonitorLogPrefix = "AllLogKey";
}
}

211
ViewModels/Common/Crypto.cs Normal file
View 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;
}
}

117
ViewModels/Common/Tools.cs Normal file
View File

@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ViewModels
{
public class Tools
{
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;
}
/// <summary>
/// 时间戳转本地时间-时间戳精确到秒
/// </summary>
public static DateTime ToLocalTimeDateBySeconds(long unix)
{
var dto = DateTimeOffset.FromUnixTimeSeconds(unix);
return dto.ToLocalTime().DateTime;
}
/// <summary>
/// 时间转时间戳Unix-时间戳精确到秒
/// </summary>
public static long ToUnixTimestampBySeconds(DateTime dt)
{
DateTimeOffset dto = new DateTimeOffset(dt);
return dto.ToUnixTimeSeconds();
}
/// <summary>
/// 时间戳转本地时间-时间戳精确到毫秒
/// </summary>
public static DateTime ToLocalTimeDateByMilliseconds(long unix)
{
var dto = DateTimeOffset.FromUnixTimeMilliseconds(unix);
return dto.ToLocalTime().DateTime;
}
/// <summary>
/// 时间转时间戳Unix-时间戳精确到毫秒
/// </summary>
public static long ToUnixTimestampByMilliseconds(DateTime dt)
{
DateTimeOffset dto = new DateTimeOffset(dt);
return dto.ToUnixTimeMilliseconds();
}
}
}