[HttpGet(Name = "GetEncryptStr")]
private string GetEncryptStr(bool test, string algorithm = "MD5")
{
long timestamp = EncoderHandler.ToUnixTimeMilliseconds();
string username = "ERPUser";
string password = "0*ERP@User";
JObject jsonObject = new JObject();
jsonObject["username"] = EncoderHandler.Encode(algorithm, username + timestamp);
jsonObject["password"] = EncoderHandler.Encode(algorithm, password + timestamp);
jsonObject["timestamp"] = timestamp + "";
return JsonConvert.SerializeObject(jsonObject);
}
using System.Security.Cryptography;
using System.Text;
namespace ERPApi.Util
{
public class EncoderHandler
{
private static readonly char[] HEX_DIGITS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public EncoderHandler()
{
}
public static string Encode(string algorithm, string str)
{
if (str == null)
{
return null;
}
try
{
using (HashAlgorithm hashAlgorithm = GetHashAlgorithm(algorithm))
{
if (hashAlgorithm == null)
{
throw new ArgumentException("Unsupported algorithm: " + algorithm);
}
byte[] bytes = Encoding.UTF8.GetBytes(str);
byte[] hash = hashAlgorithm.ComputeHash(bytes);
return GetFormattedText(hash);
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error in Encode: {ex.Message}");
return null;
}
}
private static HashAlgorithm GetHashAlgorithm(string algorithm)
{
switch (algorithm.ToUpper())
{
case "MD5":
return MD5.Create();
case "SHA1":
return SHA1.Create();
case "SHA256":
return SHA256.Create();
case "SHA384":
return SHA384.Create();
case "SHA512":
return SHA512.Create();
default:
throw new ArgumentException($"Unsupported algorithm: {algorithm}");
}
}
private static string GetFormattedText(byte[] bytes)
{
int len = bytes.Length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++)
{
buf.Append(HEX_DIGITS[bytes[j] >> 4 & 0x0F]);
buf.Append(HEX_DIGITS[bytes[j] & 0x0F]);
}
return buf.ToString();
}
/// <summary>
/// 获取当前时间戳
/// </summary>
/// <returns></returns>
public static long ToUnixTimeMilliseconds()
{
return ((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0))).TotalSeconds);
}
}
}