public static string Sha1(string text)
 {
     byte[] buffer = Encoding.UTF8.GetBytes(text);
     SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider();
     byte[] outbuffer = cryptoTransformSHA1.ComputeHash(buffer);
     return Convert.ToBase64String(outbuffer);
 }
Example #2
0
        private string EncodeBySHA1(string str)
        {
            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] data = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));

            return(Convert.ToBase64String(data));
        }
Example #3
0
    static byte[] GeneratePayload(string ipc, string input, string output)
    {
        byte[] bytes = null;
        using (FileStream fs = new FileStream(input, FileMode.Open, FileAccess.Read))
        {
            bytes = File.ReadAllBytes(input);
            fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
            fs.Close();
        }
        System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
        var hash = sha1.ComputeHash(bytes);
        var sb   = new StringBuilder(hash.Length * 2);

        foreach (byte b in hash)
        {
            sb.Append(b.ToString("X2"));
        }

        string sha1hash = sb.ToString();

        MemoryStream stm    = new MemoryStream();
        BinaryWriter writer = new BinaryWriter(stm);
        string       CACcmd = "\"CAC-move" + ipc + "\t" + input + "\t" + output + "\t" + sha1hash + "\t" + "sha1" + "\t" + "0\"";

        Console.WriteLine("[*] Payload: {0}", CACcmd);
        PackString(writer, 2, CACcmd);
        PackString(writer, 6, "C:\\Program Files (x86)\\Cisco\\Cisco AnyConnect Secure Mobility Client\\vpndownloader.exe");

        byte[] d    = stm.ToArray();
        byte[] data = PackCommand(d);
        return(data);
    }
 public static string EncodePassword(string originalPassword)
 {
     SHA1 sha1 = new SHA1CryptoServiceProvider();
     byte[] inputBytes = (new UnicodeEncoding()).GetBytes(originalPassword);
     byte[] hash = sha1.ComputeHash(inputBytes);
     return Convert.ToBase64String(hash);
 }
Example #5
0
        public static String Sha1(String s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                                 'a', 'b', 'c', 'd', 'e', 'f' };
            try
            {
                //byte[] btInput = System.Text.Encoding.Default.GetBytes(s);
                byte[] btInput = System.Text.Encoding.UTF8.GetBytes(s);//by voidarea

                SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();

                byte[] md = sha.ComputeHash(btInput);
                // 把密文转换成十六进制的字符串形式
                int    j   = md.Length;
                char[] str = new char[j * 2];
                int    k   = 0;
                for (int i = 0; i < j; i++)
                {
                    byte byte0 = md[i];
                    str[k++] = hexDigits[(int)(((byte)byte0) >> 4) & 0xf];
                    str[k++] = hexDigits[byte0 & 0xf];
                }
                return(new string(str));
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.StackTrace);
                return(null);
            }
        }
Example #6
0
        /// <summary>
        /// Takes a string and generates a hash value of 16 bytes.
        /// </summary>
        /// <param name="buffer">The string to be hashed</param>
        /// <param name="passwordFormat">Selects the hashing algorithm used. Accepted values are "sha1" and "md5".</param>
        /// <returns>A string of the hashed password.</returns>
        public static string EncodeBinary(byte[] buffer, string passwordFormat)
        {
            if (buffer == null)
            {
                return(null);
            }

            byte[] result;
            switch (passwordFormat)
            {
            case "sha1":
                SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                result = sha1.ComputeHash(buffer);
                break;

            case "md5":
                MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                result = md5.ComputeHash(buffer);
                break;

            default:
                throw new ArgumentException("Invalid format value. Accepted values are 'sha1' and 'md5'.", nameof(passwordFormat));
            }

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            var sb = new StringBuilder(16);

            foreach (byte t in result)
            {
                sb.Append(t.ToString("x2"));
            }

            return(sb.ToString());
        }
Example #7
0
		public static void Main(string[] args)
		{
			// Use Release Build to use jsc to generate java program
			// Use Debug Build to develop on .net

			// doubleclicking on the jar will not show the console

			{
				Console.WriteLine("SHA1:");
				var hash = new SHA1CryptoServiceProvider().ComputeHash(new byte[] { 0, 1, 2, 3 });

				foreach (var k in hash)
				{
					Console.Write(" " + k);
				}
				Console.WriteLine();
			}

			{
				Console.WriteLine("MD5:");
				var hash = new MD5CryptoServiceProvider().ComputeHash(new byte[] { 0, 1, 2, 3 });

				foreach (var k in hash)
				{
					Console.Write(" " + k);
				}
				Console.WriteLine();
			}

			Console.ReadLine();
		}
