59 lines
1.4 KiB
C#
59 lines
1.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace BS.Shared.Core
|
|
{
|
|
public static class SecurityUtils
|
|
{
|
|
private static readonly char[] InvalidFilenameChars = Path.GetInvalidFileNameChars();
|
|
|
|
public static bool ContainsInvalidFilenameChars(string fileName)
|
|
{
|
|
return fileName.IndexOfAny(InvalidFilenameChars) >= 0;
|
|
}
|
|
|
|
public static string SanitizeFilename(string fileName)
|
|
{
|
|
if (String.IsNullOrEmpty(fileName) || !ContainsInvalidFilenameChars(fileName))
|
|
{
|
|
return fileName;
|
|
}
|
|
|
|
var sb = new StringBuilder(fileName.Length);
|
|
foreach (char c in fileName)
|
|
{
|
|
if (!InvalidFilenameChars.Contains(c))
|
|
{
|
|
sb.Append(c);
|
|
}
|
|
}
|
|
return sb.ToString();
|
|
}
|
|
|
|
public static string GetChecksum(string filePath)
|
|
{
|
|
using (FileStream stream = File.OpenRead(filePath))
|
|
{
|
|
var sha = new SHA256Managed();
|
|
byte[] checksum = sha.ComputeHash(stream);
|
|
return BitConverter.ToString(checksum).Replace("-", String.Empty);
|
|
}
|
|
}
|
|
|
|
public static string GetChecksumBuffered(Stream stream)
|
|
{
|
|
using (var bufferedStream = new BufferedStream(stream, 1024 * 32))
|
|
{
|
|
var sha = new SHA256Managed();
|
|
byte[] checksum = sha.ComputeHash(bufferedStream);
|
|
return BitConverter.ToString(checksum).Replace("-", String.Empty);
|
|
}
|
|
}
|
|
}
|
|
}
|