Exemple #1
0
 /// <summary>
 /// Main constructor of the Tag. This reads information from the given filename and initializes all fields of the tag.
 /// It's important to know that this constructor has a considerable weight in term of processor time because it calculates two SHA1 hash:
 /// one for the entire file and one for the relevant tag information.
 /// </summary>
 /// <param name="filename">Filename from whom extract the information for the tag</param>
 public CompleteTag(string filename)
 {
     byte[] retVal;
     SHA1 crypto = new SHA1CryptoServiceProvider();
     using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
     {
     retVal = crypto.ComputeHash(file);
     file.Close();
     }
     StringBuilder sb = new StringBuilder();
     for (int i = 0; i < retVal.Length; i++)
     {
     sb.Append(retVal[i].ToString("x2"));
     }
     this.FileHash= sb.ToString();
     this.FillTag(filename);
     System.Text.UTF8Encoding enc= new UTF8Encoding();
     byte[] tHashByte = crypto.ComputeHash(enc.GetBytes(this.contentString()));
     crypto.ComputeHash(tHashByte);
     sb.Clear();
     for (int i = 0; i < tHashByte.Length; i++)
     {
     sb.Append(tHashByte[i].ToString("x2"));
     }
     this.TagHash = sb.ToString();
 }
    public static void Load(string embeddedResource, string fileName)
    {
        if (dic == null)
          dic = new Dictionary<string, Assembly>();

        byte[] ba = null;
        Assembly asm = null
          , curAsm = Assembly.GetExecutingAssembly();

        using (Stream stm = curAsm.GetManifestResourceStream(embeddedResource)) {
          // Either the file doesn't exist or it isn't marked as an embedded resource
          if (stm == null)
        throw new Exception(embeddedResource + " is not found in Embedded Resources.");

          // Get byte[] from the embedded resource
          ba = new byte[(int)stm.Length];
          stm.Read(ba, 0, (int)stm.Length);
          try {
        asm = Assembly.Load(ba);

        // Add the assembly/dll into the dictionary
        dic.Add(asm.FullName, asm);
        return;
          } catch {
        // Purposely do nothing
        // Unmanaged dll or assembly cannot be loaded directly from byte[]
        // Let the process fall through for next part
          }
        }

        bool fileOk = false;
        string tempFile = "";

        using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) {
          string fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty);
          tempFile = Path.GetTempPath() + fileName;

          if (File.Exists(tempFile)) {
        byte[] bb = File.ReadAllBytes(tempFile);
        string fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).Replace("-", string.Empty);

        fileOk = (fileHash == fileHash2);
          }
          else {
        fileOk = false;
          }
        }

        if (!fileOk) {
          System.IO.File.WriteAllBytes(tempFile, ba);
        }

        asm = Assembly.LoadFile(tempFile);

        dic.Add(asm.FullName, asm);
    }
    protected void LoginPanel_Authenticate(object sender, AuthenticateEventArgs e)
    {
        //code to authenticate user
        int userId = 0;
        System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
        byte[] buffer = encoder.GetBytes(LoginPanel.Password);
        SHA1 passwordSHA = new SHA1CryptoServiceProvider();
        string hash = BitConverter.ToString(passwordSHA.ComputeHash(buffer)).Replace("-", "");
        try {

            userId = int.Parse(LoginPanel.UserName);
            Student loggedin = Students.getAStudent(userId);

            if ((hash == loggedin.PassHash.ToUpper())) {
                e.Authenticated = true;
            }
        } catch (NullReferenceException exc) {
            System.Diagnostics.Trace.WriteLine(exc);
            Staff loggedin = StaffList.getAStaff(userId);
            if (hash == loggedin.PassHash.ToUpper()) {
                e.Authenticated = true;
            }
            Session.Add("UserName", userId);
        } catch (Exception exc) {
            System.Diagnostics.Trace.WriteLine(exc);
            e.Authenticated = false;
        }
    }
	public static int Main(string[] args)
	{
		try{
		Console.WriteLine("! MakeRes is using .NET version: " + Environment.Version.ToString());
		ResourceWriter rw = new ResourceWriter(args[0] + ".resources");
		for(int i = 1; i < args.Length; i = i + 2)
		{
			using(FileStream fs = File.OpenRead(args[i + 1]))
			{
				byte[] buffer = new byte[fs.Length];
				fs.Read(buffer, 0, buffer.Length);
				Console.WriteLine("ID = " + args[i]);
				rw.AddResource(args[i], buffer);
				fs.Close();
				SHA1 sha = new SHA1CryptoServiceProvider();
				byte[] result = sha.ComputeHash(buffer);
				WriteHash(args[0] + "."+ args[i], result);
			}
		}
		rw.Close();
	}catch(Exception ex)
	{
			Console.WriteLine("# MareRes Error: " + ex.Message + "\r\n" +  ex.StackTrace);
			return 1;
		}
		return 0;
	}
    public void In(
      [FriendlyName("Key", "The string to be used to check against the provided SHA1 hash.")]
      string Key,
      
      [FriendlyName("SHA1 Hash", "The SHA1 Hash to check the key against.")]
      string Hash
      )
    {
        if (Key != "" && Hash != "")
          {
         UTF8Encoding ue = new UTF8Encoding();
         byte[] bytes = ue.GetBytes(Key);

         // encrypt bytes
         SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
         byte[] hashBytes = sha1.ComputeHash(bytes);

         // Convert the encrypted bytes back to a string (base 16)
         string tmpHash = "";

         for (int i = 0; i < hashBytes.Length; i++)
         {
            tmpHash += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
         }

         string finalHash = tmpHash.PadLeft(32, '0');

         if (finalHash == Hash)
         {
            m_GoodHash = true;
         }
          }
    }
    public void In(
      [FriendlyName("Key", "The string to be used to generate the hash from.")]
      string Key,
      
      [FriendlyName("SHA1 Hash", "The SHA1 Hash generated by the Key.")]
      out string Hash
      )
    {
        if (Key != "")
          {
         UTF8Encoding ue = new UTF8Encoding();
         byte[] bytes = ue.GetBytes(Key);

         // encrypt bytes
         SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
         byte[] hashBytes = sha1.ComputeHash(bytes);

         // Convert the encrypted bytes back to a string (base 16)
         string tmpHash = "";

         for (int i = 0; i < hashBytes.Length; i++)
         {
            tmpHash += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
         }

         Hash = tmpHash.PadLeft(32, '0');
          }
          else
          {
         uScriptDebug.Log("[Generate SHA1 Hash] The Key provided was empty, returning an empty string for the SHA1 Hash.", uScriptDebug.Type.Warning);
         Hash = "";
          }
    }
    /// <summary>
    /// Gets the SHA1 hash from file.
    /// Adapted from https://stackoverflow.com/a/16318156/1460422
    /// </summary>
    /// <param name="fileName">The filename to hash.</param>
    /// <returns>The SHA1 hash from file.</returns>
    static string GetSHA1HashFromFile(string fileName)
    {
        FileStream file = new FileStream(fileName, FileMode.Open);
        SHA1 sha1 = new SHA1CryptoServiceProvider();
        byte[] byteHash = sha1.ComputeHash(file);
        file.Close();

        StringBuilder hashString = new StringBuilder();
        for (int i = 0; i < byteHash.Length; i++)
            hashString.Append(byteHash[i].ToString("x2"));
        return hashString.ToString();
    }
