3 using System.Xml.Serialization;
\r
4 using System.Security.Cryptography;
\r
6 namespace NaGet.Packages
\r
9 /// ハッシュ値の種類(計算法)を表す。
\r
11 public enum HashValueType
\r
14 /// ファイルのサイズ(容量)をバイト単位で返す
\r
16 [XmlEnum(Name="size")]
\r
18 [XmlEnum(Name="md5")]
\r
20 [XmlEnum(Name="sha1")]
\r
22 [XmlEnum(Name="sha256")]
\r
26 public class HashValue
\r
32 public HashValueType Type;
\r
38 public string Value;
\r
48 /// 与えられたファイルのハッシュ値が同一であるか検証する
\r
50 /// <param name="path">ハッシュ計算を行う対象のファイル</param>
\r
51 /// <returns>ファイルのハッシュ値が妥当な場合true。</returns>
\r
52 public bool Validate(string path)
\r
54 return string.Compare(this.Value, HashValueFor(path, this.Type), true) == 0;
\r
60 /// <param name="file">計算対象のファイル</param>
\r
61 /// <param name="type">ハッシュの種類(計算法)</param>
\r
62 /// <returns></returns>
\r
63 public static string HashValueFor(string file, HashValueType type)
\r
65 using (FileStream fs = new FileStream(file, FileMode.Open)) {
\r
66 return HashValue.HashValueFor(fs, type);
\r
71 /// ストリーム入力からハッシュを計算する
\r
73 /// <param name="stream">ストリーム入力</param>
\r
74 /// <param name="type">ハッシュの種類(計算法)</param>
\r
75 /// <returns>ハッシュ値</returns>
\r
76 public static string HashValueFor(Stream stream, HashValueType type)
\r
81 case HashValueType.SIZE:
\r
82 return stream.Length.ToString();
\r
83 case HashValueType.MD5SUM:
\r
84 hash = MD5.Create().ComputeHash(stream);
\r
86 case HashValueType.SHA1SUM:
\r
87 hash = SHA1.Create().ComputeHash(stream);
\r
89 case HashValueType.SHA256SUM:
\r
90 hash = SHA256.Create().ComputeHash(stream);
\r
93 throw new NotSupportedException(string.Format("Hash type {0} does not supported", type));
\r
96 return BitConverter.ToString(hash).Replace("-",string.Empty);
\r