哈希计算
对称加密
编码/解码
using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;
using System.Text;
namespace SaaS.OfficialWebSite.Web.Controllers
{
public class EncryController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult ComputeHash([FromBody] HashRequest request)
{
try
{
byte[] inputBytes = Encoding.UTF8.GetBytes(request.Input);
byte[] hashBytes;
using (HashAlgorithm algorithm = request.Algorithm.ToUpper() switch
{
"MD5" => MD5.Create(),
"SHA1" => SHA1.Create(),
"SHA256" => SHA256.Create(),
"SHA384" => SHA384.Create(),
"SHA512" => SHA512.Create(),
_ => throw new ArgumentException("不支持的哈希算法")
})
{
hashBytes = algorithm.ComputeHash(inputBytes);
}
string result = request.Format.ToLower() switch
{
"hex" => BitConverter.ToString(hashBytes).Replace("-", "").ToLower(),
"base64" => Convert.ToBase64String(hashBytes),
_ => throw new ArgumentException("不支持的输出格式")
};
return Ok(new { hash = result });
}
catch (Exception ex)
{
return BadRequest(new { message = ex.Message });
}
}
[HttpPost]
public IActionResult SymmetricOperation([FromBody] SymmetricRequest request)
{
try
{
if (string.IsNullOrEmpty(request.Key))
{
throw new ArgumentException("密钥不能为空");
}
// 根据算法创建加密器
SymmetricAlgorithm algorithm = request.Algorithm.ToUpper() switch
{
"AES" => Aes.Create(),
"DES" => DES.Create(),
"TRIPLEDES" => TripleDES.Create(),
_ => throw new ArgumentException("不支持的对称加密算法")
};
// 设置密钥和IV
algorithm.Key = NormalizeKey(request.Key, algorithm.LegalKeySizes[0], algorithm.KeySize / 8);
if (!string.IsNullOrEmpty(request.Iv))
{
algorithm.IV = NormalizeKey(request.Iv, algorithm.LegalBlockSizes[0], algorithm.BlockSize / 8);
}
else
{
// 如果没有提供IV,对于解密操作需要报错
if (request.Action.ToLower() == "decrypt")
{
throw new ArgumentException("解密操作需要提供IV");
}
algorithm.GenerateIV();
}
ICryptoTransform cryptoTransform = request.Action.ToLower() switch
{
"encrypt" => algorithm.CreateEncryptor(),
"decrypt" => algorithm.CreateDecryptor(),
_ => throw new ArgumentException("不支持的操作类型")
};
byte[] inputBytes = request.Action.ToLower() == "encrypt"
? Encoding.UTF8.GetBytes(request.Input)
: request.Format.ToLower() == "base64"
? Convert.FromBase64String(request.Input)
: HexToBytes(request.Input);
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] resultBytes = memoryStream.ToArray();
string result = request.Format.ToLower() switch
{
"base64" => Convert.ToBase64String(resultBytes),
"hex" => BitConverter.ToString(resultBytes).Replace("-", "").ToLower(),
_ => throw new ArgumentException("不支持的输出格式")
};
// 如果是加密操作,返回IV以便后续解密
if (request.Action.ToLower() == "encrypt")
{
string iv = request.Format.ToLower() == "base64"
? Convert.ToBase64String(algorithm.IV)
: BitConverter.ToString(algorithm.IV).Replace("-", "").ToLower();
return Ok(new { result = result, iv = iv });
}
return Ok(new { result = Encoding.UTF8.GetString(resultBytes) });
}
}
}
catch (Exception ex)
{
return BadRequest(new { message = ex.Message });
}
}
[HttpPost]
public IActionResult EncodeDecode([FromBody] EncodeRequest request)
{
try
{
string result = request.Type.ToLower() switch
{
"base64" => request.Action.ToLower() == "encode"
? Convert.ToBase64String(Encoding.UTF8.GetBytes(request.Input))
: Encoding.UTF8.GetString(Convert.FromBase64String(request.Input)),
"url" => request.Action.ToLower() == "encode"
? Uri.EscapeDataString(request.Input)
: Uri.UnescapeDataString(request.Input),
"html" => request.Action.ToLower() == "encode"
? System.Net.WebUtility.HtmlEncode(request.Input)
: System.Net.WebUtility.HtmlDecode(request.Input),
_ => throw new ArgumentException("不支持的编码类型")
};
return Ok(new { result = result });
}
catch (Exception ex)
{
return BadRequest(new { message = ex.Message });
}
}
private byte[] NormalizeKey(string key, KeySizes legalKeySizes, int defaultSize)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
// 找到最接近的合法密钥大小
int validSize = legalKeySizes.MinSize;
for (int i = legalKeySizes.MinSize; i <= legalKeySizes.MaxSize; i += legalKeySizes.SkipSize)
{
if (keyBytes.Length * 8 <= i)
{
validSize = i;
break;
}
}
// 如果输入的密钥太大,截断它
if (keyBytes.Length * 8 > legalKeySizes.MaxSize)
{
validSize = legalKeySizes.MaxSize;
}
// 调整密钥大小
if (validSize / 8 != keyBytes.Length)
{
byte[] newKey = new byte[validSize / 8];
Array.Copy(keyBytes, newKey, Math.Min(keyBytes.Length, newKey.Length));
// 如果密钥太短,用0填充
if (keyBytes.Length < newKey.Length)
{
for (int i = keyBytes.Length; i < newKey.Length; i++)
{
newKey[i] = 0;
}
}
return newKey;
}
return keyBytes;
}
private byte[] HexToBytes(string hex)
{
if (hex.Length % 2 != 0)
{
throw new ArgumentException("十六进制字符串长度必须为偶数");
}
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return bytes;
}
}
public class HashRequest
{
public string Input { get; set; }
public string Algorithm { get; set; }
public string Format { get; set; }
}
public class SymmetricRequest
{
public string Action { get; set; }
public string Input { get; set; }
public string Algorithm { get; set; }
public string Key { get; set; }
public string Iv { get; set; }
public string Format { get; set; }
}
public class EncodeRequest
{
public string Action { get; set; }
public string Input { get; set; }
public string Type { get; set; }
}
}
运行效果:netcore 加密/解密