Example #8
0
        public static string GetSHA1Hash(string pathName, string byteSeporator)
        {
            string strResult   = "";
            string strHashData = "";

            byte[] arrbytHashValue;
            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1Hasher =
                new System.Security.Cryptography.SHA1CryptoServiceProvider();

            try
            {
                oFileStream     = GetFileStream(pathName);
                arrbytHashValue = oSHA1Hasher.ComputeHash(oFileStream);
                oFileStream.Close();

                strHashData = System.BitConverter.ToString(arrbytHashValue);
                strHashData = strHashData.Replace("-", byteSeporator);
                strResult   = strHashData;
            }
            catch //(System.Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show(ex.Message, "Error!",
                //System.Windows.Forms.MessageBoxButtons.OK,
                //System.Windows.Forms.MessageBoxIcon.Error,
                //System.Windows.Forms.MessageBoxDefaultButton.Button1);
            }

            return(strResult);
        }
Example #9
0
        /// <summary>
        /// 验证消息是否来自微信服务器
        /// </summary>
        /// <param name="signature">微信加密签名</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">随机数</param>
        /// <param name="echostr">随机字符串</param>
        /// <param name="token">公众号基本配置中填写的Token</param>
        /// <returns></returns>
        public static bool CheckSignature(string signature, string timestamp, string nonce)
        {
            if (String.IsNullOrEmpty(signature) || String.IsNullOrEmpty(timestamp) || String.IsNullOrEmpty(nonce))
            {
                return(false);
            }

            List <string> sortList = new List <string>
            {
                timestamp,
                nonce,
                WxToken
            };

            sortList.Sort();

            byte[] data = WxEncoding.GetBytes(string.Join("", sortList));
            System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] result = sha1.ComputeHash(data);                                          //得到哈希值
            string srt    = System.BitConverter.ToString(result).Replace("-", "").ToLower(); //转换成为字符串的显示

            if (srt == signature)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #10
0
        public static string GetSha1ByPathName(string pathName)
        {
            string strResult = string.Empty;

            System.Security.Cryptography.SHA1CryptoServiceProvider oSHA1CryptoServiceProvider =
                new System.Security.Cryptography.SHA1CryptoServiceProvider();

            System.IO.FileStream oFileStream = null;

            try
            {
                oFileStream = GetFileStream(pathName);

                byte[] bytHashValues =
                    oSHA1CryptoServiceProvider.ComputeHash(oFileStream);

                strResult =
                    System.BitConverter.ToString(bytHashValues)
                    .Replace("-", string.Empty);
            }
            catch { }
            finally
            {
                if (oFileStream != null)
                {
                    //oFileStream.Close();
                    oFileStream.Dispose();
                    oFileStream = null;
                }
            }

            return(strResult);
        }
Example #11
0
 private byte[] CalculateHashValue(byte[] SerializedData)
 {
     // Calculte the serialized data's hash value
     SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider();
     byte[] hash = SHA.ComputeHash(SerializedData);
     return hash;
 }
Example #12
0
 internal static byte[] ComputeFileHash(byte[] fileBytes)
 {
     using (var sha1 = new SHA1CryptoServiceProvider())
     {
         return sha1.ComputeHash(fileBytes);
     }
 }
Example #13
0
        public static string GetSHA1Hash(string pathName)
        {
            string strResult   = "";
            string strHashData = "";

            byte[] arrbytHashValue;

            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.SHA1CryptoServiceProvider osha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            try
            {
                oFileStream = new System.IO.FileStream(pathName.Replace("\"", ""), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);

                arrbytHashValue = osha1.ComputeHash(oFileStream); //计算指定Stream 对象的哈希值

                oFileStream.Close();

                //由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”

                strHashData = System.BitConverter.ToString(arrbytHashValue);

                //替换-
                strHashData = strHashData.Replace("-", "");

                strResult = strHashData;
            }

            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(strResult);
        }
Example #14
0
 static public string SHA1Encoding(string Data)
 {
     SHA1CryptoServiceProvider sp = new SHA1CryptoServiceProvider();
     byte[] bdrr = System.Text.Encoding.UTF8.GetBytes(Data);
     byte[] barr = sp.ComputeHash(bdrr);
     return Convert.ToBase64String(barr);
 }