Exemple #8
0
 void Start()
 {
     if (Application.platform == RuntimePlatform.Android) {
         System.IO.FileStream fs = new System.IO.FileStream (
             Application.dataPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
         byte[] bs = new byte[fs.Length];
         fs.Read (bs, 0, bs.Length);
         fs.Close ();
         SHA1 sha = new SHA1CryptoServiceProvider ();
         byte[] hashBytes = sha.ComputeHash (bs);
         systemcode = System.Convert.ToBase64String (hashBytes);
     }
 }
        private void Verify(string rawText, string expected)
        {
            byte[] inputBytes = ByteUtils.AsciiBytes(rawText);
            byte[] expectedBytes = ByteUtils.HexToByteArray(expected);

            using (var hash = new SHA1CryptoServiceProvider())
            {
                Assert.True(hash.HashSize > 0);
                byte[] actual = hash.ComputeHash(inputBytes, 0, inputBytes.Length);

                Assert.Equal(expectedBytes, actual);

                actual = hash.Hash;
                Assert.Equal(expectedBytes, actual);
            }
        }
    public static void OnPostProcessBuild(BuildTarget target, string path)
    {
        // Check for official Unity SDK presence
        try
        {
            Assembly assembly = Assembly.Load("IFacebook");
            Type type = Type.GetType("Facebook.FBBuildVersionAttribute,IFacebook");

            FieldInfo sdkVersionField = type.GetField("SDKVersion");
            string sdkVersion = sdkVersionField.GetValue(null).ToString();

            object[] buildVersionAttributes = assembly.GetCustomAttributes(type, false);
            string buildVersion = "N/A";
            foreach(object attribute in buildVersionAttributes)
            {
                buildVersion = attribute.ToString();
            }
            Debug.Log("Carrot detected Unity Facebook SDK Version: " + sdkVersion + " build: " + buildVersion);

            // If needed apply fix-up to iOS code
            if(target == BuildTarget.iPhone)
            {
                string fullPath = Path.Combine(Application.dataPath, "Facebook/Editor/iOS/FbUnityInterface.mm");
                string data = Load(fullPath);

                string hash = null;
                using(var cryptoProvider = new SHA1CryptoServiceProvider())
                {
                    byte[] bytes = new byte[data.Length * sizeof(char)];
                    System.Buffer.BlockCopy(data.ToCharArray(), 0, bytes, 0, bytes.Length);
                    hash = BitConverter.ToString(cryptoProvider.ComputeHash(bytes)).Replace("-", String.Empty);
                }

                // Build 130827.e8d7fe03ac79388
                if(string.Compare(hash, "D36DE7E5867FE51D68DBF53FED8C4B01FEF1F19E", true) == 0)
                {
                    data = data.Replace("if (self.session == nil || self.session.state != FBSessionStateCreated) ", "");
                    data = data.Replace("defaultAudience:FBSessionDefaultAudienceNone", "defaultAudience:FBSessionDefaultAudienceFriends");
                    Save(fullPath, data);
                }
            }
        }
        catch(Exception e)
        {
            if(e == null) Debug.Log("Ignore this.");
        }
    }
Exemple #11
0
    public static string TableToSHA(DataTable table)
    {
        // Serialize the table
        table.TableName = "poll";
        DataContractSerializer serializer = new DataContractSerializer(typeof(DataTable));
        MemoryStream memoryStream = new MemoryStream();
        XmlWriter writer = XmlDictionaryWriter.CreateBinaryWriter(memoryStream);
        serializer.WriteObject(memoryStream, table);
        byte[] serializedData = memoryStream.ToArray();

        // Calculte the serialized data's hash value
        SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider();
        byte[] hash = SHA.ComputeHash(serializedData);

        // Convert the hash to a base 64 string
        return Convert.ToBase64String(hash);
    }
    protected void SubmitButton_Click1(object sender, EventArgs e)
    {
        string username = TextBoxUN.Text;
        string password = TextBoxPW.Text + TextBoxUN.Text;
        HashAlgorithm mhash = new SHA1CryptoServiceProvider();
        byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(password);
        byte[] bytHash = mhash.ComputeHash(bytValue);
        mhash.Clear();
        password = Convert.ToBase64String(bytHash);

        string fullname = TextBoxFN.Text;
        string emailid = TextBoxEID.Text;

        String constr = Session["connection"].ToString();
        OdbcConnection cn = new OdbcConnection(constr);
        cn.Open();

        if (IsPostBack)
        {
            Response.Write("You have successfully completed registration");
            string sql = "insert into userdata values ('" + username + "','" + password + "','"+ fullname + "','"+emailid+"');";
            OdbcCommand cmd = new OdbcCommand(sql, cn);

            try
            {
                cmd.ExecuteNonQuery();
            }

            finally
            {
                cn.Close();
                cn.Dispose();

            }

            SubmitButton.Enabled = false;
            Response.Redirect("HomePage.aspx");

        }
    }
Exemple #13
0
    /// <summary>
    /// 获取string类字符串的的十六进制大写SHA-1
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string getSHA1(string str)
    {
        if (!String.IsNullOrEmpty(str))
        {
            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();

            //将mystr转换成byte[]
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(str);

            //Hash运算
            sha.ComputeHash(dataToHash);

            //转换为 string
            string hash = BitConverter.ToString(sha.Hash).Replace("-", "");
            return hash;
        }
        else
        {
            return string.Empty;
        }
    }
Exemple #14
0
        /// <summary>
        ///开发者在web页面使用钉钉容器提供的jsapi时,需要验证调用权限,并以参数signature标识合法性
        ///签名生成的规则:
        ///List keyArray = sort(noncestr, timestamp, jsapi_ticket, url);
        /// String str = assemble(keyArray);
        ///signature = sha1(str);
        /// </summary>
        /// <param name="noncestr">随机字符串,自己随便填写即可</param>
        /// <param name="sTimeStamp">当前时间戳,具体值为当前时间到1970年1月1号的秒数</param>
        /// <param name="jsapi_ticket">获取的jsapi_ticket</param>
        /// <param name="url">当前网页的URL,不包含#及其后面部分</param>
        /// <param name="signature">生成的签名</param>
        /// <returns>0 成功,2 失败</returns>
        public static int GenSigurate(string noncestr, string sTimeStamp, string jsapi_ticket, string url, ref string signature)
        {
            //例如:
            //noncestr = Zn4zmLFKD0wzilzM
            //jsapi_ticket = mS5k98fdkdgDKxkXGEs8LORVREiweeWETE40P37wkidkfksDSKDJFD5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcKIDU8l
            //timestamp = 1414588745
            //url = http://open.dingtalk.com

            //步骤1.sort()含义为对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)
            //注意,此处是是按照【字段名】的ASCII字典序,而不是参数值的字典序(这个细节折磨我很久了)
            //0:jsapi_ticket 1:noncestr 2:timestamp 3:url;

            //步骤2.assemble()含义为根据步骤1中获的参数字段的顺序,使用URL键值对的格式(即key1 = value1 & key2 = value2…)拼接成字符串
            //string assemble = "jsapi_ticket=3fOo5UfWhmvRKnRGMmm6cWwmIxDMCnniyVYL2fqcz1I4GNU4054IOlif0dZjDaXUScEjoOnJWOVrdwTCkYrwSl&noncestr=CUMT1987wlrrlw&timestamp=1461565921&url=https://jackwangcumt.github.io/home.html";
            string assemble = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", jsapi_ticket, noncestr, sTimeStamp, url);
            //步骤2.sha1()的含义为对在步骤2拼接好的字符串进行sha1加密。
            SHA1          sha;
            ASCIIEncoding enc;
            string        hash = "";

            try
            {
                sha = new SHA1CryptoServiceProvider();
                enc = new ASCIIEncoding();
                byte[] dataToHash = enc.GetBytes(assemble);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                hash = BitConverter.ToString(dataHashed).Replace("-", "");
                hash = hash.ToLower();
            }
            catch (Exception)
            {
                return(2);
            }
            signature = hash;
            return(0);
        }
Exemple #15
0
        private void ParseBuffer()
        {
            int protoBufLength = (FileContent[0] << 24) | (FileContent[1] << 16) | (FileContent[2] << 8) | FileContent[3];

            if (protoBufLength > 0x10000)
            {
                throw new InvalidDataException();
            }
            byte[] protoBuf      = new byte[protoBufLength];
            int    payloadStart  = protoBufLength + 4;
            int    payloadLength = FileContent.Length - payloadStart;

            byte[] payload = new byte[payloadLength];

            Array.Copy(FileContent, 4, protoBuf, 0, protoBufLength);
            Array.Copy(FileContent, protoBufLength + 4, payload, 0, payloadLength);


            var        coder  = new ProtoCoder();
            FileHeader header = coder.Deserialize <FileHeader>(protoBuf);

            var prov = new SHA1CryptoServiceProvider();
            var hash = prov.ComputeHash(payload);

            HashCorrect = true;
            if (!hash.SequenceEqual(header.Hash))
            {
                HashCorrect = false;
            }

            byte[] data = coder.Serialize(header);

            HeaderLength = data.Length;
            Audio        = payload;
            Header       = header;
        }
Exemple #16
0
        /// <summary>
        /// 验证签名方法
        /// </summary>
        /// <returns></returns>
        internal static string GenerateSignature(string token,
                                                 string timestamp, string nonce, string strEncrptyMsg)
        {
            var AL = new ArrayList {
                token, timestamp, nonce, strEncrptyMsg
            };

            AL.Sort(SingleInstance <DictionarySort> .Instance);

            var raw = new StringBuilder();

            foreach (var t in AL)
            {
                raw.Append(t);
            }

            using (SHA1 sha = new SHA1CryptoServiceProvider())
            {
                var dataToHash = Encoding.ASCII.GetBytes(raw.ToString());
                var dataHashed = sha.ComputeHash(dataToHash);

                return(BitConverter.ToString(dataHashed).Replace("-", "").ToLower());
            }
        }
    private string CalculateShaSignature()
    {
        string verySecretKey = SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".OgoneShaHandshake");

        List <string> paymentValuesAsString = new List <string>();

        foreach (string name in this._paymentValues)
        {
            if (!String.IsNullOrEmpty(this._paymentValues[name]))
            {
                paymentValuesAsString.Add(String.Format("{0}={1}{2}", name.ToUpper(), this._paymentValues[name], verySecretKey));
            }
        }

        string[] bitsAndPieces = paymentValuesAsString.ToArray();
        Array.Sort(bitsAndPieces);

        string toHash = String.Join(String.Empty, bitsAndPieces);

        byte[] buffer = Encoding.ASCII.GetBytes(toHash);
        SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider();

        return(BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", ""));
    }
Exemple #18
0
        public static string GetSha1Hash(FileStream fileStream)
        {
            SHA1 sha1Hasher = new SHA1CryptoServiceProvider();

            // This is one implementation of the abstract class SHA1.

            // Convert the input string to a byte array and compute the hash.
            //byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            byte[] data = sha1Hasher.ComputeHash(fileStream);

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return(sBuilder.ToString());
        }
Exemple #19
0
        public static string getAppCard(string card_id)
        {
            string        api_ticket = getKiwifastApiTicket2();// getApiTicket();
            DateTime      dt_start   = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            int           timestamp  = (int)(DateTime.Now - dt_start).TotalSeconds;
            List <string> lst        = new List <string>();

            lst.Add(api_ticket);
            lst.Add(timestamp.ToString());
            lst.Add(card_id);
            lst.Sort();
            string str = lst[0] + lst[1] + lst[2];

            byte[] str1 = Encoding.UTF8.GetBytes(str);
            SHA1   sha1 = new SHA1CryptoServiceProvider();

            byte[] buf = sha1.ComputeHash(str1);

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < buf.Length; i++)
            {
                sBuilder.Append(buf[i].ToString("x2"));
            }
            string signature = sBuilder.ToString();

            //string signature = BitConverter.ToString(buf).ToLower();
            //signature = signature.Replace("-", "");
            return(Obj2Json(new
            {
                card_id,
                timestamp,
                signature,
                cardExt = "{\"code\":\"\", \"openid\":\"\", \"timestamp\": \"" + timestamp.ToString() + "\", \"signature\": \"" + signature + "\"}"
            }));
        }
