Ejemplo n.º 1
20
 public static HashAlgorithm GetHashProvider(HashType type)
 {
     HashAlgorithm hash = null;
     switch (type)
     {
         case HashType.MD5:
             {
                 hash = new MD5CryptoServiceProvider();
                 break;
             }
         case HashType.SHA1:
             {
                 hash = new SHA1CryptoServiceProvider();
                 break;
             }
         case HashType.SHA256:
             {
                 hash = new SHA256CryptoServiceProvider();
                 break;
             }
         case HashType.SHA384:
             {
                 hash = new SHA384CryptoServiceProvider();
                 break;
             }
         case HashType.SHA512:
             {
                 hash = new SHA512CryptoServiceProvider();
                 break;
             }
     }
     return hash;
 }
Ejemplo n.º 2
0
        private HashAlgorithm GetHashAlgorithm(string hashType)
        {
            HashAlgorithm hash = null;
            string hashTypeLower = hashType.ToLowerInvariant();

            switch (hashTypeLower)
            {
                case "md5":
                    hash = new MD5CryptoServiceProvider();
                    break;
                case "ripemd160":
                    hash = new RIPEMD160Managed();
                    break;
                case "sha1":
                    hash = new SHA1CryptoServiceProvider();
                    break;
                case "sha256":
                    hash = new SHA256CryptoServiceProvider();
                    break;
                case "sha384":
                    hash = new SHA384CryptoServiceProvider();
                    break;
                case "sha512":
                    hash = new SHA512CryptoServiceProvider();
                    break;
                default:
                    break;
            }

            return hash;
        }
Ejemplo n.º 3
0
 private static string Hash(byte[] clearBuffer, HashAlgorithm algorithm)
 {
     System.Security.Cryptography.HashAlgorithm hashAlgorithm;
     switch (algorithm)
     {
         case HashAlgorithm.MD5:
             hashAlgorithm = new MD5CryptoServiceProvider();
             break;
         case HashAlgorithm.SHA1:
         default:
             hashAlgorithm = new SHA1CryptoServiceProvider();
             break;
         case HashAlgorithm.SHA256:
             hashAlgorithm = new SHA256CryptoServiceProvider();
             break;
         case HashAlgorithm.SHA384:
             hashAlgorithm = new SHA384CryptoServiceProvider();
             break;
         case HashAlgorithm.SHA512:
             hashAlgorithm = new SHA512CryptoServiceProvider();
             break;
     }
     var encryptedBuffer = hashAlgorithm.ComputeHash(clearBuffer);
     return Convert.ToBase64String(encryptedBuffer);
 }
Ejemplo n.º 4
0
        /// <summary>
        /// SHA1编码
        /// </summary>
        /// <param name="value">明文</param>
        /// <param name="bit">位长</param>
        /// <returns></returns>
        public static string Get(string value, SHA1Bit bit)
        {
            StringBuilder sBuilder = new StringBuilder();

            if (bit == SHA1Bit.L160)
            {
                System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                // This is one implementation of the abstract class SHA1.
                byte[] result = sha.ComputeHash(Encoding.Default.GetBytes(value));
                sBuilder.Append(BitConverter.ToString(result).Replace("-", ""));
            }
            if (bit == SHA1Bit.L256)
            {
                System.Security.Cryptography.SHA256 sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
                // This is one implementation of the abstract class SHA1.
                byte[] result = sha256.ComputeHash(Encoding.Default.GetBytes(value));
                sBuilder.Append(BitConverter.ToString(result).Replace("-", ""));
            }
            if (bit == SHA1Bit.L384)
            {
                System.Security.Cryptography.SHA384 sha384 = new System.Security.Cryptography.SHA384CryptoServiceProvider();
                // This is one implementation of the abstract class SHA1.
                byte[] result = sha384.ComputeHash(Encoding.Default.GetBytes(value));
                sBuilder.Append(BitConverter.ToString(result).Replace("-", ""));
            }
            return(sBuilder.ToString());
        }
Ejemplo n.º 5
0
 /// <summary>
 /// 48字节,384位
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static string SHA384(string str)
 {
     byte[] buffer = Encoding.UTF8.GetBytes(str);
     SHA384CryptoServiceProvider SHA384 = new SHA384CryptoServiceProvider();
     byte[] byteArr = SHA384.ComputeHash(buffer);
     return BitConverter.ToString(byteArr);
 }