Example #15
0
        private string EncodeByRSA(string str)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title  = "请选择证书";
            ofd.Filter = "pfx证书(*.pfx)|*.pfx";
            if (ofd.ShowDialog() == DialogResult.Cancel)
            {
                return(string.Empty);
            }

            //1.读取证书中的私钥
            //2.计算sha1值
            //3.证书私钥->rsa->rsaformatter->对sha1值签名

            string pfxPrivateKey;

            System.Security.Cryptography.X509Certificates.X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(ofd.FileName, "110110", X509KeyStorageFlags.Exportable);
            pfxPrivateKey = x509.PrivateKey.ToXmlString(true);

            Console.WriteLine(pfxPrivateKey);

            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] hashResult = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));

            System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
            rsa.FromXmlString(pfxPrivateKey);

            System.Security.Cryptography.RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa);
            formatter.SetHashAlgorithm("sha1");
            byte[] data = formatter.CreateSignature(hashResult);

            return(Convert.ToBase64String(data));
        }
Example #16
0
 static byte[] sha1(byte[] input)
 {
     byte[] hash;
     using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
         hash = sha1.ComputeHash(input);
     return(hash);
 }
Example #17
0
        /// <summary>
        /// Open file and get it's SHA1 hash
        /// </summary>
        /// <param name="file_name">File name (full path)</param>
        /// <returns>String representation of the SHA1 hash</returns>
        public static string GetSHAHashFromFile(string file_name, SHAType shaType)
        {
            System.IO.FileStream file = new System.IO.FileStream(file_name, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            byte[] retVal             = null;
            switch (shaType)
            {
            case SHAType.SHA1:
                System.Security.Cryptography.SHA1 sha1obj = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                retVal = sha1obj.ComputeHash(file);
                break;

            case SHAType.SHA256:
                System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create();
                retVal = sha256.ComputeHash(file);
                break;

            case SHAType.SHA384:
                System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384.Create();
                retVal = sha384.ComputeHash(file);
                break;

            case SHAType.SHA512:
                System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512.Create();
                retVal = sha512.ComputeHash(file);
                break;
            }
            file.Close();
            return(BitConverter.ToString(retVal).Replace("-", "").ToLower());
        }
Example #18
0
 /// <summary>
 /// Gets the SHA1 hash of a string.
 /// </summary>
 /// <param name="str">The string to be hashed.</param>
 /// <returns>The Base64 hashed value.</returns>
 public static string Sha1Hash(this string str)
 {
     using (var sha1 = new SHA1CryptoServiceProvider())
     {
         return Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(str)));
     }
 }
Example #19
0
 private static string Sha1(string value)
 {
     var sha1 = new SHA1CryptoServiceProvider();
     byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(value));
     string delimitedHexHash = BitConverter.ToString(hash);
     return delimitedHexHash.Replace("-", "");
 }
Example #20
0
 /// <summary>
 /// SHA1加密 使用缺省密钥给字符串加密
 /// </summary>
 /// <param name="sourceString"></param>
 /// <returns></returns>
 public static string Sha1Encrypt(string sourceString)
 {
     var data = Encoding.Default.GetBytes(sourceString);
     HashAlgorithm sha = new SHA1CryptoServiceProvider();
     var bytes = sha.ComputeHash(data);
     return BitConverter.ToString(bytes).Replace("-", "");
 }
