winget-cli

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

ManifestTokens.cs (1555B)


      1 // Copyright (c) Microsoft Corporation.
      2 // Licensed under the MIT License.
      3 
      4 namespace Microsoft.WinGetSourceCreator
      5 {
      6     using System.Security.Cryptography;
      7 
      8     public class ManifestTokens
      9     {
     10         public ManifestTokens()
     11         {
     12         }
     13 
     14         public Dictionary<string, string> Tokens { get; private set; } = new Dictionary<string, string>();
     15 
     16         public void AddHashToken(string file, string token)
     17         {
     18             if (!token.StartsWith("<") || !token.EndsWith(">"))
     19             {
     20                 throw new Exception("Token should be in the form of <TOKEN VALUE>");
     21             }
     22 
     23             var hash = HashFile(file);
     24             this.Tokens.Add(token, hash);
     25         }
     26 
     27         /// <summary>
     28         /// Gets the hash of the specified file.
     29         /// </summary>
     30         /// <param name="filePath">File path.</param>
     31         /// <returns>Hash of file.</returns>
     32         private static string HashFile(string filePath)
     33         {
     34             if (!File.Exists(filePath))
     35             {
     36                 throw new FileNotFoundException(filePath);
     37             }
     38 
     39             string hash = string.Empty;
     40 
     41             using SHA256 mySHA256 = SHA256.Create();
     42             using FileStream fs = File.OpenRead(filePath);
     43             fs.Position = 0;
     44             byte[] hashValue = mySHA256.ComputeHash(fs);
     45 
     46             for (int i = 0; i < hashValue.Length; i++)
     47             {
     48                 hash += $"{hashValue[i]:X2}";
     49             }
     50 
     51             return hash;
     52         }
     53     }
     54 }