Exemple #20
0
        /// <summary>
        /// Generate a scrambled password for 4.1.0 using new passwords
        /// </summary>
        /// <param name="password">The password to scramble</param>
        /// <param name="seedBytes">The seedbytes used to scramble</param>
        /// <returns>Array of bytes containing the scrambled password</returns>
        public static byte[] Get410Password(string password, byte[] seedBytes)
        {
            SHA1 sha = new SHA1CryptoServiceProvider();

            // clean it and then digest it
            password = password.Replace(" ", "").Replace("\t", "");
            byte[] passBytes = System.Text.Encoding.Default.GetBytes(password);
            byte[] firstPass = sha.ComputeHash(passBytes);

            CryptoStream cs = new CryptoStream(Stream.Null, sha, CryptoStreamMode.Write);

            cs.Write(seedBytes, 0, 4);
            cs.Write(firstPass, 0, 20);
            cs.Close();
            byte[] secondPass = sha.Hash;

            byte[] scrambledBuff = new byte[20];
            XorScramble(seedBytes, 4, scrambledBuff, 0, secondPass, 20);

            byte[] finalBuff = new byte[20];
            XorScramble(scrambledBuff, 0, finalBuff, 0, firstPass, 20);

            return(finalBuff);
        }
        //xml格式公钥验签
        public static bool RSASignCheck(string data, string sign, string publicKey, string charset)
        {
            try
            {
                byte[] bt      = Encoding.GetEncoding(charset).GetBytes(data);
                var    sha1    = new SHA1CryptoServiceProvider();
                byte[] rgbHash = sha1.ComputeHash(bt);

                RSACryptoServiceProvider key = new RSACryptoServiceProvider();
                FromXmlString(key, publicKey);
                RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
                deformatter.SetHashAlgorithm("SHA1");
                byte[] rgbSignature = Convert.FromBase64String(sign);
                if (deformatter.VerifySignature(rgbHash, rgbSignature))
                {
                    return(true);
                }
                return(false);
            }
            catch (Exception ex)
            {
                throw new AopException("您使用的公钥格式错误,请检查RSA公钥配置" + ",charset = " + charset);
            }
        }
    public static string Build(string input)
    {
        using (var provider = new SHA1CryptoServiceProvider())
        {
            var inputBytes = Encoding.Default.GetBytes(input);
            var hashBytes  = provider.ComputeHash(inputBytes);

            var hashBuilder = new StringBuilder(string.Join("", hashBytes.Select(x => x.ToString("x2"))));
            foreach (var delimeterIndex in new[]
            {
                5,
                11,
                17,
                23,
                29,
                35,
                41
            })
            {
                hashBuilder.Insert(delimeterIndex, "-");
            }
            return(hashBuilder.ToString());
        }
    }
Exemple #23
0
        public static int GenerateHashInt(Object sourceObject)
        {
            int hashInt;

            using (var sha1 = new SHA1CryptoServiceProvider())
            {
                //Catch unuseful parameter values
                if (sourceObject == null)
                {
                    throw new ArgumentNullException("Null as parameter is not allowed");
                }
                else
                {
                    //We determine if the passed object is really serializable.
                    try
                    {
                        //Now we begin to do the real work.

                        var array     = sourceObject.ToByteArray();
                        var hashBytes = sha1.ComputeHash(sourceObject.ToByteArray());
                        var hashInt1  = BitConverter.ToInt32(hashBytes, 0);
                        var hashInt2  = BitConverter.ToInt32(hashBytes, 4);
                        var hashInt3  = BitConverter.ToInt32(hashBytes, 8);
                        var hashInt4  = BitConverter.ToInt32(hashBytes, 12);

                        hashInt = (((hashInt1 & hashInt2) ^ hashInt3) | hashInt4);

                        return(hashInt);
                    }
                    catch (AmbiguousMatchException ame)
                    {
                        throw new ApplicationException("Could not definitely decide if object is serializable. Message:" + ame.Message);
                    }
                }
            }
        }