Example #21
0
        internal static byte[] TripleDESKeyWrapDecrypt (byte[] rgbKey, byte[] rgbEncryptedWrappedKeyData) {
            // Check to see whether the length of the encrypted key is reasonable
            if (rgbEncryptedWrappedKeyData.Length != 32 && rgbEncryptedWrappedKeyData.Length != 40 
                && rgbEncryptedWrappedKeyData.Length != 48) 
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_KW_BadKeySize"));

            TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
            // Assume no padding, use CBC mode
            tripleDES.Padding = PaddingMode.None;
            ICryptoTransform dec1 = tripleDES.CreateDecryptor(rgbKey, s_rgbTripleDES_KW_IV);
            byte[] temp2 = dec1.TransformFinalBlock(rgbEncryptedWrappedKeyData, 0, rgbEncryptedWrappedKeyData.Length);
            Array.Reverse(temp2);
            // Get the IV and temp1
            byte[] rgbIV = new byte[8];
            Buffer.BlockCopy(temp2, 0, rgbIV, 0, 8);
            byte[] temp1 = new byte[temp2.Length - rgbIV.Length];
            Buffer.BlockCopy(temp2, 8, temp1, 0, temp1.Length);

            ICryptoTransform dec2 = tripleDES.CreateDecryptor(rgbKey, rgbIV);
            byte[] rgbWKCKS = dec2.TransformFinalBlock(temp1, 0, temp1.Length);

            // checksum the key
            byte[] rgbWrappedKeyData = new byte[rgbWKCKS.Length - 8];
            Buffer.BlockCopy(rgbWKCKS, 0, rgbWrappedKeyData, 0, rgbWrappedKeyData.Length);
            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
            byte[] rgbCKS = sha.ComputeHash(rgbWrappedKeyData);
            for (int index = rgbWrappedKeyData.Length, index1 = 0; index < rgbWKCKS.Length; index++, index1++)
                if (rgbWKCKS[index] != rgbCKS[index1])
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_BadWrappedKeySize"));
            return rgbWrappedKeyData;
        }
Example #22
0
 public static string GetSHA1Checksum(byte[] inBytes)
 {
     using (SHA1CryptoServiceProvider _sha1CryptoServiceProvider = new SHA1CryptoServiceProvider())
     {
         return BitConverter.ToString(_sha1CryptoServiceProvider.ComputeHash(inBytes));
     }
 }
        /// <summary> Private method used to calculate the sha1 check summ</summary>
        private void ComputeChecksum()
        {
            try
            {
                FileStream hashFile = new FileStream(fileName, FileMode.Open, FileAccess.Read);

                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                byte[] result = sha1.ComputeHash(hashFile);

                hashFile.Close();

                string buffer = "";
                foreach (byte thisByte in result)
                {
                    if (thisByte < 16)
                    {
                        buffer += "0" + thisByte.ToString("x");
                    }
                    else
                    {
                        buffer += thisByte.ToString("x");
                    }
                }
                hashResult = buffer;

                errorFlag = false;
            }
            catch
            {
                hashResult = "ERROR";
                errorFlag = true;
            }
        }
Example #24
0
 public string Sha1Hash(string input)
 {
     System.Security.Cryptography.SHA1CryptoServiceProvider sHA1CryptoServiceProvider = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input);
     byte[] value = sHA1CryptoServiceProvider.ComputeHash(bytes);
     return(System.BitConverter.ToString(value).Replace("-", string.Empty).ToLower());
 }
Example #25
0
 public static string sha1encrypt(string phrase)
 {
     UTF8Encoding encoder = new UTF8Encoding();
     SHA1CryptoServiceProvider sha1hasher = new SHA1CryptoServiceProvider();
     byte[] hashedDataBytes = sha1hasher.ComputeHash(encoder.GetBytes(phrase));
     return byteArrayToString(hashedDataBytes);
 }
Example #26
0
 public static string GetHashSHA1(byte[] data)
 {
     using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
     {
         return(string.Concat(sha1.ComputeHash(data).Select(x => x.ToString("X2"))));
     }
 }
Example #27
0
 /// <summary>
 ///success url sayfası içerisinde HashParam  değerinin doğruluğunu kontrol etmek amacıyla oluşturulan  Verilen string'i SHA1 ile hashleyip Base64 formatına çeviren fonksiyondur.
 /// CreateToken'dan farklı olarak token oluşturmaz sadece hassh hesaplar
 /// </summary>
 /// <param name="hashString"></param>
 /// <returns></returns>
 public static string ComputeHash(string hashString)
 {
     System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] hashbytes  = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(hashString);
     byte[] inputbytes = sha.ComputeHash(hashbytes);
     return(Convert.ToBase64String(inputbytes));
 }
Example #28
0
        public static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, ref string sMsgSignature)
        {
            ArrayList AL = new ArrayList();
            AL.Add(sToken);
            AL.Add(sTimeStamp);
            AL.Add(sNonce);
            AL.Add(sMsgEncrypt);
            AL.Sort(new DictionarySort());
            string raw = "";
            for (int i = 0; i < AL.Count; ++i)
            {
                raw += AL[i];
            }

            SHA1 sha;
            ASCIIEncoding enc;
            string hash = "";
            try
            {
                sha = new SHA1CryptoServiceProvider();
                enc = new ASCIIEncoding();
                byte[] dataToHash = enc.GetBytes(raw);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                hash = BitConverter.ToString(dataHashed).Replace("-", "");
                hash = hash.ToLower();
            }
            catch (Exception)
            {
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error;
            }
            sMsgSignature = hash;
            return 0;
        }
