using System; using System.IO; using System.Xml.Serialization; using System.Security.Cryptography; namespace NaGet.Packages { /// /// ハッシュ値の種類(計算法)を表す。 /// public enum HashValueType { /// /// ファイルのサイズ(容量)をバイト単位で返す /// [XmlEnum(Name="size")] SIZE, [XmlEnum(Name="md5")] MD5SUM, [XmlEnum(Name="sha1")] SHA1SUM, [XmlEnum(Name="sha256")] SHA256SUM, [XmlEnum(Name="sha512")] SHA512SUM, } public class HashValue { /// /// ハッシュ値の種類(計算法) /// [XmlAttribute] public HashValueType Type; /// /// ハッシュ値そのものをあらわす /// [XmlText] public string Value; /// /// コンストラクタ /// public HashValue() { } /// /// 与えられたファイルのハッシュ値が同一であるか検証する /// /// ハッシュ計算を行う対象のファイル /// ファイルのハッシュ値が妥当な場合true。 public bool Validate(string path) { return string.Compare(this.Value, HashValueFor(path, this.Type), true) == 0; } /// /// ファイルのハッシュを計算する /// /// 計算対象のファイル /// ハッシュの種類(計算法) /// public static string HashValueFor(string file, HashValueType type) { using (FileStream fs = new FileStream(file, FileMode.Open)) { return HashValue.HashValueFor(fs, type); } } /// /// ストリーム入力からハッシュを計算する /// /// ストリーム入力 /// ハッシュの種類(計算法) /// ハッシュ値 public static string HashValueFor(Stream stream, HashValueType type) { byte[] hash; switch (type) { case HashValueType.SIZE: return stream.Length.ToString(); case HashValueType.MD5SUM: hash = MD5.Create().ComputeHash(stream); break; case HashValueType.SHA1SUM: hash = SHA1.Create().ComputeHash(stream); break; case HashValueType.SHA256SUM: hash = SHA256.Create().ComputeHash(stream); break; case HashValueType.SHA512SUM: hash = SHA512.Create().ComputeHash(stream); break; default: throw new NotSupportedException(string.Format("Hash type {0} does not supported", type)); } return BitConverter.ToString(hash).Replace("-",string.Empty); } } }