Exemple #24
0
 /// <summary>
 /// 签名算法
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static string Encrypt(string str)
 {
     if (string.IsNullOrEmpty(str))
     {
         throw new ArgumentNullException(str);
     }
     try
     {
         //建立SHA1对象
         SHA1 sha = new SHA1CryptoServiceProvider();
         //将mystr转换成byte[]
         var enc        = new ASCIIEncoding();
         var dataToHash = enc.GetBytes(str);
         //Hash运算
         var dataHashed = sha.ComputeHash(dataToHash);
         //将运算结果转换成string
         var hash = BitConverter.ToString(dataHashed).Replace("-", "");
         return(hash);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemple #25
0
        public string SHA1_Encoding(string s)
        {
            try
            {
                String strData = "";

                byte[] plainTextBytes = Ecd_.GetBytes(s);

                HashAlgorithm Hash;
                Hash = new SHA1CryptoServiceProvider();

                byte[] hashed = Hash.ComputeHash(plainTextBytes);
                for (int i = 0; i < hashed.Length; ++i)
                {
                    strData += string.Format("{0:x2}", hashed[i]);
                }

                //MD 5 변환
                return(strData);
            }
            catch (Exception) { }

            return(null);
        }
        private static string GetSignature(HttpRequestMessage request, byte[] body, string nonce, string timestamp, string consumerKey, string consumerSecret)
        {
            var parameters = new NameValueCollection();

            parameters.AddParameter(OAuthConstants.ConsumerKeyParameter, consumerKey);
            parameters.AddParameter(OAuthConstants.NonceParameter, nonce);
            parameters.AddParameter(OAuthConstants.SignatureMethodParameter, OAuthConstants.SignatureMethodHmacSha1);
            parameters.AddParameter(OAuthConstants.VersionParameter, OAuthConstants.Version10);
            parameters.AddParameter(OAuthConstants.TimestampParameter, timestamp);

            // Calculate the body hash
            using (var sha1 = new SHA1CryptoServiceProvider())
            {
                var hash   = sha1.ComputeHash(body);
                var hash64 = Convert.ToBase64String(hash);
                parameters.AddParameter(OAuthConstants.BodyHashParameter, hash64);
            }

            // Calculate the signature
            var signature = OAuthUtility.GenerateSignature(request.Method.ToString(), request.RequestUri, parameters,
                                                           consumerSecret);

            return(signature);
        }
Exemple #27
0
        private static byte[] GenerateAuthResponsePacket(byte[] challengeBytes, string password)
        {
            //convert the password to ascii
            var encoding = new System.Text.ASCIIEncoding();
            var asciiPW  = encoding.GetBytes(password);

            //add the two ranges together and compute the hash
            var authString = new AppendableByteArray(asciiPW.Length + challengeBytes.Length);

            authString.Append(asciiPW);
            authString.Append(challengeBytes);

            var sha = new SHA1CryptoServiceProvider();

            byte[] challengeHash = sha.ComputeHash(authString.data);

            //copy the results to the raw packet data
            var rawMessageData = new AppendableByteArray(RESPONSE_PACKET_MESSAGE_SIZE);

            rawMessageData.Append(RESPONSE_PACKET_IDENTIFIER);
            rawMessageData.Append(encoding.GetBytes(Util.HashToHex(challengeHash)));

            return(rawMessageData.data);
        }
Exemple #28
0
        public bool GetFileInfo(string format, byte[] blob, out string MetaData)
        {
            var  compedObj = new CompEdObj();
            bool retval    = false;

            try
            {
                switch (format.ToUpper())
                {
                case "P7M":
                    compedObj.GetFileInfo(true, blob, out MetaData);
                    break;

                case "P7X":
                    compedObj.GetFileInfo(false, blob, out MetaData);
                    break;

                default:
                    MetaData = "<?xml version=\"1.0\" ?><file name=\"\" description=\"\"";
                    break;
                }

                SHA1   sha     = new SHA1CryptoServiceProvider();
                byte[] docHash = sha.ComputeHash(blob);

                MetaData += " containerHash=\"" + CompEdObj.ByteToHex(docHash) + "\"></file>";

                retval = true;
            }
            finally
            {
                compedObj.Dispose();
            }

            return(retval);
        }
        private void BtnDangKyDB_Click(object sender, RoutedEventArgs e)
        {
            var TaiKhoanDangKy = txtDkyTaiKhoan.Text;
            var PassDangKy     = txtDkyPass.Password;

            if (dbConnect.GetStringBySql("select USER from _USERS  where USERNAME  ='******'").Equals(""))
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

                byte[] bs = System.Text.Encoding.UTF8.GetBytes(PassDangKy);
                bs = sha1.ComputeHash(bs);
                System.Text.StringBuilder s = new System.Text.StringBuilder();
                foreach (byte b in bs)
                {
                    s.Append(b.ToString("x2"));
                }
                PassDangKy = s.ToString();

                string sqlInset = "insert into _USERS values ('" + TaiKhoanDangKy + "','" + PassDangKy + "', '" + txtTenDau.Text + "', '" + txtTenCuoi.Text + "')";
                dbConnect.UpdateTableBySql(sqlInset);


                MainWindow.ftp.createDirectory(TaiKhoanDangKy);


                DialogResult result = System.Windows.Forms.MessageBox.Show("Đăng ký thành công", "Thông báo", MessageBoxButtons.OK);
                if (result == DialogResult.Yes)
                {
                    Switcher.Switch(new ucLogin());
                }
            }
            else
            {
                System.Windows.MessageBox.Show("Tài khoản đã tồn tại", "Thông báo");
            }
        }
Exemple #30
0
        private string generarSHA1(string cadena) //encripta la contraseña de registro
        {
            UTF8Encoding enc = new UTF8Encoding();

            byte[] data = enc.GetBytes(cadena);
            byte[] result;

            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();

            result = sha.ComputeHash(data);

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < result.Length; i++)
            {
                if (result[i] < 16)
                {
                    sb.Append("0");
                }
                sb.Append(result[i].ToString("x"));
            }

            return(sb.ToString());
        }
Exemple #31
0
        public static string GenarateSinature(string raw)
        {
            string        sMsgSignature = "";
            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)
            {
                throw;
                //return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error;
            }
            sMsgSignature = hash;
            return(sMsgSignature);
        }
Exemple #32
0
        /// <summary>
        /// 验证许可证是否有效。
        /// </summary>
        /// <returns>有效返回True,否则返回False。</returns>
        public static bool Verify()
        {
            try
            {
                var serializer = new JavaScriptSerializer();
                var dic        = (Dictionary <string, object>)serializer.DeserializeObject(DecryptTextFromFile());

                var  licenseData = new UnicodeEncoding().GetBytes(dic["LicenseData"].ToString());
                SHA1 sha         = new SHA1CryptoServiceProvider();
                var  hashValue   = sha.ComputeHash(licenseData);
                var  signedData  = ObjectToByteArray(dic["SignedData"]);

                if (DsaVerifyHash(hashValue, signedData, "SHA1", PublicKeyString))
                {
                    return(true);
                }

                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemple #33
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);
        }
        /// <summary>
        /// 计算加密值
        /// </summary>
        /// <param name="sToken">Token值</param>
        /// <param name="sTimeStamp">时间戳</param>
        /// <param name="sNonce">nonce随机参数</param>
        /// <param name="sMsgEncrypt">加密私钥</param>
        /// <param name="sMsgSignature">返回计算得出的签名</param>
        /// <returns></returns>
        private static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, ref string sMsgSignature)
        {
            ArrayList al = new ArrayList {
                sToken, sTimeStamp, sNonce
            };

            if (!string.IsNullOrEmpty(sMsgEncrypt))
            {
                al.Add(sMsgEncrypt);
            }
            al.Sort(new DictionarySort());
            string raw = "";

            for (int i = 0; i < al.Count; ++i)
            {
                raw += al[i];
            }

            string hash;

            try
            {
                SHA1   sha        = new SHA1CryptoServiceProvider();
                var    enc        = new ASCIIEncoding();
                byte[] dataToHash = enc.GetBytes(raw);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                hash = BitConverter.ToString(dataHashed).Replace("-", "");
                hash = hash.ToLower();
            }
            catch (Exception)
            {
                return(-1);
            }
            sMsgSignature = hash;
            return(0);
        }
        public ActionResult Authorization(UnknownUser unUser)
        {
            User user = db.Users.FirstOrDefault(u => (u.Email == unUser.Email));

            if (user == null)
            {
                return(ErrorView("Пользователь с такой почтой не найден"));
            }

            byte[] inputPas = Encoding.Unicode.GetBytes(unUser.Password);
            SHA1   sha      = new SHA1CryptoServiceProvider();

            inputPas = sha.ComputeHash(inputPas);
            if (!inputPas.SequenceEqual(user.Password))
            {
                return(ErrorView("Вы ввели неверный пароль"));
            }

            Session["User"]      = user;
            ViewBag.User         = user;
            ViewBag.SelectedUser = user;

            return(View("PersonalArea"));
        }
