File size: 9,728 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Security.Cryptography;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This class implements Get-FileHash.
/// </summary>
[Cmdlet(VerbsCommon.Get, "FileHash", DefaultParameterSetName = PathParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=517145")]
[OutputType(typeof(FileHashInfo))]
public class GetFileHashCommand : HashCmdletBase
{
/// <summary>
/// Path parameter.
/// The paths of the files to calculate hash values.
/// Resolved wildcards.
/// </summary>
/// <value></value>
[Parameter(Mandatory = true, ParameterSetName = PathParameterSet, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
public string[] Path
{
get
{
return _paths;
}
set
{
_paths = value;
}
}
/// <summary>
/// LiteralPath parameter.
/// The literal paths of the files to calculate a hashs.
/// Don't resolved wildcards.
/// </summary>
/// <value></value>
[Parameter(Mandatory = true, ParameterSetName = LiteralPathParameterSet, Position = 0, ValueFromPipelineByPropertyName = true)]
[Alias("PSPath", "LP")]
public string[] LiteralPath
{
get
{
return _paths;
}
set
{
_paths = value;
}
}
private string[] _paths;
/// <summary>
/// InputStream parameter.
/// The stream of the file to calculate a hash.
/// </summary>
/// <value></value>
[Parameter(Mandatory = true, ParameterSetName = StreamParameterSet, Position = 0)]
public Stream InputStream { get; set; }
/// <summary>
/// ProcessRecord() override.
/// This is for paths collecting from pipe.
/// </summary>
protected override void ProcessRecord()
{
List<string> pathsToProcess = new();
ProviderInfo provider = null;
switch (ParameterSetName)
{
case PathParameterSet:
// Resolve paths and check existence
foreach (string path in _paths)
{
try
{
Collection<string> newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider);
if (newPaths != null)
{
pathsToProcess.AddRange(newPaths);
}
}
catch (ItemNotFoundException e)
{
if (!WildcardPattern.ContainsWildcardCharacters(path))
{
ErrorRecord errorRecord = new(e,
"FileNotFound",
ErrorCategory.ObjectNotFound,
path);
WriteError(errorRecord);
}
}
}
break;
case LiteralPathParameterSet:
foreach (string path in _paths)
{
string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
pathsToProcess.Add(newPath);
}
break;
}
foreach (string path in pathsToProcess)
{
if (ComputeFileHash(path, out string hash))
{
WriteHashResult(Algorithm, hash, path);
}
}
}
private byte[] ComputeHash(Stream stream)
{
switch (Algorithm)
{
case HashAlgorithmNames.SHA1:
return SHA1.HashData(stream);
case HashAlgorithmNames.SHA256:
return SHA256.HashData(stream);
case HashAlgorithmNames.SHA384:
return SHA384.HashData(stream);
case HashAlgorithmNames.SHA512:
return SHA512.HashData(stream);
case HashAlgorithmNames.MD5:
return MD5.HashData(stream);
}
Debug.Assert(false, "invalid hash algorithm");
return SHA256.HashData(stream);
}
/// <summary>
/// Perform common error checks.
/// Populate source code.
/// </summary>
protected override void EndProcessing()
{
if (ParameterSetName == StreamParameterSet)
{
byte[] bytehash = ComputeHash(InputStream);
string hash = Convert.ToHexString(bytehash);
WriteHashResult(Algorithm, hash, string.Empty);
}
}
/// <summary>
/// Read the file and calculate the hash.
/// </summary>
/// <param name="path">Path to file which will be hashed.</param>
/// <param name="hash">Will contain the hash of the file content.</param>
/// <returns>Boolean value indicating whether the hash calculation succeeded or failed.</returns>
private bool ComputeFileHash(string path, out string hash)
{
Stream openfilestream = null;
hash = null;
try
{
openfilestream = File.OpenRead(path);
byte[] bytehash = ComputeHash(openfilestream);
hash = Convert.ToHexString(bytehash);
}
catch (FileNotFoundException ex)
{
var errorRecord = new ErrorRecord(
ex,
"FileNotFound",
ErrorCategory.ObjectNotFound,
path);
WriteError(errorRecord);
}
catch (UnauthorizedAccessException ex)
{
var errorRecord = new ErrorRecord(
ex,
"UnauthorizedAccessError",
ErrorCategory.InvalidData,
path);
WriteError(errorRecord);
}
catch (IOException ioException)
{
var errorRecord = new ErrorRecord(
ioException,
"FileReadError",
ErrorCategory.ReadError,
path);
WriteError(errorRecord);
}
finally
{
openfilestream?.Dispose();
}
return hash != null;
}
/// <summary>
/// Create FileHashInfo object and output it.
/// </summary>
private void WriteHashResult(string Algorithm, string hash, string path)
{
FileHashInfo result = new();
result.Algorithm = Algorithm;
result.Hash = hash;
result.Path = path;
WriteObject(result);
}
/// <summary>
/// Parameter set names.
/// </summary>
private const string PathParameterSet = "Path";
private const string LiteralPathParameterSet = "LiteralPath";
private const string StreamParameterSet = "StreamParameterSet";
}
/// <summary>
/// Base Cmdlet for cmdlets which deal with crypto hashes.
/// </summary>
public class HashCmdletBase : PSCmdlet
{
/// <summary>
/// Algorithm parameter.
/// The hash algorithm name: "SHA1", "SHA256", "SHA384", "SHA512", "MD5".
/// </summary>
/// <value></value>
[Parameter(Position = 1)]
[ValidateSet(HashAlgorithmNames.SHA1,
HashAlgorithmNames.SHA256,
HashAlgorithmNames.SHA384,
HashAlgorithmNames.SHA512,
HashAlgorithmNames.MD5)]
public string Algorithm
{
get
{
return _Algorithm;
}
set
{
// A hash algorithm name is case sensitive
// and always must be in upper case
_Algorithm = value.ToUpper();
}
}
private string _Algorithm = HashAlgorithmNames.SHA256;
/// <summary>
/// Hash algorithm names.
/// </summary>
internal static class HashAlgorithmNames
{
public const string MD5 = "MD5";
public const string SHA1 = "SHA1";
public const string SHA256 = "SHA256";
public const string SHA384 = "SHA384";
public const string SHA512 = "SHA512";
}
}
/// <summary>
/// FileHashInfo class contains information about a file hash.
/// </summary>
public class FileHashInfo
{
/// <summary>
/// Hash algorithm name.
/// </summary>
public string Algorithm { get; set; }
/// <summary>
/// Hash value.
/// </summary>
public string Hash { get; set; }
/// <summary>
/// File path.
/// </summary>
public string Path { get; set; }
}
}
|