3 using System.Xml.Serialization;
\r
4 using System.Security.Cryptography;
\r
6 namespace NaGet.Packages
\r
9 /// ハッシュ値の種類(計算法)を表す。
\r
11 public enum HashValueType
\r
13 [XmlEnum(Name="size")]
\r
15 [XmlEnum(Name="md5")]
\r
17 [XmlEnum(Name="sha1")]
\r
19 [XmlEnum(Name="sha256")]
\r
23 public class HashValue
\r
29 public HashValueType Type;
\r
35 public string Value;
\r
45 /// 与えられたファイルのハッシュ値が同一であるか検証する
\r
47 /// <param name="path">ハッシュ計算を行う対象のファイル</param>
\r
48 /// <returns>ファイルのハッシュ値が妥当な場合true。</returns>
\r
49 public bool Validate(string path)
\r
51 return string.Compare(this.Value, HashValueFor(path, this.Type), true) == 0;
\r
57 /// <param name="file">計算対象のファイル</param>
\r
58 /// <param name="type">ハッシュの種類(計算法)</param>
\r
59 /// <returns></returns>
\r
60 public static string HashValueFor(string file, HashValueType type)
\r
62 using (FileStream fs = new FileStream(file, FileMode.Open)) {
\r
63 return HashValue.HashValueFor(fs, type);
\r
68 /// ストリーム入力からハッシュを計算する
\r
70 /// <param name="stream">ストリーム入力</param>
\r
71 /// <param name="type">ハッシュの種類(計算法)</param>
\r
72 /// <returns></returns>
\r
73 public static string HashValueFor(Stream stream, HashValueType type)
\r
78 case HashValueType.SIZE:
\r
79 return stream.Length.ToString();
\r
80 case HashValueType.MD5SUM:
\r
81 hash = MD5.Create().ComputeHash(stream);
\r
83 case HashValueType.SHA1SUM:
\r
84 hash = SHA1.Create().ComputeHash(stream);
\r
86 case HashValueType.SHA256SUM:
\r
87 hash = SHA256.Create().ComputeHash(stream);
\r
90 throw new NotSupportedException(string.Format("Hash type {0} does not supported", type));
\r
93 return BitConverter.ToString(hash).Replace("-",string.Empty);
\r