Exemple #36
0
 private static string SHA1Crypt(string txt, Encoding encoding = null)
 {
     try
     {
         encoding = encoding ?? Encoding.UTF8;
         if (string.IsNullOrEmpty(txt))
         {
             throw new Exception("原文不能为空!");
         }
         SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
         byte[] org    = encoding.GetBytes(txt);
         byte[] output = sha1.ComputeHash(org);
         string retStr = "";
         for (int i = 0; i < output.Length; i++)
         {
             retStr += output[i].ToString("x2");
         }
         return(retStr);
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemple #37
0
        private static WeChatEncryptionErrorCode GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, ref string sMsgSignature)
        {
            ArrayList AL = new ArrayList
            {
                sToken,
                sTimeStamp,
                sNonce,
                sMsgEncrypt
            };

            AL.Sort(new DictionarySort());
            string raw = "";

            for (int i = 0; i < AL.Count; ++i)
            {
                raw += AL[i];
            }

            string        hash = "";
            SHA1          sha  = new SHA1CryptoServiceProvider();
            ASCIIEncoding enc  = new ASCIIEncoding();

            try
            {
                byte[] dataToHash = enc.GetBytes(raw);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                hash = BitConverter.ToString(dataHashed).Replace("-", "");
                hash = hash.ToLower();
            }
            catch (Exception)
            {
                return(WeChatEncryptionErrorCode.ComputeSignature_Error);
            }
            sMsgSignature = hash;
            return(WeChatEncryptionErrorCode.OK);
        }
        private void BeginOperation()
        {
            if (_viewModel.Results.Count > 0)
            {
                _viewModel.Results = new List <string>();
            }

            // if the MD5 option is selected
            if (_viewModel.MD5Selected)
            {
                foreach (string source in _viewModel.SourceFiles)
                {
                    using (MD5 _md5 = MD5.Create())
                    {
                        using (var stream = File.OpenRead(source))
                        {
                            _viewModel.Results.Add(BitConverter.ToString(_md5.ComputeHash(stream)).Replace("-", "‌​").ToLower());
                        }
                    }
                }
            }

            if (_viewModel.SHA1Selected)
            {
                foreach (string source in _viewModel.SourceFiles)
                {
                    using (var cryptoProvider = new SHA1CryptoServiceProvider())
                    {
                        using (var stream = File.OpenRead(source))
                        {
                            _viewModel.Results.Add(BitConverter.ToString(cryptoProvider.ComputeHash(stream)).Replace("-", "‌​").ToLower());
                        }
                    }
                }
            }
        }
Exemple #39
0
        public static bool ExistPassword(string login, string N, string password)
        {
            string        connectionStr = "Data Source=localhost;Initial Catalog=server;Integrated Security=True";
            SqlConnection dbConnection  = new SqlConnection(connectionStr);

            dbConnection.Open();
            String        command = "SELECT Password FROM Users AS l WHERE l.Login = '******'";
            SqlCommand    cmnd    = new SqlCommand(command, dbConnection);
            SqlDataReader dr      = cmnd.ExecuteReader();

            //if (dr["Password"].ToString() == password)
            //{ return true; }
            //else return false;
            dr.Read();

            string OnTest = N + dr["Password"].ToString();
            SHA1   sha    = new SHA1CryptoServiceProvider();

            byte[] passwdbyteforhash = Encoding.Unicode.GetBytes(OnTest);
            byte[] passwbeforhash    = sha.ComputeHash(passwdbyteforhash);
            string PasswordHash      = "";

            for (int i = 0; i < passwbeforhash.Count(); i++)
            {
                PasswordHash += passwbeforhash[i].ToString();
            }

            if (PasswordHash == password)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #40
0
        /// <summary>
        /// ユーザ鍵の署名を生成します。
        /// 引数のユーザ鍵インスタンスは書き換えません。
        /// </summary>
        /// <param name="key"></param>
        /// <returns>署名</returns>
        private static string SignPeerKey(PeerKey key)
        {
            // 署名用データ生成
            byte[] expire    = Encoding.ASCII.GetBytes(key.Expire.ToString("yyyy/MM/dd HH-mm-ss"));
            byte[] publicKey = key.PublicKeyBytes;
            byte[] signData  = Enumerable.Concat(publicKey, expire).ToArray();

            SHA1CryptoServiceProvider sha1Provider = new SHA1CryptoServiceProvider();

            byte[] sha1SignData = sha1Provider.ComputeHash(signData);

            // 署名生成
            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

            rsaProvider.ImportParameters(KeyDefine.PeerVerificationKey);

            RSAPKCS1SignatureFormatter pkcsFormatter = new RSAPKCS1SignatureFormatter(rsaProvider);

            pkcsFormatter.SetHashAlgorithm("SHA1");

            byte[] sign = pkcsFormatter.CreateSignature(sha1SignData);

            return(Convert.ToBase64String(sign, Base64FormattingOptions.None));
        }
Exemple #41
0
        private bool haskKey(string strKey)
        {
            try
            {
                //Convert Key to byte array
                byte[]       bp   = new byte[strKey.Length];
                UTF8Encoding aEnc = new UTF8Encoding();
                //Dim aEnc As ASCIIEncoding = New ASCIIEncoding()
                aEnc.GetBytes(strKey, 0, strKey.Length, bp, 0);

                //Hash the key using SHA1
                SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
                byte[] bpHash = null;
                int    i      = 0;

                bpHash = sha.ComputeHash(bp);

                //use the low 64-bits for the key value
                for (i = 0; i <= 7; i++)
                {
                    mKey[i] = bpHash[i];
                }

                for (i = 8; i <= 15; i++)
                {
                    mIV[i - 8] = bpHash[i];
                }


                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        /// <summary>Create a new revocation message.</summary>
        public UserRevocationMessage(RSACryptoServiceProvider private_key, string username)
        {
            Username = username;
            int signature_length = private_key.KeySize / 8;

            byte[] data = null;

            using (MemoryStream ms = new MemoryStream()) {
                AdrConverter.Serialize(Username, ms);
                Random rand = new Random();
                NumberSerializer.WriteInt(rand.Next(), ms);
                NumberSerializer.WriteLong(DateTime.UtcNow.Ticks, ms);
                data        = new byte[ms.Length + signature_length];
                ms.Position = 0;
                ms.Read(data, 0, (int)ms.Length);
            }

            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            Hash      = sha1.ComputeHash(data, 0, data.Length - signature_length);
            Signature = private_key.SignHash(Hash, CryptoConfig.MapNameToOID("SHA1"));
            Signature.CopyTo(data, data.Length - signature_length);
            _data = MemBlock.Reference(data);
        }
        public string Shorten(string url)
        {
            // generate random bytes, and add process id and current time for more entropy
            var randomBytes = RandomBytes();
            var pid         = Pid();
            var time        = Time();

            // combine url with random data
            var combined = String.Format("{0}:{1}:{2}:{3}", url, randomBytes, pid, time);

            // apply sha1 hash to combined data to get fixed number of bytes
            SHA1 sha1      = new SHA1CryptoServiceProvider();
            var  hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(combined));

            // convert sha1 bytes to integer
            var number = BytesToBigInteger(hashBytes);

            // convert to base 62 so we only return alpha numeric chars
            var result = BigIntegerToBase62(number);

            // truncate value to seven chars so it will be short
            // 62^7 combinations (3,521,614,606,208)
            return(result.Substring(0, ShortStringLength));
        }
    public static void Main(string[] args)
    {
        string rl_path = args[0];
        string cacert_path = args[1];

        byte[] data = null;
        using(FileStream fs = File.Open(rl_path, FileMode.Open)) {
          data = new byte[fs.Length];
          fs.Read(data, 0, data.Length);
        }

        Certificate cert = null;
        using(FileStream fs = File.Open(cacert_path, FileMode.Open)) {
          byte[] cert_blob = new byte[fs.Length];
          fs.Read(cert_blob, 0, cert_blob.Length);
          cert = new Certificate(cert_blob);
        }

        int length = data.Length;
        if(length < 12) {
          Console.WriteLine("No data?  Didn't get enough data...");
          return;
        }

        length = NumberSerializer.ReadInt(data, 0);
        DateTime date = new DateTime(NumberSerializer.ReadLong(data, 4));
        if(date < DateTime.UtcNow.AddHours(-24)) {
          Console.WriteLine("Revocation list is over 24 hours old");
        }

        Console.WriteLine("CRL Date: " + date);

        if(length > data.Length - 12) {
          Console.WriteLine("Missing data?  Didn't get enough data...");
          return;
        }

        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
        byte[] hash = sha1.ComputeHash(data, 4, length);
        byte[] signature = new byte[data.Length - 4 - length];
        Array.Copy(data, 4 + length, signature, 0, signature.Length);

        if(!cert.PublicKey.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature)) {
          Console.WriteLine("Invalid signature!");
          return;
        }

        MemBlock mem = MemBlock.Reference(data, 12, length - 8);

        object list = null;
        try {
          list = AdrConverter.Deserialize(mem) as ArrayList;
        } catch {
          Console.WriteLine("Unable to deserialize data...");
        }

        ArrayList rl = list as ArrayList;
        if(rl == null) {
          Console.WriteLine("Data wasn't a list...");
          return;
        }

        foreach(string name in rl) {
          Console.WriteLine(name);
        }
    }
Exemple #45
0
    public void calculateSRP_M1()
    {
        SHA1 sha = new SHA1CryptoServiceProvider();

        // limit SRP_N to 32 bytes
        byte[] N = new byte[32];
        Buffer.BlockCopy(SRP_N.ToByteArray(), 0, N, 0, 32);
        // Calculate the hashes
        byte[] Nhash = sha.ComputeHash(N);
        byte[] ghash = sha.ComputeHash(SRP_g.ToByteArray());
        byte[] userhash = sha.ComputeHash(Encoding.ASCII.GetBytes(SRP_I));

        byte[] nghash = new byte[20];
        for (uint i = 0; i < nghash.Length; i++)
            nghash[i] = (byte)(Nhash[i] ^ ghash[i]);

        // Convert to array and ensure the right size
        byte[] Abytes = new byte[32];
        Buffer.BlockCopy(SRP_A.ToByteArray(), 0, Abytes, 0, 32);
        byte[] Bbytes = new byte[32];
        Buffer.BlockCopy(SRP_B.ToByteArray(), 0, Bbytes, 0, 32);

        byte[] concat = new byte[nghash.Length + userhash.Length + SRP_s.Length
            + Abytes.Length + Bbytes.Length + SRP_K.Length];

        int offset = 0;
        nghash.CopyTo(concat, 0);
        offset += nghash.Length;
        userhash.CopyTo(concat, offset);
        offset += userhash.Length;
        SRP_s.CopyTo(concat, offset);
        offset += SRP_s.Length;
        Abytes.CopyTo(concat, offset);
        offset += Abytes.Length;
        Bbytes.CopyTo(concat, offset);
        offset += Bbytes.Length;
        SRP_K.CopyTo(concat, offset);

        SRP_M1 = sha.ComputeHash(concat);
    }
Exemple #46
0
 /// <summary>
 /// Encodes the input as a sha1 hash
 /// </summary>
 /// <param name="input">
 /// The input we want to encoded <see cref="System.String"/>
 /// </param>
 /// <returns>
 /// The sha1 hash encoded result of input <see cref="System.String"/>
 /// </returns>
 public string CreateSha1Hash(string input)
 {
     // Gets the sha1 hash for input
     SHA1 sha1 = new SHA1CryptoServiceProvider();
     byte[] data = Encoding.Default.GetBytes(input);
     byte[] hash = sha1.ComputeHash(data);
     // Returns sha1 hash as string
     return Convert.ToBase64String(hash);
 }
Exemple #47
0
	internal RegistrationDetails(string registrationKey)
	{
		try
		{
			int y = DateTime.Now.Year;
			int m = DateTime.Now.Month;
			int d = DateTime.Now.Day;
			string host;
			if (HttpContext.Current!=null)
			{
				host = HttpContext.Current.Request.Url.Host.ToLower();
			}
			else
			{
				host="localhost";
			}
			string serverName = HttpContext.Current.Server.MachineName;


			this.registrationKey = registrationKey;
			string[] regParts = UrlDeSerialize(registrationKey).ToString().Split('|');

			Product = (Products)int.Parse(regParts[0]);
			MajorVersion = (int)int.Parse(regParts[1]);
			MinorVersion = (int)int.Parse(regParts[2]);
			Build = (int)int.Parse(regParts[3]);

			Edition = (EditionTypes)int.Parse(regParts[4]);
			LicenseType = (LicenseTypes)int.Parse(regParts[5]);
			UrlRestriction = (UrlRestrictionTypes)int.Parse(regParts[6]);
			TimeRestriction = (TimeRestrictionTypes)int.Parse(regParts[7]);

			RestrictionString = UrlTextDeSerialize(regParts[8]);
			string restrictionStringPlusWww = "www."+RestrictionString;
			Organisation = UrlTextDeSerialize(regParts[9]);
			ExpiryYear = int.Parse(regParts[10]);
			ExpiryMonth = int.Parse(regParts[11]);
			ExpiryDay = int.Parse(regParts[12]);

			PurchaseK = int.Parse(regParts[13]);

			LicensedServers = int.Parse(regParts[14]);
			ServerNameRestriction = (ServerNameRestrictionTypes)int.Parse(regParts[15]);
			LicenseIsPaid = (LicenseIsPaidTypes)int.Parse(regParts[16]);

			HashFromRegKey = UrlTextDeSerialize(regParts[17]);

			string licenseString = regParts[0]+"|"+regParts[1]+"|"+regParts[2]+"|"+regParts[4]+"|"+regParts[5]+"|"+regParts[6]+"|"+regParts[7]+"|"+regParts[8]+"|"+regParts[9]+"|"+regParts[10]+"|"+regParts[11]+"|"+regParts[12]+"|"+regParts[13]+"|"+regParts[14]+"|"+regParts[15]+"|"+regParts[16]+"|"+UrlDeSerialize("aeaaaaU99999baaaaaaaaaEbbaaaaufzPNKzIn1zPnHnZqXmZqHx7R1mZqXoImGxOyGxHqcBWJ1-QNg-KB0-QNg-LnhzJqWiWvgBWvKzIB0-OBKzIVKreBeshzIszNYmYutnYmdzKnh-LF0zl");
			SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
			byte[] hashFromClientByteArray = sha1.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(licenseString));
			string hashFromClientString = System.Text.ASCIIEncoding.ASCII.GetString(hashFromClientByteArray);

			if ( Product!=Products.DbCombo || (Edition == EditionTypes.Free && ( ! LicenseType.Equals(LicenseTypes.Restricted) || ! UrlRestriction.Equals(UrlRestrictionTypes.UrlRestricted) ) ) )
				throw new InvalidSerialException();
			if (MajorVersion!=Assembly.GetExecutingAssembly().GetName().Version.Major || MinorVersion != Assembly.GetExecutingAssembly().GetName().Version.Minor )
				throw new InvalidVersionException(this);
			if (TimeRestriction.Equals(TimeRestrictionTypes.TimeRestricted) && ( ExpiryYear < y || ( ExpiryYear == y && ExpiryMonth < m ) || ( ExpiryYear == y && ExpiryMonth == m && ExpiryDay <= d ) ) )
				throw new ExpiredSerialException();
			if (LicenseIsPaid.Equals(LicenseIsPaidTypes.Free))
			{
				if (UrlRestriction.Equals(UrlRestrictionTypes.UrlRestricted) &! (host == RestrictionString.ToLower() || host == "www."+RestrictionString.ToLower() || host == "localhost"))
					throw new DomainSerialException(this);
				if (ServerNameRestriction.Equals(ServerNameRestrictionTypes.ServerNameRestricted) &! (host == "localhost") &! (RestrictionString.ToUpper() == HttpContext.Current.Server.MachineName.ToUpper()))
					throw new ServerNameSerialException(this);
			}
			//if (HashFromRegKey != hashFromClientString )
			//	throw new InvalidSerialException();
		}
		catch (DbComboGenericSerialException a)
		{
			throw a;
		}
		catch (Exception)
		{
			throw new InvalidSerialException();
		}
	}
    public bool UpdateRevocationList(string group_name)
    {
        if(!Context.Request.IsLocal) {
          throw new Exception("Call must be made locally!");
        }

        IDbConnection dbcon = new MySqlConnection(_connection_string);
        dbcon.Open();
        IDbCommand dbcmd = dbcon.CreateCommand();

        // Get the group_id
        string sql = "SELECT group_id from groupvpn WHERE group_name = \"" + group_name + "\"";
        dbcmd.CommandText = sql;
        IDataReader reader = dbcmd.ExecuteReader();
        if(!reader.Read()) {
          throw new Exception("No such group.");
        }

        int group_id = (int) reader["group_id"];
        reader.Close();

        // get revoked users
        sql = "SELECT user_id FROM groups WHERE group_id = \"" + group_id + "\" and revoked = 1";
        dbcmd.CommandText = sql;
        reader = dbcmd.ExecuteReader();

        // add revoked users by user name to the revocation list
        ArrayList revoked_user_ids = new ArrayList();
        while(reader.Read()) {
          revoked_user_ids.Add((int) reader["user_id"]);
        }

        reader.Close();

        ArrayList revoked_users = new ArrayList();
        foreach(int user_id in revoked_user_ids) {
          sql = "SELECT username FROM " + _db_prefix + "users WHERE id = " + user_id;
          dbcmd.CommandText = sql;
          IDataReader user_reader = dbcmd.ExecuteReader();
          if(!user_reader.Read()) {
        continue;
          }

          revoked_users.Add(user_reader["username"]);
          user_reader.Close();
        }

        reader.Close();
        dbcmd.Dispose();
        dbcon.Close();

        // get private key
        string private_path = GetGroupPrivatePath(group_name) + "private_key";
        if(!File.Exists(private_path)) {
          throw new Exception("No private key for " + private_path + " " + File.Exists(private_path));
        }

        RSACryptoServiceProvider private_key = new RSACryptoServiceProvider();
        using(FileStream fs = File.Open(private_path, FileMode.Open)) {
          byte[] blob = new byte[fs.Length];
          fs.Read(blob, 0, blob.Length);
          private_key.ImportCspBlob(blob);
        }

        // create revocation list
        byte[] to_sign = null;
        using(MemoryStream ms = new MemoryStream()) {
          NumberSerializer.WriteLong(DateTime.UtcNow.Ticks, ms);
          AdrConverter.Serialize(revoked_users, ms);
          to_sign = ms.ToArray();
        }

        // sign revocation list
        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
        byte[] hash = sha1.ComputeHash(to_sign);
        byte[] signature = private_key.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
        byte[] data = new byte[4 + to_sign.Length + signature.Length];
        NumberSerializer.WriteInt(to_sign.Length, data, 0);
        to_sign.CopyTo(data, 4);
        signature.CopyTo(data, 4 + to_sign.Length);

        // write revocation list
        using(FileStream fs = File.Open(GetGroupDataPath(group_name) + "revocation_list", FileMode.Create)) {
          fs.Write(data, 0, data.Length);
        }

        return true;
    }
Exemple #49
0
    /// <summary>
    /// Encrypts a string into a SHA-1 hash.
    /// </summary>
    /// <param name="toEncrypt">The string to encrypt.</param>
    public static string Sha1Hash(string toEncrypt)
    {
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] bytes = encoding.GetBytes(toEncrypt);

        SHA1 sha = new SHA1CryptoServiceProvider();
        byte[] result = sha.ComputeHash(bytes);

        string hash = "";
        for (int i = 0; i < result.Length; i++) {
            hash += Convert.ToString(result[i], 16).PadLeft(2, '0');
        }

        return hash;
    }