Example #29
0
        public static string GenerateToken(string subdomainName, string ssoKey, Object userAttributes, int valid_for=5*60) {
            string initVector = "OpenSSL for Ruby"; // DO NOT CHANGE

            byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            byte[] keyBytesLong;
            using( SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider() ) {
                keyBytesLong = sha.ComputeHash( Encoding.UTF8.GetBytes( ssoKey + subdomainName ) );
            }
            byte[] keyBytes = new byte[16];
            Array.Copy(keyBytesLong, keyBytes, 16);
            var jsonText = JsonConvert.SerializeObject(userAttributes);
            Dictionary<string, dynamic> dict = JsonConvert.DeserializeObject<Dictionary<string, dynamic> >(jsonText);
            if (!dict.ContainsKey("expires")) {
                dict["expires"] = DateTime.UtcNow.AddSeconds(valid_for).ToString("u");
                //Console.WriteLine("Setting expires " + dict["expires"]);
            }

            byte[] textBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dict));
            for (int i = 0; i < 16; i++) {
                textBytes[i] ^= initVectorBytes[i];
            }

            // Encrypt the string to an array of bytes
            byte[] encrypted = EncryptStringToBytesWithAES(textBytes, keyBytes, initVectorBytes);
            string encoded = Convert.ToBase64String(encrypted);
            return HttpUtility.UrlEncode(encoded);
        }
Example #30
0
 /// <summary>
 /// Хэширует текст
 /// </summary>
 /// <param name="phrase"></param>
 /// <returns></returns>
 public static string Sha1EncryptPassword(string phrase)
 {
     var encoder = new UTF8Encoding();
     var sha1Hasher = new SHA1CryptoServiceProvider();
     var hashedDataBytes = sha1Hasher.ComputeHash(encoder.GetBytes(phrase));
     return ByteArrayToString(hashedDataBytes);
 }
Example #31
0
 private byte[] GetPasswordHash()
 {
     var data = Encoding.ASCII.GetBytes(Password);
     SHA1 sha1 = new SHA1CryptoServiceProvider();
     var hashPassword = sha1.ComputeHash(data);
     return hashPassword;
 }
 // Slightly modified stackoverflow code for sha1
 public static string CalculateSHA1(string text)
 {
     Encoding enc = Encoding.GetEncoding(1252);
     byte[] buffer = enc.GetBytes(text);
     SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider();
     return BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "");
 }
Example #33
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);
 }
 public ActionResult Index()
 {
     Init();
     ViewData["timestamp"] = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
     Random random = new Random();
     ViewData["nonceStr"] = new string(
         Enumerable.Repeat("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 16)
                   .Select(s => s[random.Next(s.Length)])
                   .ToArray()); ;
     string weaTokenFetchUrl = string.Format(@"https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={0}", weAccessToken.AccessToken);
     if (jsTicket==null||!jsTicket.IsValid)
     {
         using (var webClient = new WebClient())
         {
             string response = webClient.DownloadString(weaTokenFetchUrl);
             jsTicket = JsonConvert.DeserializeObject<WEAJsApiTicket>(response);
         }
     }
     byte[] hashData = Encoding.Default.GetBytes(string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", jsTicket.Ticket, ViewData["nonceStr"].ToString(), ViewData["timestamp"].ToString(), Request.Url.AbsoluteUri));
     SHA1 sha = new SHA1CryptoServiceProvider();
     byte[] hashResult = sha.ComputeHash(hashData);
     string signature = BitConverter.ToString(hashResult).Replace("-", string.Empty).ToLower();
     ViewData["signature"] = signature;
     return View();
 }
Example #35
0
        /// <summary>
        /// Computes the hash value for the specified string.
        /// </summary>
        /// <param name="text">The text for the input data.</param>
        /// <returns>Hash value as a string.</returns>
        public string ComputeHash(string text)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] hash = sha1.ComputeHash(Encoding.Default.GetBytes(text));

            return this.BytesToString(hash);
        }