Ejemplo n.º 6
0
        private static string Hash(string password)
        {
            var provider = new SHA384CryptoServiceProvider();
            var passBytes = GetBytes(password);
            var hash = provider.ComputeHash(passBytes);
            var hashString = GetString(hash);

            return hashString;
        }
Ejemplo n.º 7
0
        public static string Sha384Encode(string pwd)
        {
            SHA384 sha384 = new SHA384CryptoServiceProvider();//建立一個SHA384

            byte[] source = Encoding.Default.GetBytes(pwd);//將字串轉為Byte[]

            byte[] crypto = sha384.ComputeHash(source);//進行SHA384加密

            string result = Convert.ToBase64String(crypto);//把加密後的字串從Byte[]轉為字串

            return result;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Calculates the SHA384-hash of the given string
        /// </summary>
        /// <returns>Hexadecimal representation of the SHA384-hash.</returns>
        /// <param name="str">Input string.</param>
        public static string SHA384(string str)
        {
            var bytes = Encoding.ASCII.GetBytes (str);
            byte[] hash;

            // We're using the native SHA384 implementation here.
            using (var hasher = new SHA384CryptoServiceProvider ()) {
                hash = hasher.ComputeHash (bytes);
            }

            return hash.ToHex ();
        }
Ejemplo n.º 9
0
        public static string GetSHA384(byte[] data)
        {
            System.Security.Cryptography.SHA384 sha = new System.Security.Cryptography.SHA384CryptoServiceProvider();
            byte[] bytResult = sha.ComputeHash(data);
            //转换成字符串,32位
            string strResult = BitConverter.ToString(bytResult);

            //BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉
            strResult = strResult.Replace("-", "");

            return(strResult);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Hashes a stream with SHA-384.
        /// </summary>
        /// <param name="stream">The stream to hash.</param>
        /// <returns>The hash.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="stream" /> is <see langword="null" />.
        /// </exception>
        public static byte[] SHA384(this Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            using (var hasher = new SHA384CryptoServiceProvider())
            {
                return hasher.ComputeHash(stream);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 获取文本SHA384
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string GetTextSHA_384(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return("");
            }
            System.Security.Cryptography.SHA384CryptoServiceProvider SHA384CSP = new System.Security.Cryptography.SHA384CryptoServiceProvider();
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(text);
            byte[] bytHash  = SHA384CSP.ComputeHash(bytValue);
            SHA384CSP.Clear();

            //根据计算得到的Hash码翻译为SHA-1码
            string sHash = ConvertHashBytes(bytHash);

            //根据大小写规则决定返回的字符串
            return(sHash.ToLower());
        }
Ejemplo n.º 12
0
 /// <summary>
 /// 获取字符串的 40 位 SHA384 大写。
 /// </summary>
 /// <param name="input">需计算 SHA384 的字符串。</param>
 /// <param name="prefix">需添加的字符串前缀。</param>
 /// <returns>40 位 SHA384 大写。</returns>
 /// <exception cref="ArgumentNullException"><c>input</c> 为 null。</exception>
 public static string GetStringSHA386(string input, string prefix = "")
 {
     if (input == null)
     {
         throw new ArgumentNullException("input", "input 不能为空。");
     }
     using (SHA384CryptoServiceProvider sha384Csp = new SHA384CryptoServiceProvider())
     {
         byte[] bytes = sha384Csp.ComputeHash(Encoding.UTF8.GetBytes(prefix + input));
         StringBuilder sb = new StringBuilder(40);
         foreach (var temp in bytes)
         {
             sb.AppendFormat("{0:X2}", temp);
         }
         return sb.ToString();
     }
 }
Ejemplo n.º 13
0
        public static byte[] HashRaw(EHashType type, byte[] bs)
        {
            if (bs == null) return null;

            HashAlgorithm cmd5 = null;
            switch (type)
            {
                case EHashType.Md5: cmd5 = new MD5CryptoServiceProvider(); break;
                case EHashType.Sha1: cmd5 = new SHA1CryptoServiceProvider(); break;
                case EHashType.Sha256: cmd5 = new SHA256CryptoServiceProvider(); break;
                case EHashType.Sha384: cmd5 = new SHA384CryptoServiceProvider(); break;
                case EHashType.Sha512: cmd5 = new SHA512CryptoServiceProvider(); break;
            }

            bs = cmd5.ComputeHash(bs);
            cmd5.Dispose();
            return bs;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 计算SHA-384码
        /// </summary>
        /// <param name="word">字符串</param>
        /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
        /// <returns></returns>
        public static string Hash_SHA_384(string word, bool toUpper = true)
        {
            try
            {
                System.Security.Cryptography.SHA384CryptoServiceProvider SHA384CSP
                    = new System.Security.Cryptography.SHA384CryptoServiceProvider();

                byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
                byte[] bytHash  = SHA384CSP.ComputeHash(bytValue);
                SHA384CSP.Clear();

                //根据计算得到的Hash码翻译为SHA-1码
                string sHash = "", sTemp = "";
                for (int counter = 0; counter < bytHash.Count(); counter++)
                {
                    long i = bytHash[counter] / 16;
                    if (i > 9)
                    {
                        sTemp = ((char)(i - 10 + 0x41)).ToString();
                    }
                    else
                    {
                        sTemp = ((char)(i + 0x30)).ToString();
                    }
                    i = bytHash[counter] % 16;
                    if (i > 9)
                    {
                        sTemp += ((char)(i - 10 + 0x41)).ToString();
                    }
                    else
                    {
                        sTemp += ((char)(i + 0x30)).ToString();
                    }
                    sHash += sTemp;
                }

                //根据大小写规则决定返回的字符串
                return(toUpper ? sHash : sHash.ToLower());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Calculate the hash value based on the hash algorith type  selected by the user
        /// Default to SHA1
        /// This result from is used for both generating a hash value as well as validating the file hash
        /// </summary>
        /// <param name="file">file to get the hash of</param>
        /// <param name="hashAlgo">hash algorithm to use</param>
        public string[] CalculateHash(string file, string hashAlgo)
        {
            string caseSwitch = hashAlgo;
            resultToReturn = new string[2];
            string hashValue = String.Empty;
            FileStream fileStream = File.Open(file, FileMode.Open);
            fileStream.Position = 0;
            try
            {
                switch (caseSwitch)
                {
                    case "MD5":
                        MD5 objMd5 = new MD5CryptoServiceProvider();
                        hashValue = BitConverter.ToString(objMd5.ComputeHash(fileStream)).Replace("-", String.Empty).ToLower();
                        break;
                    case "SHA-256":
                        SHA256 objSha256 = new SHA256CryptoServiceProvider();
                        hashValue = BitConverter.ToString(objSha256.ComputeHash(fileStream)).Replace("-", String.Empty).ToLower();
                        break;
                    case "SHA-384":
                        SHA384 objSha384 = new SHA384CryptoServiceProvider();
                        hashValue = BitConverter.ToString(objSha384.ComputeHash(fileStream)).Replace("-", String.Empty).ToLower();
                        break;
                    default:
                        SHA1 objSha1 = new SHA1CryptoServiceProvider();
                        hashValue = BitConverter.ToString(objSha1.ComputeHash(fileStream)).Replace("-", String.Empty).ToLower();
                        break;
                }

                resultToReturn[0] = SUCCESS;
                resultToReturn[1] = hashValue;
            }
            catch
            {
                resultToReturn[0] = FAIL;
                resultToReturn[1] = ERROR_MSG;
            }
            finally
            {
                fileStream.Close();
            }

            return resultToReturn;
        }
Ejemplo n.º 16
0
        public static HashAlgorithm CreateInstance(HashType theHash)
        {
            HashAlgorithm hash = null;
            switch(theHash)
            {
                case HashType.MD5:
                {
                    hash = new MD5CryptoServiceProvider();
                    break;
                }
                case HashType.RIPEMD160:
                {
                    hash = new RIPEMD160Managed();
                    break;
                }
                case HashType.SHA1:
                {
                    hash = new SHA1CryptoServiceProvider();
                    break;
                }
                case HashType.SHA256:
                {
                    hash = new SHA256CryptoServiceProvider();
                    break;
                }
                case HashType.SHA384:
                {
                    hash = new SHA384CryptoServiceProvider();
                    break;
                }
                case HashType.SHA512:
                {
                    hash = new SHA512CryptoServiceProvider();
                    break;
                }
                default:
                {
                    throw new NotSupportedException(String.Format("The hash algorithm '{0}' is not supported", theHash.ToString()));
                }
            }

            return hash;
        }
Ejemplo n.º 17
0
        public static byte[] HashRaw(EHashType type, Stream bs, bool seekBegin)
        {
            if (bs == null) return null;

            HashAlgorithm cmd5 = null;
            switch (type)
            {
                case EHashType.Md5: cmd5 = new MD5CryptoServiceProvider(); break;
                case EHashType.Sha1: cmd5 = new SHA1CryptoServiceProvider(); break;
                case EHashType.Sha256: cmd5 = new SHA256CryptoServiceProvider(); break;
                case EHashType.Sha384: cmd5 = new SHA384CryptoServiceProvider(); break;
                case EHashType.Sha512: cmd5 = new SHA512CryptoServiceProvider(); break;
            }

            if (seekBegin) bs.Seek(0, SeekOrigin.Begin);

            byte[] bsh = cmd5.ComputeHash(bs);
            cmd5.Dispose();
            return bsh;
        }
Ejemplo n.º 18
0
 /// <summary>
 /// 获取文件的 40 位 SHA384 大写。
 /// </summary>
 /// <param name="filePath">需计算 SHA384 的文件。</param>
 /// <returns>40 位 SHA384 大写。</returns>
 /// <exception cref="FileNotFoundException"><c>filePath</c> 不存在。</exception>
 public static string GetFileSHA384(string filePath)
 {
     if (File.Exists(filePath) == false)
     {
         throw new FileNotFoundException("文件不存在!", filePath);
     }
     using (SHA384CryptoServiceProvider sha384Csp = new SHA384CryptoServiceProvider())
     {
         using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
         {
             byte[] bytes = sha384Csp.ComputeHash(fs);
             StringBuilder sb = new StringBuilder(40);
             foreach (var temp in bytes)
             {
                 sb.AppendFormat("{0:X2}", temp);
             }
             return sb.ToString();
         }
     }
 }
Ejemplo n.º 19
0
        public static string ComputeHash(string msg)
        {
            string result = string.Empty;
            var md5 = new MD5CryptoServiceProvider();
            var sha1 = new SHA1CryptoServiceProvider();
            var sha256 = new SHA256CryptoServiceProvider();
            var sha384 = new SHA384CryptoServiceProvider();
            var sha512 = new SHA512CryptoServiceProvider();
            var ripemd160 = new RIPEMD160Managed();

            var source = System.Text.UTF8Encoding.Default.GetBytes(msg);

            var algorithms = new Dictionary<string, HashAlgorithm>();
            algorithms["md5"] = md5;
            algorithms["sha1"] = sha1;
            algorithms["sha256"] = sha256;
            algorithms["sha384"] = sha384;
            algorithms["sha512"] = sha512;
            algorithms["ripemd160"] = ripemd160;

            result = Convert.ToBase64String(sha512.ComputeHash(source));
            return result;
        }
Ejemplo n.º 20
0
 private void btn3_Click(object sender, RoutedEventArgs e)
 {
     SHA384CryptoServiceProvider sha = new SHA384CryptoServiceProvider();
     Encode(sha);
 }
Ejemplo n.º 21
0
 /// <summary>
 /// sha-384
 /// </summary>
 /// <param name="s"></param>
 /// <returns></returns>
 public static string Sha384(string s)
 {
     SHA384 sha1 = new SHA384CryptoServiceProvider();
     var encryptedBytes = sha1.ComputeHash(s.ToAsciiBytes());
     var sb = new StringBuilder();
     foreach (var t in encryptedBytes) sb.AppendFormat("{0:x2}", t);
     return sb.ToString().ToLower();
 }
		public override void SetUp ()
		{
			hash = new SHA384CryptoServiceProvider ();
		}
Ejemplo n.º 23
0
 public static string HashSHA384(string phrase)
 {
     if (phrase == null)
         return null;
     var encoder = new UTF8Encoding();
     var sha384Hasher = new SHA384CryptoServiceProvider();
     var hashedDataBytes = sha384Hasher.ComputeHash(encoder.GetBytes(phrase));
     return ByteArrayToHexString(hashedDataBytes);
 }
Ejemplo n.º 24
0
        void ParseServerKeyExchangeMessage(byte[] buf, ref int pos)
        {
            var secParamStart = pos;

            if (_pendingConnState.CipherSuite.KeyExchange == KeyExchange.DHE_RSA || _pendingConnState.CipherSuite.KeyExchange == KeyExchange.DHE_DSS)
            {

                // We add 1 extra 0-byte to each array to make sure the sign is positive (BigInteger constructor checks most significant bit)
                var Plen = Utils.ReadUInt16(buf, ref pos);
                _handshakeData.P = new byte[Plen + 1];
                for (var i = 0; i < Plen; i++)
                    _handshakeData.P[i] = buf[pos + Plen - 1 - i];
                pos += Plen;

                var Glen = Utils.ReadUInt16(buf, ref pos);
                _handshakeData.G = new byte[Glen + 1];
                for (var i = 0; i < Glen; i++)
                    _handshakeData.G[i] = buf[pos + Glen - 1 - i];
                pos += Glen;

                var Yslen = Utils.ReadUInt16(buf, ref pos);
                _handshakeData.Ys = new byte[Yslen + 1];
                for (var i = 0; i < Yslen; i++)
                    _handshakeData.Ys[i] = buf[pos + Yslen - 1 - i];
                pos += Yslen;
            }
            else if (_pendingConnState.CipherSuite.KeyExchange == KeyExchange.ECDHE_RSA || _pendingConnState.CipherSuite.KeyExchange == KeyExchange.ECDHE_ECDSA)
            {
                // ECDHE

                var curveType = buf[pos++];
                if (curveType != 0x03) // 0x03 = Named curve
                {
                    SendAlertFatal(AlertDescription.IllegalParameter);
                }
                var namedcurve = (NamedCurve)Utils.ReadUInt16(buf, ref pos);
                EllipticCurve curve;
                switch (namedcurve)
                {
                    case NamedCurve.secp256r1:
                        curve = EllipticCurve.P256;
                        break;
                    case NamedCurve.secp384r1:
                        curve = EllipticCurve.P384;
                        break;
                    case NamedCurve.secp521r1:
                        curve = EllipticCurve.P521;
                        break;
                    default:
                        SendAlertFatal(AlertDescription.IllegalParameter);
                        curve = null;
                        break;
                }
                pos++;  // opaqueLen. TODO: check len
                if (buf[pos++] != 4) // Uncompressed
                {
                    SendAlertFatal(AlertDescription.IllegalParameter);
                }
                _handshakeData.EcX = new EllipticCurve.BigInt(buf, pos, curve.curveByteLen);
                pos += curve.curveByteLen;
                _handshakeData.EcY = new EllipticCurve.BigInt(buf, pos, curve.curveByteLen);
                pos += curve.curveByteLen;
                _handshakeData.EcCurve = curve;
            }
            else
            {
                SendAlertFatal(AlertDescription.UnexpectedMessage);
            }

            int parametersEnd = pos;

            // Digitally signed client random + server random + parameters
            TLSHashAlgorithm hashAlgorithm;
            SignatureAlgorithm signatureAlgorithm;
            if (_pendingConnState.TlsVersion == TlsVersion.TLSv1_2)
            {
                hashAlgorithm = (TLSHashAlgorithm)buf[pos++];
                signatureAlgorithm = (SignatureAlgorithm)buf[pos++];
            }
            else
            {
                signatureAlgorithm = _pendingConnState.CipherSuite.GetSignatureAlgorithm();
                if (signatureAlgorithm == SignatureAlgorithm.RSA)
                    hashAlgorithm = TLSHashAlgorithm.MD5SHA1;
                else
                    hashAlgorithm = TLSHashAlgorithm.SHA1;
            }

            var signatureLen = Utils.ReadUInt16(buf, ref pos);
            byte[] signature = new byte[signatureLen];
            Buffer.BlockCopy(buf, pos, signature, 0, signatureLen);
            pos += signatureLen;

            System.Security.Cryptography.HashAlgorithm alg = null;
            switch (hashAlgorithm)
            {
                case TLSHashAlgorithm.SHA1: alg = new SHA1CryptoServiceProvider(); break;
                case TLSHashAlgorithm.SHA256: alg = new SHA256CryptoServiceProvider(); break;
                case TLSHashAlgorithm.SHA384: alg = new SHA384CryptoServiceProvider(); break;
                case TLSHashAlgorithm.SHA512: alg = new SHA512CryptoServiceProvider(); break;
                case TLSHashAlgorithm.MD5SHA1:
                    if (_pendingConnState.TlsVersion != TlsVersion.TLSv1_2)
                    {
                        alg = new MD5SHA1();
                        break;
                    }
                    else
                    {
                        goto default;
                    }
                default: SendAlertFatal(AlertDescription.IllegalParameter); break;
            }

            alg.TransformBlock(_pendingConnState.ClientRandom, 0, 32);
            alg.TransformBlock(_pendingConnState.ServerRandom, 0, 32);
            alg.TransformBlock(buf, secParamStart, parametersEnd - secParamStart);
            alg.TransformFinalBlock(buf, 0, 0);
            var hash = alg.Hash;

            if (signatureAlgorithm == SignatureAlgorithm.ECDSA)
            {
                var pkParameters = _handshakeData.CertList[0].GetKeyAlgorithmParameters();
                var pkKey = _handshakeData.CertList[0].GetPublicKey();
                bool? res;
                if (Type.GetType("Mono.Runtime") != null)
                    res = EllipticCurve.VerifySignature(pkParameters, pkKey, hash, signature);
                else
                    res = EllipticCurve.VerifySignatureCng(pkParameters, pkKey, hash, signature);
                if (!res.HasValue)
                {
                    SendAlertFatal(AlertDescription.IllegalParameter);
                }
                else if (!res.Value)
                {
                    SendAlertFatal(AlertDescription.DecryptError);
                }
            }
            else
            {
                var pubKey = _handshakeData.CertList[0].PublicKey.Key;
                var rsa = pubKey as RSACryptoServiceProvider;
                var dsa = pubKey as DSACryptoServiceProvider;
                if (signatureAlgorithm == SignatureAlgorithm.RSA && rsa != null)
                {
                    bool ok = _pendingConnState.TlsVersion == TlsVersion.TLSv1_2 ?
                        rsa.VerifyHash(hash, Utils.HashNameToOID[hashAlgorithm.ToString()], signature) :
                        RsaPKCS1.VerifyRsaPKCS1(rsa, signature, hash, _pendingConnState.TlsVersion == TlsVersion.TLSv1_0 && _pendingConnState.CipherSuite.KeyExchange == KeyExchange.DHE_RSA);

                    if (!ok)
                    {
                        SendAlertFatal(AlertDescription.DecryptError);
                    }
                }
                else if (signatureAlgorithm == SignatureAlgorithm.DSA && dsa != null)
                {
                    // We must decode from DER to two raw integers
                    // NOTE: DSACryptoServiceProvider can't handle keys larger than 1024 bits, neither can SslStream.
                    var decodedSignature = Utils.DecodeDERSignature(signature, 0, signature.Length, Utils.GetHashLen(hashAlgorithm) >> 3);
                    if (!dsa.VerifyHash(hash, Utils.HashNameToOID[hashAlgorithm.ToString()], decodedSignature))
                    {
                        SendAlertFatal(AlertDescription.DecryptError);
                    }
                }
                else
                {
                    SendAlertFatal(AlertDescription.IllegalParameter);
                }
            }
        }
		protected override void SetUp ()
		{
			hash = new SHA384CryptoServiceProvider ();
		}
Ejemplo n.º 26
0
 private void Checksum(string algorithm, byte[] data)
 {
   if (algorithm == @"CRC32")
   {
     long crc = CRC32CryptoServiceProvider.Compute(data);
     OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", crc));
   }
   else if (algorithm == @"CRC64")
   {
     ulong crc = CRC64CryptoServiceProvider.Compute(data);
     OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", crc));
   }
   else if (algorithm == @"MD5")
   {
     using (MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider())
     {
       byte[] list = hasher.ComputeHash(data);
       StringBuilder sb = new StringBuilder();
       for (int i = 0; i < list.Length; i++)
       {
         sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
       }
       OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
     }
   }
   else if (algorithm == @"SHA1")
   {
     using (SHA1CryptoServiceProvider hasher = new SHA1CryptoServiceProvider())
     {
       byte[] list = hasher.ComputeHash(data);
       StringBuilder sb = new StringBuilder();
       for (int i = 0; i < list.Length; i++)
       {
         sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
       }
       OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
     }
   }
   else if (algorithm == @"SHA256")
   {
     using (SHA256CryptoServiceProvider hasher = new SHA256CryptoServiceProvider())
     {
       byte[] list = hasher.ComputeHash(data);
       StringBuilder sb = new StringBuilder();
       for (int i = 0; i < list.Length; i++)
       {
         sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
       }
       OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
     }
   }
   else if (algorithm == @"SHA384")
   {
     using (SHA384CryptoServiceProvider hasher = new SHA384CryptoServiceProvider())
     {
       byte[] list = hasher.ComputeHash(data);
       StringBuilder sb = new StringBuilder();
       for (int i = 0; i < list.Length; i++)
       {
         sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
       }
       OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
     }
   }
   else if (algorithm == @"SHA512")
   {
     using (SHA512CryptoServiceProvider hasher = new SHA512CryptoServiceProvider())
     {
       byte[] list = hasher.ComputeHash(data);
       StringBuilder sb = new StringBuilder();
       for (int i = 0; i < list.Length; i++)
       {
         sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
       }
       OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
     }
   }
   else if (algorithm == @"RIPEMD160")
   {
     using (RIPEMD160 hasher = RIPEMD160Managed.Create())
     {
       byte[] list = hasher.ComputeHash(data);
       StringBuilder sb = new StringBuilder();
       for (int i = 0; i < list.Length; i++)
       {
         sb.Append(list[i].ToString("x2", CultureInfo.CurrentCulture));
       }
       OutputText(string.Format(CultureInfo.CurrentCulture, "{0}", sb.ToString()));
     }
   }
 }
Ejemplo n.º 27
0
Archivo: FileEx.cs Proyecto: nikeee/nth
 public static byte[] ComputeHashSha384(string fileName)
 {
     using (var csp = new SHA384CryptoServiceProvider())
         return ComputeHash(fileName, csp);
 }
Ejemplo n.º 28
0
        static HashAlgorithm GetAlgorithm(string name)
        {
            HashAlgorithm alg = null;

            switch(name.ToLowerInvariant())
            {
                case "md2":
                    alg = new MD2Managed();
                    break;
                case "md4":
                    alg = new MD4Managed();
                    break;
                case "md5":
                    alg = new MD5CryptoServiceProvider();
                    break;
                case "sha1":
                    alg = new SHA1CryptoServiceProvider();
                    break;
                case "sha224":
                    alg = new SHA224Managed();
                    break;
                case "sha256":
                    alg = new SHA256CryptoServiceProvider();
                    break;
                case "sha384":
                    alg = new SHA384CryptoServiceProvider();
                    break;
                case "sha512":
                    alg = new SHA512CryptoServiceProvider();
                    break;
                case "xxhash32":
                    alg = new XXHash32();
                    break;
                case "xxhash64":
                    alg = new XXHash64();
                    break;
                default:
                    throw new ArgumentException(_("Invalid algorithm."));
            }
            return alg;
        }
Ejemplo n.º 29
0
 /// <summary>
 /// 创建Hash算法
 /// </summary>
 /// <param name="hashProvider"></param>
 /// <returns></returns>
 internal static HashAlgorithm CreateHashAlgorithm(EnumHashProvider hashProvider)
 {
     HashAlgorithm hashAlgorithm = null;
     switch (hashProvider)
     {
         case EnumHashProvider.MD5CryptoServiceProvider:
             hashAlgorithm = new MD5CryptoServiceProvider();
             break;
         case EnumHashProvider.RIPEMD160Managed:
             hashAlgorithm = new RIPEMD160Managed();
             break;
         case EnumHashProvider.SHA1CryptoServiceProvider:
             hashAlgorithm = new SHA1CryptoServiceProvider();
             break;
         case EnumHashProvider.SHA1Managed:
             hashAlgorithm = new SHA1Managed();
             break;
         case EnumHashProvider.SHA256Managed:
             hashAlgorithm = new SHA256CryptoServiceProvider();
             break;
         case EnumHashProvider.SHA384Managed:
             hashAlgorithm = new SHA384CryptoServiceProvider();
             break;
         case EnumHashProvider.SHA512Managed:
             hashAlgorithm = new SHA512CryptoServiceProvider();
             break;
     }
     return hashAlgorithm;
 }
Ejemplo n.º 30
0
 public static string SHA384(string input)
 {
     SHA384CryptoServiceProvider hasher = new SHA384CryptoServiceProvider();
     return ComputeHash(input, hasher);
 }
Ejemplo n.º 31
0
 static SecurityExtensions()
 {
     rngService = new RNGCryptoServiceProvider();
     sha3Service = new SHA384CryptoServiceProvider();
 }
Ejemplo n.º 32
0
 private string GetSha384Password(string input)
 {
     System.Security.Cryptography.SHA384 sha1 = new System.Security.Cryptography.SHA384CryptoServiceProvider();
     return(Encoding.ASCII.GetString(sha1.ComputeHash(Encoding.ASCII.GetBytes(input))));
 }
Ejemplo n.º 33
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            // Used to build the hash output
            StringBuilder sBuilder = new StringBuilder();

            // Get the plain text from the user
            String input = this.tbPlainText.Text;

            // Will hold the bytes of the encoded hash
            byte[] data;

            // Generate the hash based on the algorithm selection
            switch(cbAlgorithms.Items[cbAlgorithms.SelectedIndex].ToString()) {
                case "MD5":
                       MD5 md5Hash = MD5.Create();
                       data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
                       for (int i = 0; i < data.Length; i++)
                       {
                           sBuilder.Append(data[i].ToString("x2"));
                       }
                    break;

               case "SHA1":
                      SHA1 sha = new SHA1CryptoServiceProvider();
                      data = sha.ComputeHash(Encoding.UTF8.GetBytes(input));
                      for (int i = 0; i < data.Length; i++)
                      {
                          sBuilder.Append(data[i].ToString("x2"));
                      }
                    break;

               case "SHA256":
                      SHA256 sha256 = new SHA256CryptoServiceProvider();
                      data = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
                      for (int i = 0; i < data.Length; i++)
                      {
                          sBuilder.Append(data[i].ToString("x2"));
                      }
                    break;

                case "SHA384":
                      SHA384 sha384 = new SHA384CryptoServiceProvider();
                      data = sha384.ComputeHash(Encoding.UTF8.GetBytes(input));
                      for (int i = 0; i < data.Length; i++)
                      {
                          sBuilder.Append(data[i].ToString("x2"));
                      }
                    break;

                case "SHA512":
                      SHA512 sha512 = new SHA512CryptoServiceProvider();
                      data = sha512.ComputeHash(Encoding.UTF8.GetBytes(input));
                      for (int i = 0; i < data.Length; i++)
                      {
                          sBuilder.Append(data[i].ToString("x2"));
                      }
                    break;

                case "Base 64":
                    data = Encoding.UTF8.GetBytes(this.tbPlainText.Text);
                    sBuilder.Append(Convert.ToBase64String (data));
                    break;

                default:
                    MessageBox.Show("Error: Unknown Algorithm Selected, cannot compute!");
                    break;
            }

            // Display the hash output
            this.tbHashOutput.Text = sBuilder.ToString();
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Returns the hash of the input.
        /// </summary>
        /// <param name="input">The value to hash.</param>
        /// <returns>Hashed string.</returns>
        private string ComputeHash(string input)
        {
            // Calculate hash. Make it look pretty.
            HashAlgorithm provider;

            switch (HashingType)
            {
                case HashingTypeEnum.Sha256:
                    provider = new SHA256CryptoServiceProvider();
                    break;
                case HashingTypeEnum.Sha384:
                    provider = new SHA384CryptoServiceProvider();
                    break;
                case HashingTypeEnum.Sha512:
                    provider = new SHA512CryptoServiceProvider();
                    break;
                default:
                    throw new NotImplementedException(
                        "Hashing type '" + HashingType.ToString() + "' is not implemented.");
            }

            Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            Byte[] hashedBytes = provider.ComputeHash(inputBytes);

            string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "");

            return hashedString;
        }
Ejemplo n.º 35
0
            public string SHA384Hash(string data) {
                Contract.Requires<ArgumentNullException>(data != null);

                using (SHA384 sha = new SHA384CryptoServiceProvider())
                    return GetHash(sha.ComputeHash(Encoding.ASCII.GetBytes(data)));
            }