Exemple #50
0
    private static string ComputeSHA(string input)
    {
        byte[] byteArray = Encoding.ASCII.GetBytes(input);

        SHA1 sha = new SHA1CryptoServiceProvider();
        byte[] result = sha.ComputeHash(byteArray);

        return Encoding.ASCII.GetString(result);
    }
Exemple #51
0
    /// <summary>
    /// Gets a universally unique ID to represent the user. User ID should be device specific to allow tracking across different games on the same device:
    /// -- Android uses deviceUniqueIdentifier.
    /// -- iOS/PC/Mac uses the first MAC addresses available.
    /// -- Webplayer uses deviceUniqueIdentifier.
    /// Note: The unique user ID is based on the ODIN specifications. See http://code.google.com/p/odinmobile/ for more information on ODIN.
    /// </summary>
    /// <returns>
    /// The generated UUID <see cref="System.String"/>
    /// </returns>
    public static string GetUserUUID()
    {
        #if UNITY_IPHONE && !UNITY_EDITOR

        string uid = GA.SettingsGA.GetUniqueIDiOS();

        if (uid == null)
        {
            return "";
        }
        else if (uid != "OLD")
        {
            if (uid.StartsWith("VENDOR-"))
                return uid.Remove(0, 7);
            else
                return uid;
        }

        #endif

        #if UNITY_ANDROID && !UNITY_EDITOR

        string uid = GA.SettingsGA.GetAdvertisingIDAndroid();

        if (!string.IsNullOrEmpty(uid))
        {
            return uid;
        }

        #endif

        #if UNITY_WEBPLAYER || UNITY_NACL || UNITY_WP8 || UNITY_METRO || UNITY_PS3

        return SystemInfo.deviceUniqueIdentifier;

        #elif !UNITY_FLASH

        try
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            string mac = "";

            foreach (NetworkInterface adapter in nics)
            {
                PhysicalAddress address = adapter.GetPhysicalAddress();
                if (address.ToString() != "" && mac == "")
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(address.ToString());
                    SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider();
                    mac = BitConverter.ToString(SHA.ComputeHash(bytes)).Replace("-", "");
                }
            }
            return mac;
        }
        catch
        {
            return SystemInfo.deviceUniqueIdentifier;
        }

        #else

        return GetSessionUUID();

        #endif
    }