Example #36
0
        public static string EncripContra(string password)
        {
            SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();

            byte[] input = (new UnicodeEncoding()).GetBytes(password); byte[] hash = sha1.ComputeHash(input);
            return(Convert.ToBase64String(hash));
        }
Example #37
0
        public static String Sha1(String s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                    'a', 'b', 'c', 'd', 'e', 'f' };
            try
            {
                byte[] btInput = System.Text.Encoding.Default.GetBytes(s);
                SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();

                byte[] md = sha.ComputeHash(btInput);
                // 把密文转换成十六进制的字符串形式
                int j = md.Length;
                char[] str = new char[j * 2];
                int k = 0;
                for (int i = 0; i < j; i++)
                {
                    byte byte0 = md[i];
                    str[k++] = hexDigits[(int)(((byte)byte0) >> 4) & 0xf];
                    str[k++] = hexDigits[byte0 & 0xf];
                }
                return new string(str);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.StackTrace);
                return null;
            }
        }
Example #38
0
        /// <summary>
        /// Computes the hash for the specified Stream.
        /// </summary>
        /// <param name="stream">The stream for the input data.</param>
        /// <returns>Hash value as a string.</returns>
        public string ComputeHashFromStream(Stream stream)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] hash = sha1.ComputeHash(stream);

            return this.BytesToString(hash);
        }
Example #39
0
 public static string EncodePassword(string password)
 {
     using (SHA1CryptoServiceProvider Sha = new SHA1CryptoServiceProvider())
     {
         return Convert.ToBase64String(Sha.ComputeHash(Encoding.ASCII.GetBytes(password)));
     }
 }
Example #40
0
        private byte[] Sign(SHA1CryptoServiceProvider hash)
        {
            var formatter = new RSAPKCS1SignatureFormatter(_certificate.PrivateKey).
                Tap(it => it.SetHashAlgorithm("MD5"));

            return formatter.CreateSignature(hash);
        }
        public static RealmPacket CreateAuthResponse(String name, String password)
        {
            SHA1 sha = new SHA1CryptoServiceProvider();
            byte[] user_pass = System.Text.Encoding.UTF8.GetBytes(((name + ":" + password).ToCharArray()));
            byte[] hash = sha.ComputeHash(user_pass);
            byte[] salt = new byte[32];
            new Random().NextBytes(salt);
            byte[] result = new byte[hash.Length + salt.Length];
            hash.CopyTo(result, 0);
            salt.CopyTo(result, hash.Length);
            byte[] finalhash = sha.ComputeHash(result);

            byte[] rand = new byte[20];
            new Random().NextBytes(rand);
            //BigInteger int_a = new BigInteger(reverse(finalhash));
            //BigInteger int_b = new BigInteger(reverse(N));
            BigInteger int_c = new BigInteger(new Byte[] { 7 });
            BigInteger int_d = int_c.modPow(new BigInteger(reverse(finalhash)),new BigInteger(reverse(N)));

            BigInteger K = new BigInteger(new Byte[] { 3 });
            BigInteger temp = ((K * int_d) + int_c.modPow(new BigInteger(reverse(rand)), new BigInteger(reverse(N)))) % new BigInteger(reverse(N));

            RealmPacket response = new RealmPacket();
            response.opcode = RealmOpcode.RS_AUTH_LOGON_CHALLENGE;
            response.Data.Add(RealmData.RD_AUTH_ERROR, 0);
            response.Data.Add(RealmData.RD_AUTH_HASH, temp.getBytes());
            response.Data.Add(RealmData.RD_AUTH_SALT, salt);
            response.Data.Add(RealmData.RD_AUTH_N, N);
            return response;
        }
 public static string SHA1File(FileInfo fileInfo)
 {
     using (SHA1 sha1 = new SHA1CryptoServiceProvider())
     {
         return FileHash(fileInfo, sha1);
     }
 }
