Ejemplo n.º 1
0
        /// <summary>
        /// 以指定的编码方式计算字符串指定模式的SHA值。
        /// </summary>
        /// <param name="input">需要计算SHA值的字符串。</param>
        /// <param name="encoding">字符串的编码方式。</param>
        /// <param name="mode">计算SHA的模式。</param>
        /// <returns>字符串对应的SHA值。</returns>
        /// <exception cref="ArgumentNullException">参数encoding为null时将抛出该异常。</exception>
        /// <exception cref="ArgumentException">传入不能识别的ShaMode时将抛出该异常。</exception>
        public static string ComputeSha(string input, Encoding encoding, ShaMode mode)
        {
            int length = Convert.ToInt32(mode);

            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty.PadLeft(length, '0'));
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }
            byte[]        buffer  = encoding.GetBytes(input);
            StringBuilder builder = new StringBuilder(length);

            using (HashAlgorithm provider = Encryption.CreateShaProvider(mode))
            {
                byte[] result = provider.ComputeHash(buffer);
                for (int i = 0; i < result.Length; i++)
                {
                    builder.Append(result[i].ToString("X2"));
                }
            }
            return(builder.ToString());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 计算IO流指定模式的SHA值。
        /// </summary>
        /// <param name="stream">需要计算SHA值的IO流。</param>
        /// <param name="mode">计算SHA的模式。</param>
        /// <returns>IO流对应的SHA值。</returns>
        /// <exception cref="ArgumentNullException">参数stream为null时将抛出该异常。</exception>
        /// <exception cref="ArgumentException">传入不能识别的ShaMode时将抛出该异常。</exception>
        public static string ComputeSha(Stream stream, ShaMode mode)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            int           length  = Convert.ToInt32(mode);
            StringBuilder builder = new StringBuilder(length);

            using (HashAlgorithm provider = Encryption.CreateShaProvider(mode))
            {
                byte[] result = provider.ComputeHash(stream);
                for (int i = 0; i < result.Length; i++)
                {
                    builder.Append(result[i].ToString("X2"));
                }
            }
            return(builder.ToString());
        }