Exemple #52
0
    public void calculateSRP_u()
    {
        // create the sha object
        SHA1 sha = new SHA1CryptoServiceProvider();

        // get array of bytes
        byte[] Abytes = SRP_A.ToByteArray();
        byte[] Bbytes = SRP_B.ToByteArray();

        // concatenate A and B
        byte[] concat = new byte[Abytes.Length + Bbytes.Length];
        Abytes.CopyTo(concat, 0);
        Bbytes.CopyTo(concat, Abytes.Length);

        // Compute sha(concat(A, B))
        byte[] hash = sha.ComputeHash(concat);

        // add 0 to the end of the hash to get a positive value
        byte[] b = new byte[hash.Length + 1];
        hash.CopyTo(b, 0);

        SRP_u = new BigInteger(b);
    }
Exemple #53
0
    public void calculateSRP_K()
    {
        byte[] S = SRP_S.ToByteArray();
        byte[] S1 = new byte[16];
        byte[] S2 = new byte[16];

        // Split the S value in S1 and S2, interleaving each char
        uint j = 0;
        for (uint i = 0; i < 32; i+=2)
        {
            S1[j] = S[i];
            S2[j] = S[i + 1];
            j++;
        }

        // Calculate S1 and S2 sha
        SHA1 sha = new SHA1CryptoServiceProvider();
        byte[] S1hash = sha.ComputeHash(S1);
        byte[] S2hash = sha.ComputeHash(S2);

        //
        j = 0;
        byte[] SKhash = new byte[40];
        for (uint i = 0; i < 20; i++)
        {
            SKhash[j++] = S1hash[i];
            SKhash[j++] = S2hash[i];
        }

        SRP_K = SKhash;
    }
    private static String ComputeWebSocketHandshakeSecurityHash09(string secWebSocketKey)
    {
        const String MagicKEY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";

        String secWebSocketAccept = String.Empty;
        // 1. Combine the request Sec-WebSocket-Key with magic key.
        String ret = secWebSocketKey + MagicKEY;

        // 2. Compute the SHA1 hash
        SHA1 sha = new SHA1CryptoServiceProvider();
        byte[] sha1Hash = sha.ComputeHash(Encoding.UTF8.GetBytes(ret));

        // 3. Base64 encode the hash
        secWebSocketAccept = Convert.ToBase64String(sha1Hash);
        return secWebSocketAccept;
    }