Example #43
0
        static void Main(string[] args)
        {
            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();

            Console.Write("Enter username: "******"Enter password: "******":" + password;

            byte[] temp2 = Encoding.ASCII.GetBytes(temp);

            sha.ComputeHash(temp2, 0, temp2.Length);

            string hash = String.Empty;

            for (int i = 0; i < sha.Hash.Length; i++)
            {
                hash += sha.Hash[i].ToString("X2");
            }

            Console.WriteLine("Hash: {0}", hash);
            Console.ReadKey();
        }
 /// <summary>
 /// 引用证书非对称加/解密RSA-公钥验签【OriginalString:原文;SignatureString:签名字符;pubkey_path:证书路径;CertificatePW:证书密码;SignType:签名摘要类型(1:MD5,2:SHA1)】
 /// </summary>
 public static bool CerRSAVerifySignature(string OriginalString, string SignatureString, string pubkey_path, string CertificatePW, int SignType)
 {
     byte[] OriginalByte = System.Text.Encoding.UTF8.GetBytes(OriginalString);
     byte[] SignatureByte = Convert.FromBase64String(SignatureString);
     X509Certificate2 x509_Cer1 = new X509Certificate2(pubkey_path, CertificatePW);
     RSACryptoServiceProvider rsapub = (RSACryptoServiceProvider)x509_Cer1.PublicKey.Key;
     rsapub.ImportCspBlob(rsapub.ExportCspBlob(false));
     RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsapub);
     byte[] HashData;
     switch (SignType)
     {
         case 1:
             f.SetHashAlgorithm("MD5");//摘要算法MD5
             MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
             HashData = md5.ComputeHash(OriginalByte);
             break;
         default:
             f.SetHashAlgorithm("SHA1");//摘要算法SHA1
             SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
             HashData = sha.ComputeHash(OriginalByte);
             break;
     }
     if (f.VerifySignature(HashData, SignatureByte))
     {
         return true;
     }
     else
     {
         return false;
     }
 }
Example #45
0
        //
        // internal static methods
        //

        // CMS TripleDES KeyWrap as described in "http://www.w3.org/2001/04/xmlenc#kw-tripledes"
        internal static byte[] TripleDESKeyWrapEncrypt (byte[] rgbKey, byte[] rgbWrappedKeyData) {
            // checksum the key
            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
            byte[] rgbCKS = sha.ComputeHash(rgbWrappedKeyData);

            // generate a random IV
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] rgbIV = new byte[8];
            rng.GetBytes(rgbIV);

            // rgbWKCS = rgbWrappedKeyData | (first 8 bytes of the hash)
            byte[] rgbWKCKS = new byte[rgbWrappedKeyData.Length + 8];
            TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
            // Don't add padding, use CBC mode: for example, a 192 bits key will yield 40 bytes of encrypted data
            tripleDES.Padding = PaddingMode.None;
            ICryptoTransform enc1 = tripleDES.CreateEncryptor(rgbKey, rgbIV);
            Buffer.BlockCopy(rgbWrappedKeyData, 0, rgbWKCKS, 0, rgbWrappedKeyData.Length);
            Buffer.BlockCopy(rgbCKS, 0, rgbWKCKS, rgbWrappedKeyData.Length, 8);
            byte[] temp1 = enc1.TransformFinalBlock(rgbWKCKS, 0, rgbWKCKS.Length);
            byte[] temp2 = new byte[rgbIV.Length + temp1.Length];
            Buffer.BlockCopy(rgbIV, 0, temp2, 0, rgbIV.Length);
            Buffer.BlockCopy(temp1, 0, temp2, rgbIV.Length, temp1.Length);
            // temp2 = REV (rgbIV | E_k(rgbWrappedKeyData | rgbCKS))
            Array.Reverse(temp2);

            ICryptoTransform enc2 = tripleDES.CreateEncryptor(rgbKey, s_rgbTripleDES_KW_IV);
            return enc2.TransformFinalBlock(temp2, 0, temp2.Length);
        }
Example #46
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());
        }
Example #47
0
        private static string CalculateSha1(string text, Encoding enc)
        {
            byte[] buffer = enc.GetBytes(text);
            System.Security.Cryptography.SHA1CryptoServiceProvider cryptoTransformSha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            string hash = BitConverter.ToString(cryptoTransformSha1.ComputeHash(buffer)).Replace("-", "");

            return(hash);
        }
Example #48
0
    public static string Sha1Sum2(string str)
    {
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        byte[] bytes = encoding.GetBytes(str);
        var    sha   = new System.Security.Cryptography.SHA1CryptoServiceProvider();

        return(System.BitConverter.ToString(sha.ComputeHash(bytes)));
    }
