Repository URL to install this package:
|
Version:
1.0.0 ▾
|
using System;
using System.Security.Cryptography;
using System.Text;
using JetBrains.Annotations;
namespace Fluctio.FluctioSim.Utils.Extensions
{
public static class BytesExtensions
{
[Pure] public static byte[] Encode(this string str, Encoding encoding) => encoding.GetBytes(str);
[Pure] public static string Decode(this byte[] bytes, Encoding encoding) => encoding.GetString(bytes);
[Pure] public static string ToBase64(this byte[] bytes) => Convert.ToBase64String(bytes);
[Pure] public static byte[] FromBase64(this string str) => Convert.FromBase64String(str);
[Pure]
public static string ToBase64UrlSafe(this byte[] bytes) =>
bytes
.ToBase64()
.Replace("+", "-")
.Replace("/", "_")
.TrimEnd('=');
[Pure]
public static byte[] FromBase64UrlSafe(this string str)
{
var paddingToAdd = (str.Length % 4) switch
{
0 => 0,
2 => 2,
3 => 1,
_ => throw new ArgumentException("Incorrect url-safe base64, wrong length", nameof(str))
};
var totalLength = str.Length + paddingToAdd;
return str
.PadRight(totalLength, '=')
.Replace("-", "+")
.Replace("_", "/")
.FromBase64();
}
[Pure]
public static byte[] Hash(this byte[] bytes, HashAlgorithmName algorithmName)
{
var algorithmNameString = algorithmName.Name;
var algorithm = HashAlgorithm.Create(algorithmNameString);
if (algorithm == null)
{
throw new ArgumentException("Invalid algorithm name", nameof(algorithmName));
}
return algorithm.ComputeHash(bytes);
}
}
}