Exemple #55
0
    public void calculateSRP_M2()
    {
        SHA1 sha = new SHA1CryptoServiceProvider();
        byte[] Abytes = SRP_A.ToByteArray();

        byte[] concat = new byte[Abytes.Length + SRP_M1.Length + SRP_K.Length];
        int offset = 0;

        Abytes.CopyTo(concat, offset);
        offset += Abytes.Length;
        SRP_M1.CopyTo(concat, offset);
        offset += SRP_M1.Length;
        SRP_K.CopyTo(concat, offset);

        SRP_M2 = sha.ComputeHash(concat);
    }
Exemple #56
0
    string HashFromImage(Image img)
    {
        string hash;
        byte[] bytes = null;

        using (MemoryStream ms = new MemoryStream()) {
            img.Save (ms, img.RawFormat);
            bytes = ms.ToArray ();
        }

        using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) {
            bytes = sha1.ComputeHash (bytes);
            hash = BitConverter.ToString (bytes).Replace ("-", "").ToLower ();
        }

        return hash;
    }
Exemple #57
0
    public void calculateSRP_x()
    {
        SHA1 sha = new SHA1CryptoServiceProvider();

        // authstr = username:password
        string authstr = string.Format("{0}:{1}", SRP_I, SRP_P);

        // userhash = sha1(authstr)
        byte[] userhash = sha.ComputeHash(Encoding.ASCII.GetBytes(authstr));

        // concatenate the salt and the hash
        byte[] concat = new byte[SRP_s.Length + userhash.Length];
        SRP_s.CopyTo(concat, 0);
        userhash.CopyTo(concat, SRP_s.Length);

        // compute the salted auth string SHA1
        byte[] hash = sha.ComputeHash(concat);

        // recreate an array with trailing 0 to specify a positive value
        byte[] b = new byte[hash.Length + 1];
        hash.CopyTo(b, 0);

        SRP_x = new BigInteger(b);
    }
        /// <summary>
        ///     Verify the hash of the manifest without any signature attached is what the Authenticode
        ///     signature expects it to be
        /// </summary>
        private SignatureVerificationResult VerifyAuthenticodeExpectedHash(XmlElement licenseNode) {
            Debug.Assert(licenseNode != null, "licenseNode != null");

            // Get the expected hash value from the signature
            XmlElement manifestInformation = licenseNode.SelectSingleNode("r:grant/as:ManifestInformation",
                                                                          m_namespaceManager) as XmlElement;
            if (manifestInformation == null)
                return SignatureVerificationResult.BadSignatureFormat;

            string expectedHashString = manifestInformation.GetAttribute("Hash");
            if (String.IsNullOrEmpty(expectedHashString)) {
                return SignatureVerificationResult.BadSignatureFormat;
            }

            // The expected hash value is stored in backward order, so we cannot use a standard hex to bytes
            // routine to decode it.
            byte[] expectedHash = BackwardHexToBytes(expectedHashString);

            // Make a normalized copy of the manifest without the strong name signature attached
            XmlDocument normalizedManifest = new XmlDocument();
            normalizedManifest.PreserveWhitespace = true;

            XmlReaderSettings normalizationSettings = new XmlReaderSettings();
            normalizationSettings.DtdProcessing = DtdProcessing.Parse;

            using (TextReader manifestReader = new StringReader(m_manifestXml.OuterXml))
            using (XmlReader xmlReader = XmlReader.Create(manifestReader, normalizationSettings, m_manifestXml.BaseURI)) {
                normalizedManifest.Load(xmlReader);
            }

            XmlElement signatureNode = normalizedManifest.SelectSingleNode("//asm:assembly/ds:Signature",
                                                                           m_namespaceManager) as XmlElement;
            Debug.Assert(signatureNode != null, "signatureNode != null");

            signatureNode.ParentNode.RemoveChild(signatureNode);

            // calculate the hash value of the manifest
            XmlDsigExcC14NTransform canonicalizedXml = new XmlDsigExcC14NTransform();
            canonicalizedXml.LoadInput(normalizedManifest);

            byte[] actualHash = null;
            using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) {
                actualHash = sha1.ComputeHash(canonicalizedXml.GetOutput() as MemoryStream);
            }

            if (!CompareBytes(expectedHash, actualHash)) {
                return SignatureVerificationResult.BadDigest;
            }

            return SignatureVerificationResult.Valid;
        }
    /// <summary>
    /// Load Assembly, DLL from Embedded Resources into memory.
    /// </summary>
    /// <param name="embeddedResource">Embedded Resource string. Example: WindowsFormsApplication1.SomeTools.dll</param>
    /// <param name="fileName">File Name. Example: SomeTools.dll</param>
    public static void Load(string embeddedResource, string fileName)
    {
        if (dic == null)
            dic = new Dictionary<string, Assembly>();

        byte[] ba = null;
        Assembly asm = null;
        Assembly curAsm = Assembly.GetExecutingAssembly();

        using (Stream stm = curAsm.GetManifestResourceStream(embeddedResource))
        {
            // Either the file is not existed or it is not mark as embedded resource
            if (stm == null)
                throw new Exception(embeddedResource + " is not found in Embedded Resources.");

            // Get byte[] from the file from embedded resource
            ba = new byte[(int)stm.Length];
            stm.Read(ba, 0, (int)stm.Length);
            try
            {
                asm = Assembly.Load(ba);

                // Add the assembly/dll into dictionary
                dic.Add(asm.FullName, asm);
                return;
            }
            catch
            {
                // Purposely do nothing
                // Unmanaged dll or assembly cannot be loaded directly from byte[]
                // Let the process fall through for next part
            }
        }

        bool fileOk = false;
        string tempFile = "";

        using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
        {
            // Get the hash value from embedded DLL/assembly
            string fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty);
            
            // Define the temporary storage location of the DLL/assembly
            tempFile = Path.GetTempPath() + fileName;

            // Determines whether the DLL/assembly is existed or not
            if (File.Exists(tempFile))
            {
                // Get the hash value of the existed file
                byte[] bb = File.ReadAllBytes(tempFile);
                string fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).Replace("-", string.Empty);

                // Compare the existed DLL/assembly with the Embedded DLL/assembly
                if (fileHash == fileHash2)
                {
                    // Same file
                    fileOk = true;
                }
                else
                {
                    // Not same
                    fileOk = false;
                }
            }
            else
            {
                // The DLL/assembly is not existed yet
                fileOk = false;
            }
        }

        // Create the file on disk
        if (!fileOk)
        {
            System.IO.File.WriteAllBytes(tempFile, ba);
        }
        
        // Load it into memory
        asm = Assembly.LoadFile(tempFile);

        // Add the loaded DLL/assembly into dictionary
        dic.Add(asm.FullName, asm);
    }
 public static byte[] GetSha1(byte[] pData)
 {
     using (var sha = new SHA1CryptoServiceProvider())
     {
         return sha.ComputeHash(pData, 0, pData.Length);
     }
 }