Example #49
0
 public static string HashStringSHA1(string textToHash)
 {
     System.Security.Cryptography.SHA1CryptoServiceProvider SHA1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(textToHash);
     byte[] byteHash  = SHA1.ComputeHash(byteValue);
     SHA1.Clear();
     return(Convert.ToBase64String(byteHash));
 }
Example #50
0
        public string SHA1Encrypt(string normalTxt)
        {
            var bytes        = Encoding.Default.GetBytes(normalTxt);
            var SHA          = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            var encryptbytes = SHA.ComputeHash(bytes);

            return(Convert.ToBase64String(encryptbytes));
        }
    public static Guid StringToGuid(string str)
    {
        var stringbytes = Encoding.ASCII.GetBytes(str);
        var hashedBytes = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(stringbytes);

        Array.Resize(ref hashedBytes, 16);
        return(new Guid(hashedBytes));
    }
Example #52
0
    public static string SHA1(byte[] data)
    {
        //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(text, "SHA1");
        System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
        byte[] result = sha1.ComputeHash(data);//得到哈希值
        string hash   = BitConverter.ToString(result).Replace("-", "");

        return(hash);
    }
Example #53
0
 public static string sign(string content, string privateKey, string input_charset)
 {
     System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(input_charset);
     byte[] bytes = encoding.GetBytes(content);
     System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = RSAFromPkcs8.DecodePemPrivateKey(privateKey);
     System.Security.Cryptography.SHA1 halg = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] inArray = rSACryptoServiceProvider.SignData(bytes, halg);
     return(System.Convert.ToBase64String(inArray));
 }
Example #54
0
    public static string get_hash(byte[] data)
    {
        string result;

        using (System.Security.Cryptography.SHA1CryptoServiceProvider sha = new System.Security.Cryptography.SHA1CryptoServiceProvider())
            result = Convert.ToBase64String(sha.ComputeHash(data));

        return(result);
    }
 public static Guid ToGuid(string src)
 {
     byte[] stringbytes = Encoding.UTF8.GetBytes(src);
     byte[] hashedBytes = new System.Security.Cryptography
                          .SHA1CryptoServiceProvider()
                          .ComputeHash(stringbytes);
     Array.Resize(ref hashedBytes, 16);
     return(new Guid(hashedBytes));
 }
Example #56
0
 //Sha1 - özəl
 public static string SHA1Special(this string Value)
 {
     byte[] result;
     System.Security.Cryptography.SHA1 ShaEncrp = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     Value = String.Format("{0}{1}{0}", "CSAASADM", Value);
     byte[] buffer = new byte[Value.Length];
     buffer = System.Text.Encoding.UTF8.GetBytes(Value);
     result = ShaEncrp.ComputeHash(buffer);
     return(Convert.ToBase64String(result));
 }
Example #57
0
        ///
        /// SHA1 加密(不可逆加密)
        ///
        /// 要加密的原始字串
        ///
        public static string SHA1Encrypt(string pass)
        {
            System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] bytResult = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(pass));
            sha1.Clear();
            string strResult = BitConverter.ToString(bytResult);

            strResult = strResult.Replace("-", "");
            return(strResult);
        }
Example #58
0
    public string HashString(char[] chData, byte[] byData)
    {
        for (int i = 0; i < chData.Length; i++)
        {
            byData[i] = (byte)chData[i];
        }

        System.Security.Cryptography.SHA1 sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
        return(HexStringFromBytes(sha1.ComputeHash(byData)));
    }
Example #59
0
        private static string Get_SHA1(string strSource)
        {
            System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] bytResult = sha.ComputeHash(Encoding.Default.GetBytes(strSource));
            //转换成字符串,32位
            string strResult = BitConverter.ToString(bytResult);

            //BitConverter转换出来的字符串会在每个字符中间产生一个分隔符,需要去除掉
            strResult = strResult.Replace("-", "");
            return(strResult);
        }
Example #60
0
 public static bool verify(string content, string signedString, string publicKey, string input_charset)
 {
     System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(input_charset);
     byte[] bytes     = encoding.GetBytes(content);
     byte[] signature = System.Convert.FromBase64String(signedString);
     System.Security.Cryptography.RSAParameters            parameters = RSAFromPkcs8.ConvertFromPublicKey(publicKey);
     System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider();
     rSACryptoServiceProvider.ImportParameters(parameters);
     System.Security.Cryptography.SHA1 halg = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     return(rSACryptoServiceProvider.VerifyData(bytes, halg, signature));
 }