private static void SetHash(HttpContext context, string key, CSPHashType algorithm, string hash) { var hashes = context.Items[key] as List <string>; if (hashes is null) { hashes = new List <string>(); context.Items[key] = hashes; } hashes.Add(GetSource(algorithm, hash)); }
private static string GetSource(CSPHashType algorithm, string hash) { switch (algorithm) { case CSPHashType.SHA256: return($"'sha256-{hash}'"); case CSPHashType.SHA384: return($"'sha384-{hash}'"); case CSPHashType.SHA512: return($"'sha512-{hash}'"); default: throw new InvalidOperationException($"Unknown CSP hash algorithm: {algorithm}"); } }
/// <summary> /// Create an instance of the required hashing algorithm /// </summary> /// <param name="algorithm">The CSP algorithm to create</param> /// <returns>The hashing algorithm instance</returns> public static HashAlgorithm Create(CSPHashType algorithm) { switch (algorithm) { case CSPHashType.SHA256: return(CreateSHA256()); case CSPHashType.SHA384: return(CreateSHA384()); case CSPHashType.SHA512: return(CreateSHA512()); default: throw new InvalidOperationException($"Unknown CSP Hash Type: {algorithm}"); } }
/// <summary> /// Adds a CSP hash to the collection of sources for style-src /// </summary> /// <param name="context">The <see cref="HttpContext"/> for the request</param> /// <param name="algorithm">The algorithm used to calcualte the hash</param> /// <param name="hash">The hash generated from the content</param> public static void SetStylesCSPHash(this HttpContext context, CSPHashType algorithm, string hash) { SetHash(context, Constants.DefaultStylesHashKey, algorithm, hash); }