示例#1
1
    ///<summary>Enables the SA if it has been properly setup.</summary>
    public void Enable() {
      // If both parties setup simultaneous SAs we could end up calling this
      // twice, once as a client and the other as server, this way we only
      // go through the whole process once.
      lock(_sync) {
        if(_called_enable == 1) {
          return;
        } else if(_closed == 1) {
          throw new Exception("Cannot enable a closed SA!");
        } else if(_ldhe == null) {
          throw new Exception("Local DHE not set.");
        } else if(RDHE.Value == null) {
          throw new Exception("Remote DHE not set.");
        } else if(!_hash_verified) {
          throw new Exception("Hash is not verified!");
        } else if(TimedOut) {
          throw new Exception("Timed out on this one!");
        }
        _called_enable = 1;

        // Deriving the DHE exchange and determing the order of keys
        // Specifically, we need up to 4 keys for the sender/receiver encryption/
        // authentication codes.  So to determine the order, we say whomever has
        // the smallest gets the first set of keys.
        byte[] rdhe = (byte[]) RDHE.Value;
        RDHE = null;
        byte[] key = _dh.DecryptKeyExchange(rdhe);
        _dh.Clear();
        _dh = null;
        int i = 0;
        while(i < _ldhe.Length && _ldhe[i] == rdhe[i]) i++;
        bool same = i == _ldhe.Length;
        bool first = !same && (_ldhe[i] < rdhe[i]);
        _ldhe = null;
        // Gathering our security parameter objects
        SecurityPolicy sp = SecurityPolicy.GetPolicy(_spi);
        SymmetricAlgorithm in_sa = sp.CreateSymmetricAlgorithm();
        HashAlgorithm in_ha = sp.CreateHashAlgorithm();
        SymmetricAlgorithm out_sa = sp.CreateSymmetricAlgorithm();
        HashAlgorithm out_ha = sp.CreateHashAlgorithm();

        // Generating the total key length 
        int key_length = key.Length + 2 + (in_sa.KeySize / 8 + in_sa.BlockSize / 8) * 2;
        KeyedHashAlgorithm in_kha = in_ha as KeyedHashAlgorithm;
        KeyedHashAlgorithm out_kha = out_ha as KeyedHashAlgorithm;
        if(in_kha != null) {
          key_length += (in_kha.HashSize / 8) * 2;
        }

        // Generating a key by repeatedly hashing the DHE value and the key so far
        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
        int usable_key_offset = key.Length;
        while(key.Length < key_length) {
          byte[] hash = sha1.ComputeHash(key);
          byte[] tmp_key = new byte[hash.Length + key.Length];
          key.CopyTo(tmp_key, 0);
          hash.CopyTo(tmp_key, key.Length);
          key = tmp_key;
        }

        // Like a sub-session ID (see DTLS)
        short epoch = (short) ((key[usable_key_offset] << 8) + key[usable_key_offset + 1]);
        usable_key_offset += 2;

        byte[] key0 = new byte[in_sa.KeySize / 8];
        Array.Copy(key, usable_key_offset, key0, 0, key0.Length);
        usable_key_offset += key0.Length;

        byte[] key1 = new byte[in_sa.KeySize / 8];
        Array.Copy(key, usable_key_offset, key1, 0, key1.Length);
        usable_key_offset += key1.Length;

        // Same may occur if we are forming a session with ourselves!
        if(same) {
          in_sa.Key = key0;
          out_sa.Key = key0;
        } else if(first) {
          in_sa.Key = key0;
          out_sa.Key = key1;
        } else {
          out_sa.Key = key0;
          in_sa.Key = key1;
        }

        if(in_kha != null) {
          byte[] hkey0 = new byte[in_kha.HashSize / 8];
          Array.Copy(key, usable_key_offset, hkey0, 0, hkey0.Length);
          usable_key_offset += hkey0.Length;

          byte[] hkey1 = new byte[in_kha.HashSize / 8];
          Array.Copy(key, usable_key_offset, hkey1, 0, hkey1.Length);
          usable_key_offset += hkey1.Length;

          if(same) {
            in_kha.Key = hkey0;
            out_kha.Key = hkey0;
          } else if(first) {
            in_kha.Key = hkey0;
            out_kha.Key = hkey1;
          } else {
            out_kha.Key = hkey0;
            in_kha.Key = hkey1;
          }
        }

        SecurityHandler sh = new SecurityHandler(in_sa, out_sa, in_ha, out_ha, epoch);
        sh.Update += UpdateSH;
        SecurityHandler to_close = _current_sh;
        if(to_close != null) {
          to_close.Close();
        }
        _current_sh = sh;
        _last_epoch = _current_epoch;
        _current_epoch = epoch;
      }
      // All finished set the state (which will probably fire an event)
      State = SAState.Active;
    }
示例#2
0
    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 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 = "";
          }
    }
    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;
         }
          }
    }
示例#6
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);
    }
示例#8
0
文件: RSA.cs 项目: cangjie/lq_yeepay
 /// <summary>
 /// 验签
 /// </summary>
 /// <param name="content">待验签字符串</param>
 /// <param name="signedString">签名</param>
 /// <param name="publicKey">公钥</param>
 /// <param name="input_charset">编码格式</param>
 /// <returns>true(通过),false(不通过)</returns>
 public static bool checkSign(string content, string signedString, string publicKey, string input_charset)
 {
     bool result = false;
         byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
         byte[] data = Convert.FromBase64String(signedString);
         RSAParameters paraPub = ConvertFromPublicKey(publicKey);
         RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
         rsaPub.ImportParameters(paraPub);
         SHA1 sh = new SHA1CryptoServiceProvider();
         result = rsaPub.VerifyData(Data, sh, data);
         return result;
 }
    /// <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();
    }
示例#10
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.");
        }
    }
示例#13
0
        public HMACSHA1 (byte[] key, bool useManagedSha1) {
            m_hashName = "SHA1";
#if FEATURE_CRYPTO
            if (useManagedSha1) {
#endif // FEATURE_CRYPTO
                m_hash1 = new SHA1Managed();
                m_hash2 = new SHA1Managed();
#if FEATURE_CRYPTO
            } else {
                m_hash1 = new SHA1CryptoServiceProvider();
                m_hash2 = new SHA1CryptoServiceProvider();
            }
#endif // FEATURE_CRYPTO

            HashSizeValue = 160;
            base.InitializeKey(key);
        }
示例#14
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");

        }
    }
示例#16
0
文件: misc.cs 项目: liuzhenkn/OurNet
    /// <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;
        }
    }
示例#17
0
文件: RSA.cs 项目: cangjie/lq_yeepay
 /// <summary>
 /// 签名
 /// </summary>
 /// <param name="content">待签名字符串</param>
 /// <param name="privateKey">私钥</param>
 /// <param name="input_charset">编码格式</param>
 /// <returns>签名后字符串</returns>
 public static string sign(string content, string privateKey, string input_charset)
 {
     byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
         RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
         SHA1 sh = new SHA1CryptoServiceProvider();
         byte[] signData = rsa.SignData(Data, sh);
         return Convert.ToBase64String(signData);
 }
示例#18
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();
		}
	}
示例#19
0
文件: RSA.cs 项目: cangjie/lq_yeepay
 private static string decrypt(byte[] data, string privateKey, string input_charset)
 {
     string result = "";
         RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
         SHA1 sh = new SHA1CryptoServiceProvider();
         byte[] source = rsa.Decrypt(data, false);
         char[] asciiChars = new char[Encoding.GetEncoding(input_charset).GetCharCount(source, 0, source.Length)];
         Encoding.GetEncoding(input_charset).GetChars(source, 0, source.Length, asciiChars, 0);
         result = new string(asciiChars);
         //result = ASCIIEncoding.ASCII.GetString(source);
         return result;
 }
示例#20
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);
    }
示例#21
0
        /// <summary>
        /// Computes the hash for the specified stream and compares
        /// it to the value in this object. CRC hashes are not supported
        /// because there is no built-in support in the .net framework and
        /// a CRC implementation exceeds the scope of this project. If you
        /// attempt to call this on a CRC hash a <see cref="NotImplementedException"/> will
        /// be thrown.
        /// </summary>
        /// <param name="istream">The stream to compute the hash for</param>
        /// <returns>True if the computed hash matches what's stored in this object.</returns>
        /// <exception cref="NotImplementedException">Thrown if called on a CRC Hash</exception>
        public bool Verify(Stream istream)
        {
            if (IsValid)
            {
                HashAlgorithm hashAlg = null;

                switch (m_algorithm)
                {
                case FtpHashAlgorithm.SHA1:
#if CORE
                    hashAlg = SHA1.Create();
#else
                    hashAlg = new SHA1CryptoServiceProvider();
#endif
                    break;

#if !NET2
                case FtpHashAlgorithm.SHA256:
#if CORE
                    hashAlg = SHA256.Create();
#else
                    hashAlg = new SHA256CryptoServiceProvider();
#endif
                    break;

                case FtpHashAlgorithm.SHA512:
#if CORE
                    hashAlg = SHA512.Create();
#else
                    hashAlg = new SHA512CryptoServiceProvider();
#endif
                    break;
#endif
                case FtpHashAlgorithm.MD5:
#if CORE
                    hashAlg = MD5.Create();
#else
                    hashAlg = new MD5CryptoServiceProvider();
#endif
                    break;

                case FtpHashAlgorithm.CRC:
                    throw new NotImplementedException("There is no built in support for computing CRC hashes.");

                default:
                    throw new NotImplementedException("Unknown hash algorithm: " + m_algorithm.ToString());
                }

                try {
                    byte[] data = null;
                    string hash = "";

                    data = hashAlg.ComputeHash(istream);
                    if (data != null)
                    {
                        foreach (byte b in data)
                        {
                            hash += b.ToString("x2");
                        }

                        return(hash.ToUpper() == m_value.ToUpper());
                    }
                } finally {
#if !NET2 // .NET 2.0 doesn't provide access to Dispose() for HashAlgorithm
                    if (hashAlg != null)
                    {
                        hashAlg.Dispose();
                    }
#endif
                }
            }

            return(false);
        }
示例#22
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);
    }
示例#23
0
        public static void Load(string dllFileName)
        {
            // Get the byte[] of the DLL
            byte[]   ba       = null;
            string   resource = System.Reflection.Assembly.GetEntryAssembly().GetName().Name + ".Resources." + dllFileName + ".dll";
            Assembly curAsm   = Assembly.GetExecutingAssembly();

            using (Stream stm = curAsm.GetManifestResourceStream(resource))
            {
                ba = new byte[(int)stm.Length];
                stm.Read(ba, 0, (int)stm.Length);
            }

            bool   fileOk   = false;
            string tempFile = "";

            using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
            {
                // Get the hash value of the Embedded DLL
                string fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty);

                // The full path of the DLL that will be saved
                tempFile = Path.GetTempPath() + dllFileName + ".dll";

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

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

            // Create the file on disk
            if (!fileOk)
            {
                System.IO.File.WriteAllBytes(tempFile, ba);
            }

            hModule = LoadLibrary(tempFile);

            if (hModule == IntPtr.Zero)
            {
                Exception e = new Win32Exception();
                throw new DllNotFoundException(dllFileName + "을 찾을 수 없습니다. 잠시후 다시 해주세요.\n");
            }

            // allocating all functions...
            IntPtr pFuncAddr = IntPtr.Zero;


            pFuncAddr = GetProcAddress(hModule, "OnTest1" /*dll 함수 이름*/);                                                                                // 메모리에 올라간 dll의 내용중 OnTest1이라는 함수의 주소를 찾는다.
            func_OnTest1 /*dll에서 C#용으로 쓰는 함수*/ = (OnTest1 /*dll 함수 이름*/)Marshal.GetDelegateForFunctionPointer(pFuncAddr, typeof(OnTest1 /*dll 함수 이름*/)); // 찾은 함수의 주소를 포인팅한다.

            pFuncAddr = GetProcAddress(hModule, "shutdownWAS" /*dll 함수 이름*/);
            func_shutdownWAS /*dll에서 C#용으로 쓰는 함수*/ = (shutdownWAS /*dll 함수 이름*/)Marshal.GetDelegateForFunctionPointer(pFuncAddr, typeof(shutdownWAS /*dll 함수 이름*/));

            pFuncAddr = GetProcAddress(hModule, "_GetAdapterDescription" /*dll 함수 이름*/);
            func_GetAdapterDescription /*dll에서 C#용으로 쓰는 함수*/ = (_GetAdapterDescription /*dll 함수 이름*/)Marshal.GetDelegateForFunctionPointer(pFuncAddr, typeof(_GetAdapterDescription /*dll 함수 이름*/));


            pFuncAddr = GetProcAddress(hModule, "_SetAdapter" /*dll 함수 이름*/);
            func_SetAdapter /*dll에서 C#용으로 쓰는 함수*/ = (_SetAdapter /*dll 함수 이름*/)Marshal.GetDelegateForFunctionPointer(pFuncAddr, typeof(_SetAdapter /*dll 함수 이름*/));

            // load는 더이상 하지 않아도 된다. 다만 함수를 Delegate해준것에 대해 위와 같이 포인팅작업을 해주어야한다.
            // pFuncAddr = GetProcAddress(hModule, dll 함수이름);
            // add = ... 위와 같음, 그리고 30~32줄처럼 해주어야함. 반환값이나 전달인자는 C/C++에서 정의한대로 적어주면됨.
        }
示例#24
0
        ///<summary>
        /// Chipher text.
        ///</summary>
        ///<param name="settings">
        ///DLMS settings.
        ///</param>
        ///<param name="cipher">
        ///Cipher.
        ///</param>
        ///<param name="ic">
        ///Invocation counter.
        ///</param>
        ///<param name="data">
        ///Text to chipher.
        ///</param>
        ///<param name="secret">
        ///Secret.
        ///</param>
        ///<returns>
        ///Chiphered text.
        ///</returns>
        public static byte[] Secure(GXDLMSSettings settings, GXICipher cipher, UInt32 ic, byte[] data, byte[] secret)
        {
            byte[] tmp;
            if (settings.Authentication == Authentication.High)
            {
                int len = secret.Length;
                if (len % 16 != 0)
                {
                    len += 16 - (secret.Length % 16);
                }
                byte[] p = new byte[len];
                byte[] s = new byte[16];
                byte[] x = new byte[16];
                int    i;
                data.CopyTo(p, 0);
                secret.CopyTo(s, 0);
                for (i = 0; i < p.Length; i += 16)
                {
                    Buffer.BlockCopy(p, i, x, 0, 16);
                    GXAes128.Encrypt(x, s);
                    Buffer.BlockCopy(x, 0, p, i, 16);
                }
                Buffer.BlockCopy(p, 0, x, 0, 16);
                return(x);
            }
            // Get server Challenge.
            GXByteBuffer challenge = new GXByteBuffer();

            // Get shared secret
            if (settings.Authentication == Authentication.HighGMAC)
            {
                challenge.Set(data);
            }
            else
            {
                challenge.Set(data);
                challenge.Set(secret);
            }
            tmp = challenge.Array();
            if (settings.Authentication == Authentication.HighMD5)
            {
#if !WINDOWS_UWP
                using (MD5 md5Hash = MD5.Create())
                {
                    tmp = md5Hash.ComputeHash(tmp);
                    return(tmp);
                }
#endif
            }
            else if (settings.Authentication == Authentication.HighSHA1)
            {
#if !WINDOWS_UWP
                using (SHA1 sha = new SHA1CryptoServiceProvider())
                {
                    tmp = sha.ComputeHash(tmp);
                    return(tmp);
                }
#endif
            }
            else if (settings.Authentication == Authentication.HighSHA256)
            {
                //Windows UWP, IOS ad Android don't support this.
#if !WINDOWS_UWP && !__IOS__ && !__ANDROID__
                using (SHA256 sha = new SHA256CryptoServiceProvider())
                {
                    tmp = sha.ComputeHash(tmp);
                    return(tmp);
                }
#endif
            }
            else if (settings.Authentication == Authentication.HighGMAC)
            {
                //SC is always Security.Authentication.
                AesGcmParameter p = new AesGcmParameter(0, Security.Authentication, ic,
                                                        secret, cipher.BlockCipherKey, cipher.AuthenticationKey);
                p.Type = CountType.Tag;
                challenge.Clear();
                challenge.SetUInt8((byte)Security.Authentication);
                challenge.SetUInt32((UInt32)p.InvocationCounter);
                challenge.Set(GXDLMSChippering.EncryptAesGcm(p, tmp));
                tmp = challenge.Array();
                return(tmp);
            }
            return(data);
        }
示例#25
0
        public void PackDirectory(bool overwriteExisting, string inputFolder, string pboFileName)
        {
            try
            {
                // Make sure the input folder string is in the correct format
                if (!inputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    inputFolder = string.Format("{0}{1}", inputFolder, Path.DirectorySeparatorChar);
                }

                _log.InfoFormat("Packing the folder \"{0}\" with the ArmA 3 format.", inputFolder);

                // If a file already exists make a backup.
                if (File.Exists(pboFileName))
                {
                    if (overwriteExisting)
                    {
                        var str = string.Format("{0}.bak", pboFileName);

                        // If a old backup exists, delete it.
                        if (File.Exists(str))
                        {
                            _log.Trace("Old backup file detected. Removing the backup file.");
                            File.Delete(str);
                        }

                        _log.Trace("Found existing PBO with the same name. Renaming the file to have a .bak extension.");
                        File.Move(pboFileName, str);
                    }
                    else
                    {
                        throw new IOException("Destination file already exists. Please clear the destination or use the overwrite flag.");
                    }
                }

                var files            = Directory.GetFiles(inputFolder, "*", SearchOption.AllDirectories);
                var pboHeaderEntries = BuildPboHeaderList(inputFolder, files).OrderBy(x => x.FileName).ToList();

                using (var pboStream = new MemoryStream())
                    using (var pboWriter = new PboBinaryWriter(pboStream))
                    {
                        var currentPosition = 1;                      // Make it a bit nicer for users :-)
                        var basePathLength  = inputFolder.Length;
                        var totalEntries    = (files.Length * 2) + 3; // Headers, separator,  Files, sha1 and another 1 just because 'normal' people aren't used to 0-based counts.
                        _log.Trace("Writing header block...");
                        foreach (var headerEntry in pboHeaderEntries)
                        {
                            var fileWithPath = string.Format("{0}{1}", inputFolder, headerEntry.FileName);
                            headerEntry.Serialize(pboWriter);
                            _log.DebugFormat("Op. {0} of {1}. Packed header: {2}", currentPosition, totalEntries, fileWithPath.Substring(basePathLength));
                            currentPosition++;
                        }

                        // An empty record signifies the end of the header record.
                        pboWriter.Write(new byte[21]);
                        _log.DebugFormat("Op. {0} of {1}. Finalizing header.", currentPosition, totalEntries);
                        currentPosition++;

                        foreach (var pboHeaderEntry in pboHeaderEntries)
                        {
                            var fileWithPath = string.Format("{0}{1}", inputFolder, pboHeaderEntry.FileName);

                            using (var fileStream = new FileStream(fileWithPath, FileMode.Open, FileAccess.Read))
                                using (var binaryReader = new BinaryReader(fileStream))
                                {
                                    var bytes = binaryReader.ReadBytes((int)fileStream.Length);
                                    pboWriter.Write(bytes);
                                }

                            _log.DebugFormat("Op. {0} of {1}. Packed file: {2}", currentPosition, totalEntries, fileWithPath.Substring(basePathLength));
                            currentPosition++;
                        }

                        // Get the bytes of the pbo body so that the sha1 can be computed
                        pboStream.Position = 0;
                        var contentBytes = ReadStreamToEnd(pboStream);
                        var sha1Bytes    = new byte[21];
                        try
                        {
                            using (var sha1CryptoServiceProvider = new SHA1CryptoServiceProvider())
                            {
                                Array.Copy(sha1CryptoServiceProvider.ComputeHash(contentBytes), 0, sha1Bytes, 1, 20);
                                currentPosition++;
                            }
                        }
                        catch (Exception exception)
                        {
                            throw new Exception(exception.Message);
                        }

                        // Write out the body of the file along with the sha1
                        using (var fs = new FileStream(pboFileName, FileMode.Create, FileAccess.Write))
                        {
                            var fileBytes = new byte[contentBytes.Length + 21];
                            Buffer.BlockCopy(contentBytes, 0, fileBytes, 0, contentBytes.Length);
                            Buffer.BlockCopy(sha1Bytes, 0, fileBytes, contentBytes.Length, sha1Bytes.Length);
                            fs.Write(fileBytes, 0, fileBytes.Length);
                        }
                        _log.DebugFormat("Op. {0} of {1}. Writing PBO file to {2}.", currentPosition, totalEntries, pboFileName);
                        _log.Info("Writing PBO out to disk...");
                    }
                GC.Collect();
            }
            catch (Exception ex)
            {
                _log.Fatal("Fatal issue encountered", ex);
                Environment.ExitCode = 1;
            }
        }
示例#26
0
        /// <summary>
        /// Check for an upgrade to a web socket connection.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        private IWebSocketRequestHandler UpgradeToWebsocket(HttpRequest request, HttpResponse response)
        {
            // Check for required headers
            if (!(request.Headers.ContainsKey(HttpHeaders.Connection) && request.Headers[HttpHeaders.Connection].ToLower().Contains("upgrade")))
            {
                return(null);
            }
            if (!(request.Headers.ContainsKey(HttpHeaders.Upgrade) && request.Headers[HttpHeaders.Upgrade].ToLower().Contains("websocket")))
            {
                return(null);
            }
            if (!request.Headers.ContainsKey(SecWebSocketVersion))
            {
                return(null);
            }
            int version;

            if (!(int.TryParse(request.Headers[SecWebSocketVersion], out version) && (version == 13)))
            {
                return(null);
            }
            if (!request.Headers.ContainsKey(SecWebSocketKey))
            {
                return(null);
            }
            // Make sure we have a handler for the URI
            string partial;
            IWebSocketRequestHandler handler = m_server.GetHandlerForWebSocket(request.URI, out partial);

            if (handler == null)
            {
                return(null);
            }
            // Do we support the protocols requested?
            string protocol = null;

            if (request.Headers.ContainsKey(SecWebSocketProtocol))
            {
                foreach (string proto in request.Headers[SecWebSocketProtocol].Split(WebSocketProtocolSeparator))
                {
                    if (handler.WillAcceptRequest(partial, proto.Trim()))
                    {
                        protocol = proto.Trim();
                        break;
                    }
                }
            }
            else if (handler.WillAcceptRequest(partial, ""))
            {
                protocol = "";
            }
            if (protocol == null)
            {
                return(null);
            }
            // Finish the handshake
            byte[] security = Encoding.UTF8.GetBytes(request.Headers[SecWebSocketKey].Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            sha1.Initialize();
            sha1.HashCore(security, 0, security.Length);
            security = sha1.HashFinal();
            response.Headers[SecWebSocketAccept]     = Convert.ToBase64String(security);
            response.Headers[HttpHeaders.Upgrade]    = "websocket";
            response.Headers[HttpHeaders.Connection] = "Upgrade";
            response.ResponseCode = HttpResponseCode.SwitchingProtocols;
            if (protocol.Length > 0)
            {
                response.Headers[SecWebSocketProtocol] = protocol;
            }
            // And we are done
            return(handler);
        }
示例#27
0
        public byte[] Execute(HatContext context)
        {
            // search login into database

            // if found, then return account data
            // else return fail or create new account.

            HatUserFactory factory = HatUserFactory.Instance();

            HatUser u = factory.LoadOne(Encoding.Default.GetBytes(Login));

            if (u != null)
            {
                var sha  = new SHA1CryptoServiceProvider();
                var hash = sha.ComputeHash(Encoding.Default.GetBytes(Password));

                if (u.Password != BitConverter.ToString(hash))
                {
                    return(NetworkHelper.ClientMessageBuild(ClientOperation.SendMessage,
                                                            ClientMessage.M_INVALID_LOGIN_PASSWORD));
                }
            }
            else
            {
                if (Hat.Configuration.IsRegistrationAllowed)
                {
                    u = new HatUser();

                    u.Login = Login;

                    var sha  = new SHA1CryptoServiceProvider();
                    var hash = sha.ComputeHash(Encoding.Default.GetBytes(Password));

                    u.Password = BitConverter.ToString(hash);

                    factory.Save(u);
                }
                else
                {
                    return(NetworkHelper.ClientMessageBuild(ClientOperation.SendMessage,
                                                            ClientMessage.M_INVALID_LOGIN_PASSWORD));
                }
            }

            context.User = u;

            var characters = u.GetCharacters();

            var chars = new byte[characters.Count * 8 + 9];

            using (var mem = new MemoryStream(chars))
            {
                var bw = new BinaryWriter(mem);

                bw.Write((byte)0xCE);
                bw.Write((characters.Count * 8) + 4);
                bw.Write(Consts.HatIdentifier);
                foreach (var user in characters)
                {
                    bw.Write(user.CharacterId);
                }

                return(chars);
            }
        }
        private void GetPasswordStatus()
        {
            var pwd_sha_str = String.Empty;

            using (var sha1 = new SHA1CryptoServiceProvider())
            {
                var context  = new SprContext(PasswordEntry, Host.Database, SprCompileFlags.All);
                var password = SprEngine.Compile(PasswordEntry.Strings.GetSafe(PwDefs.PasswordField).ReadString(), context);

                var pwd_sha_bytes = sha1.ComputeHash(UTF8Encoding.UTF8.GetBytes(password));
                var sb            = new StringBuilder(2 * pwd_sha_bytes.Length);

                foreach (byte b in pwd_sha_bytes)
                {
                    sb.AppendFormat("{0:X2}", b);
                }
                pwd_sha_str = sb.ToString();
            }

            var latestFile = PluginOptions.HIBPFileName;

            if (!File.Exists(latestFile))
            {
                Status = "HIBP file not found";
                return;
            }

            using (FileStream fs = File.OpenRead(latestFile))
                using (StreamReader sr = new StreamReader(fs))
                {
                    try
                    {
                        string line;
                        Status = PluginOptions.SecureText;
                        int sha_len = pwd_sha_str.Length;

                        var low  = 0L;
                        var high = fs.Length;

                        while (low <= high)
                        {
                            var middle = (low + high + 1) / 2;
                            fs.Seek(middle, SeekOrigin.Begin);

                            // Resync with base stream after seek
                            sr.DiscardBufferedData();

                            line = sr.ReadLine();

                            if (sr.EndOfStream)
                            {
                                break;
                            }

                            // We may have read only a partial line so read again to make sure we get a full line
                            if (middle > 0)
                            {
                                line = sr.ReadLine() ?? String.Empty;
                            }

                            int compare = String.Compare(pwd_sha_str, line.Substring(0, sha_len), StringComparison.Ordinal);

                            if (compare < 0)
                            {
                                high = middle - 1;
                            }
                            else if (compare > 0)
                            {
                                low = middle + 1;
                            }
                            else
                            {
                                string[] tokens = line.Split(':');
                                Status          = PluginOptions.InsecureText;
                                insecureWarning = true;

                                if (PluginOptions.BreachCountDetails)
                                {
                                    Status += " (password count: " + tokens[1].Trim() + ")";
                                }

                                break;
                            }
                        }
                    }
                    catch
                    {
                        Status = "Failed to read HIBP file";
                    }
                }
        }
示例#29
0
        public MM_AdPlugin(AdDesc desc, AdCreatedCallbackMethod createdCallback, MonoBehaviour service)
        {
            this.service = service;

            try
            {
                this.desc = desc;
                testing   = desc.Testing;
                adEvent   = desc.EventCallback;

                gravity = AdGravity.CenterScreen;
                                #if !DISABLE_REIGN
                                #if UNITY_EDITOR
                refreshRate = desc.Editor_MillennialMediaAdvertising_RefreshRate;
                apid        = desc.Editor_MillennialMediaAdvertising_APID;
                userAgent   = "";
                gravity     = desc.Editor_MillennialMediaAdvertising_AdGravity;
                uiScale     = desc.Editor_AdScale;
#elif UNITY_BLACKBERRY
                refreshRate = desc.BB10_MillennialMediaAdvertising_RefreshRate;
                apid        = desc.BB10_MillennialMediaAdvertising_APID;

                IntPtr handle = IntPtr.Zero;
                if (Common.deviceinfo_get_details(ref handle) != 0)
                {
                    throw new Exception("Failed: deviceinfo_get_details");
                }
                string deviceType = Common.deviceinfo_details_get_keyboard(handle) == 0 ? "Touch" : "Kbd";
                Common.deviceinfo_free_details(ref handle);
                string osVersion = System.Text.RegularExpressions.Regex.Match(SystemInfo.operatingSystem, @"\d*\.\d*\.\d*\.\d*").Groups[0].Value;
                userAgent = WWW.EscapeURL("Mozilla/5.0 (BB10; " + deviceType + ") AppleWebKit/537.10+ (KHTML, like Gecko) Version/" + osVersion + " Mobile Safari/537.10+");

                gravity = desc.BB10_MillennialMediaAdvertising_AdGravity;
                uiScale = desc.BB10_AdScale;
#elif UNITY_WP8
                refreshRate = desc.WP8_MillennialMediaAdvertising_RefreshRate;
                apid        = desc.WP8_MillennialMediaAdvertising_APID;
                userAgent   = "";
                gravity     = desc.WP8_MillennialMediaAdvertising_AdGravity;
                uiScale     = desc.WP8_AdScale;
#elif UNITY_METRO
                refreshRate = desc.WinRT_MillennialMediaAdvertising_RefreshRate;
                apid        = desc.WinRT_MillennialMediaAdvertising_APID;
                userAgent   = "";
                gravity     = desc.WinRT_MillennialMediaAdvertising_AdGravity;
                uiScale     = desc.WinRT_AdScale;
#elif UNITY_IOS
                refreshRate = desc.iOS_MillennialMediaAdvertising_RefreshRate;
                apid        = desc.iOS_MillennialMediaAdvertising_APID;
                userAgent   = "";
                gravity     = desc.iOS_MillennialMediaAdvertising_AdGravity;
                uiScale     = desc.iOS_AdScale;
#elif UNITY_ANDROID
                refreshRate = desc.Android_MillennialMediaAdvertising_RefreshRate;
                apid        = desc.Android_MillennialMediaAdvertising_APID;
                userAgent   = "";
                gravity     = desc.Android_MillennialMediaAdvertising_AdGravity;
                uiScale     = desc.Android_AdScale;
#elif UNITY_STANDALONE_WIN
                refreshRate = desc.Win32_MillennialMediaAdvertising_RefreshRate;
                apid        = desc.Win32_MillennialMediaAdvertising_APID;
                userAgent   = "";
                gravity     = desc.Editor_MillennialMediaAdvertising_AdGravity;
                uiScale     = desc.Win32_AdScale;
#elif UNITY_STANDALONE_OSX
                refreshRate = desc.OSX_MillennialMediaAdvertising_RefreshRate;
                apid        = desc.OSX_MillennialMediaAdvertising_APID;
                userAgent   = "";
                gravity     = desc.OSX_MillennialMediaAdvertising_AdGravity;
                uiScale     = desc.OSX_AdScale;
#elif UNITY_STANDALONE_LINUX
                refreshRate = desc.Linux_MillennialMediaAdvertising_RefreshRate;
                apid        = desc.Linux_MillennialMediaAdvertising_APID;
                userAgent   = "";
                gravity     = desc.Linux_MillennialMediaAdvertising_AdGravity;
                uiScale     = desc.Linux_AdScale;
#endif
#endif

                // make sure ad refresh rate doesn't go under 1 min
                if (refreshRate < 60)
                {
                    refreshRate = 60;
                }

                // create or get device ID
                if (PlayerPrefs.HasKey("Reign_MMWebAds_DeviceID"))
                {
                    deviceID = PlayerPrefs.GetString("Reign_MMWebAds_DeviceID");
                }
                else
                {
                                        #if UNITY_EDITOR || UNITY_STANDALONE
                    var hash = new SHA1CryptoServiceProvider().ComputeHash(Guid.NewGuid().ToByteArray());
                    deviceID = BitConverter.ToString(hash).ToLower();
                                        #else
                    deviceID = Guid.NewGuid().ToString().Replace("-", "0").ToLower() + "0000";
                                        #endif

                    PlayerPrefs.SetString("Reign_MMWebAds_DeviceID", deviceID);
                }

                if (desc.UseClassicGUI)
                {
                    guiSytle = new GUIStyle()
                    {
                        stretchWidth  = true,
                        stretchHeight = true
                    };
                }
                else
                {
                    // Create Ad Canvas
                    adCanvas = new GameObject("MM Ad");
                    GameObject.DontDestroyOnLoad(adCanvas);
                    adCanvas.AddComponent <RectTransform>();
                    var canvas = adCanvas.AddComponent <Canvas>();
                    canvas.renderMode   = RenderMode.ScreenSpaceOverlay;
                    canvas.sortingOrder = 1000;
                    adCanvas.AddComponent <CanvasScaler>();
                    adCanvas.AddComponent <GraphicRaycaster>();

                    // Create ad
                    var ad = new GameObject("AdButtonImage");
                    ad.transform.parent = adCanvas.transform;
                    adRect                 = ad.AddComponent <RectTransform>();
                    adImage                = ad.AddComponent <Image>();
                    adImage.sprite         = Resources.Load <Sprite>("Reign/Ads/AdLoading");
                    adImage.preserveAspect = true;
                    var button = ad.AddComponent <Button>();
                    button.onClick.AddListener(adClicked);
                }

                // set default visible state
                Visible = desc.Visible;
                SetGravity(gravity);

                // load ad
                service.StartCoroutine(init(createdCallback));

                // set screen size changed callback
                ReignServices.ScreenSizeChangedCallback += ReignServices_ScreenSizeChangedCallback;
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
                if (createdCallback != null)
                {
                    createdCallback(false);
                }
            }
        }
示例#30
0
文件: IAMKey.cs 项目: radtek/safeid
        private static string GeraKey(String installKey, Boolean isServerKey, UInt32 numLic, Boolean isTemp, DateTime?tempDate, IAMVersion version)
        {
            byte[] buffer       = new byte[0];
            uint   totalSeconds = 0;

            if (isTemp)
            {
                DateTime?nullable  = tempDate;
                DateTime time      = new DateTime(0x7b2, 1, 1, 0, 0, 0);
                TimeSpan?nullable3 = nullable.HasValue ? new TimeSpan?(nullable.GetValueOrDefault() - time) : null;
                totalSeconds = (uint)nullable3.Value.TotalSeconds;
                //totalSeconds += 0x1517f;
            }

            using (MemoryStream stream = new MemoryStream())
            {
                if (version == IAMVersion.v100)
                {
                    stream.Write(secret1_v100, 0, secret1_v100.Length);
                }

                byte[] bytes = Encoding.ASCII.GetBytes(installKey.ToLower().Replace("-", "").Replace("/", "").Replace("\\", ""));
                stream.Write(bytes, 0, bytes.Length);
                ushort num2 = (ushort)(numLic ^ 0x33bb);
                bytes = BitConverter.GetBytes(num2);
                stream.Write(bytes, 0, bytes.Length);
                uint num3 = 0;
                num3  = totalSeconds ^ 0xffbb0033;
                bytes = BitConverter.GetBytes(num3);
                stream.Write(bytes, 0, bytes.Length);

                if (version == IAMVersion.v100)
                {
                    stream.Write(secret2_v100, 0, secret2_v100.Length);
                }

                num2  = (ushort)(numLic ^ 0xbb33);
                bytes = BitConverter.GetBytes(num2);
                stream.Write(bytes, 0, bytes.Length);
                num3  = totalSeconds ^ 0x33ffbb;
                bytes = BitConverter.GetBytes(num3);
                stream.Write(bytes, 0, bytes.Length);
                bytes = Encoding.ASCII.GetBytes(installKey.Replace("-", "").Replace("/", "").Replace("\\", ""));
                stream.Write(bytes, 0, bytes.Length);

                if (version == IAMVersion.v100)
                {
                    stream.Write(secret3_v100, 0, secret3_v100.Length);
                }

                stream.Flush();
                buffer = stream.ToArray();
            }

            byte[] buffer3 = new SHA1CryptoServiceProvider().ComputeHash(buffer);
            buffer3[3]  = ToByte((uint)((isServerKey ? 1 : 0) & 0xff));
            buffer3[4]  = ToByte((numLic >> 8) & 0xff);
            buffer3[6]  = ToByte(numLic & 0xff);
            buffer3[2]  = ToByte((totalSeconds >> 0x18) & 0xff);
            buffer3[12] = ToByte((totalSeconds >> 0x10) & 0xff);
            buffer3[9]  = ToByte((totalSeconds >> 8) & 0xff);
            buffer3[7]  = ToByte(totalSeconds & 0xff);


            String key = BitConverter.ToString(buffer3).Replace("-", "");

            string str5 = "";

            for (int j = 0; j < key.Length; j++)
            {
                if ((j > 0) && ((j % 8) == 0))
                {
                    str5 = str5 + '/';
                }
                str5 = str5 + key[j];
            }
            key = str5;

            return(key);
        }
示例#31
0
        public void UpdateCurrentGame(string playerName, string weaponString, string sessionID, string sessionHostName, string lobbyID, string lobbyHostName, bool isExpedition)
        {
            bool wasHost = CurrentGame.IsCurrentPlayerLobbyHost();

            CurrentGame.CurrentPlayerName     = playerName;
            CurrentGame.CurrentWeaponString   = weaponString;
            CurrentGame.SessionID             = sessionID;
            CurrentGame.SessionHostPlayerName = sessionHostName;
            CurrentGame.LobbyID              = lobbyID;
            CurrentGame.LobbyHostPlayerName  = lobbyHostName;
            CurrentGame.IsPlayerInExpedition = isExpedition;
            CurrentGame.IsValid              = true;
            if (ConfigHelper.Main.Values.Overlay.MonsterWidget.UseNetworkServer && ServerManager.Instance.IsServerOline == 1)
            {
                if (CurrentGame.IsPlayerOnline() && CurrentGame.IsPlayerInLobby())
                {
                    if (CurrentGame.IsCurrentPlayerLobbyHost() && !wasHost)
                    {
                        ServerManager.Instance.RequestCommadWithHandler(ServerManager.Command.ELEVATE, CurrentGame.key, null, true, 0, null);
                    }
                    if (!CurrentGame.LobbyID.Equals(OutdatedLobbyID))
                    {
                        SHA1 sha = new SHA1CryptoServiceProvider();
                        CurrentGame.key = Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(CurrentGame.SessionID + CurrentGame.LobbyID)));
                        if (CurrentGame.helloDone)
                        {
                            ServerManager.Instance.RequestCommadWithHandler(ServerManager.Command.DONE, Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(CurrentGame.SessionID + OutdatedLobbyID))), null, wasHost, 0, null, (result, ping) =>
                            {
                                if (result != null && !result["status"].ToString().Equals("error"))
                                {
                                    Core.Log.WriteLine($"Left lobby with id '{result["result"]}'");
                                }
                            });
                        }
                        CurrentGame.helloDone = false;
                        OutdatedLobbyID       = CurrentGame.LobbyID;
                    }
                    if (!CurrentGame.helloDone && networkOperationDone && DateTime.Now.Second - (lastNetworkOperationTime > DateTime.Now.Second ? lastNetworkOperationTime - 60 : lastNetworkOperationTime) >= 5)
                    {
                        networkOperationDone = false;
                        ServerManager.Instance.RequestCommadWithHandler(ServerManager.Command.HELLO, CurrentGame.key, null, CurrentGame.IsCurrentPlayerLobbyHost(), 0, null, (result, ping) =>
                        {
                            if (result != null && result["status"].ToString().Equals("ok"))
                            {
                                if (CurrentGame.key.Equals(result["result"].ToString()))
                                {
                                    Core.Log.WriteLine($"Joined lobby with id '{result["result"]}'");
                                    CurrentGame.helloDone = true;
                                }
                                else
                                {
                                    ServerManager.Instance.RequestCommadWithHandler(ServerManager.Command.DONE, result["result"].ToString(), null, wasHost, 0, null, (result, ping) =>
                                    {
                                        if (result != null && !result["status"].ToString().Equals("error"))
                                        {
                                            Core.Log.WriteLine($"Left lobby with id '{result["result"]}'");
                                        }
                                    });
                                }
                            }
                            else
                            {
                                CurrentGame.helloDone = false;
                            }
                            networkOperationDone     = true;
                            lastNetworkOperationTime = DateTime.Now.Second;
                        }, (error) =>
                        {
                            networkOperationDone     = true;
                            lastNetworkOperationTime = DateTime.Now.Second;
                        });
                    }
                    else if (CurrentGame.helloDone && networkOperationDone && !(CurrentGame.IsCurrentPlayerLobbyHost() && CurrentGame.IsPlayerAlone()) && !CurrentGame.checkDone && DateTime.Now.Second - (lastNetworkOperationTime > DateTime.Now.Second ? lastNetworkOperationTime - 60 : lastNetworkOperationTime) >= 5)
                    {
                        networkOperationDone = false;
                        ServerManager.Instance.RequestCommadWithHandler(ServerManager.Command.CHECK, CurrentGame.key, null, CurrentGame.IsCurrentPlayerLobbyHost(), 0, null, (result, ping) =>
                        {
                            if (result != null && result["status"].ToString().Equals("ok"))
                            {
                                CurrentGame.checkDone = result["result"].ToString().Equals("true");
                            }
                            else if (result != null && result["result"].ToString().Equals("0"))
                            {
                                CurrentGame.helloDone = false;
                                CurrentGame.checkDone = false;
                            }
                            else
                            {
                                CurrentGame.checkDone = false;
                            }
                            networkOperationDone     = true;
                            lastNetworkOperationTime = DateTime.Now.Second;
                        }, (error) =>
                        {
                            CurrentGame.checkDone    = false;
                            networkOperationDone     = true;
                            lastNetworkOperationTime = DateTime.Now.Second;
                        });
                    }
                }
                else
                {
                    if (CurrentGame.helloDone)
                    {
                        ServerManager.Instance.RequestCommadWithHandler(ServerManager.Command.DONE, CurrentGame.key, null, wasHost, 0, null, (result, ping) =>
                        {
                            if (result != null && !result["status"].ToString().Equals("error"))
                            {
                                Core.Log.WriteLine($"Left lobby with id '{result["result"]}'");
                            }
                            ServerManager.Instance.PrintStats();
                            ServerManager.Instance.ResetStats();
                        }, (error) =>
                        {
                            ServerManager.Instance.PrintStats();
                            ServerManager.Instance.ResetStats();
                        });
                    }
                    CurrentGame.key       = "";
                    CurrentGame.helloDone = false;
                    CurrentGame.checkDone = false;
                    networkOperationDone  = true;
                }
            }
        }
示例#32
0
        void ValidateDownload()
        {
            //if an Adler32 checksum is provided, check the file
            if (!bw.CancellationPending)
            {
                if (Adler32 != 0 && Adler32 != downloadedAdler32.Value)
                {
                    // file failed to vaildate, throw an error
                    throw new Exception("The downloaded file \"" + Path.GetFileName(DownloadingTo) + "\" failed the Adler32 validation.");
                }

                if (PublicSignKey != null)
                {
                    if (SignedSHA1Hash == null)
                    {
                        throw new Exception("The downloaded file \"" + Path.GetFileName(DownloadingTo) + "\" is not signed.");
                    }

                    byte[] hash = null;

                    try
                    {
                        using (FileStream fs = new FileStream(DownloadingTo, FileMode.Open, FileAccess.Read))
                            using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
                            {
                                hash = sha1.ComputeHash(fs);
                            }

                        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                        RSA.FromXmlString(PublicSignKey);

                        RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA);
                        RSADeformatter.SetHashAlgorithm("SHA1");

                        // verify signed hash
                        if (!RSADeformatter.VerifySignature(hash, SignedSHA1Hash))
                        {
                            // The signature is not valid.
                            throw new Exception("Verification failed.");
                        }
                    }
                    catch (Exception ex)
                    {
                        string msg = "The downloaded file \"" + Path.GetFileName(DownloadingTo) +
                                     "\" failed the signature validation: " + ex.Message;

                        long sizeInBytes = new FileInfo(DownloadingTo).Length;

                        msg += "\r\n\r\nThis error is likely caused by a download that ended prematurely. Total size of the downloaded file: " + BytesToString(sizeInBytes, false);

                        // show the size in bytes only if the size displayed isn't already in bytes
                        if (sizeInBytes >= 0.9 * 1024)
                        {
                            msg += " (" + sizeInBytes + " bytes).";
                        }

                        if (hash != null)
                        {
                            msg += "\r\n\r\nComputed SHA1 hash of the downloaded file: " + BitConverter.ToString(hash);
                        }

                        throw new Exception(msg);
                    }
                }
            }
        }
示例#33
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);
    }
示例#34
0
        public static void Load(string embeddedResource,
                                string fileName)
        {
            if (_dic == null)
            {
                _dic = new Dictionary <string, Assembly>();
            }

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

            using (var stm = curAsm.GetManifestResourceStream(embeddedResource))
            {
                if (stm == null)
                {
                    return;
                }

                ba = new byte[(int)stm.Length];
                stm.Read(ba,
                         0,
                         (int)stm.Length);
                try
                {
                    asm = Assembly.Load(ba);

                    _dic.Add(asm.GetName().Name,
                             asm);
                    return;
                }
                catch
                {
                }
            }

            bool   fileOk;
            string tempFile;

            using (var sha1 = new SHA1CryptoServiceProvider())
            {
                var fileHash = BitConverter.ToString(sha1.ComputeHash(ba))
                               .Replace("-",
                                        string.Empty);

                tempFile = Path.GetTempPath() + fileName;

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

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

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

            asm = Assembly.LoadFile(tempFile);

            _dic.Add(asm.GetName().Name,
                     asm);
        }
示例#35
0
        private byte[] GetXMACsLogonKey(KVInfo KVI)
        {
            RSACryptoServiceProvider Provider = LoadXMACs();

            byte[] TimeTick = new byte[0x10];
            new Random(Environment.TickCount).NextBytes(TimeTick);

            byte[] EncryptedTick = Provider.Encrypt(TimeTick, true);
            Array.Reverse(EncryptedTick);

            byte[] DestBuffer = Keys.XMACS_REQ;
            Array.Copy(EncryptedTick, 0, DestBuffer, 0x2C, 0x100);
            byte[] InputBuffer = FileEx.ReadBytes(KVI.Location, 0xB0, 12);
            byte[] Source      = FileEx.ReadBytes(KVI.Location, 0x9C8, 0x1A8);
            byte[] Exponent    = FileEx.ReadBytes(KVI.Location, 0x29C, 4);
            byte[] KeyParams   = FileEx.ReadBytes(KVI.Location, 0x2A8, 0x1C0);
            byte[] ConsoleID   = FileEx.ReadBytes(KVI.Location, 0x9CA, 5);
            byte[] ClientName  = ComputeClientName(ConsoleID);
            byte[] UTCTime     = BitConverter.GetBytes(DateTime.UtcNow.ToFileTime());
            Array.Reverse(UTCTime);

            KVI.Serial = Conversion.BytesToHexString(ConsoleID);

            byte[] TimeStamp = Conversion.HexStringToBytes("301aa011180f32303132313231323139303533305aa10502030b3543");
            Array.Copy(Encoding.ASCII.GetBytes(DateTime.Now.ToUniversalTime().ToString("yyyyMMddHHmmssZ")), 0, TimeStamp, 6, 15);

            byte[] EncryptedHMAC = RC4HMACEncrypt(TimeTick, 0x10, TimeStamp, TimeStamp.Length, 1);
            byte[] TickChecksum  = SHA1.Create().ComputeHash(TimeTick);

            SHA1CryptoServiceProvider SHAProvider = new SHA1CryptoServiceProvider();

            SHAProvider.TransformBlock(TimeTick, 0, 8, null, 0);
            SHAProvider.TransformBlock(InputBuffer, 0, 12, null, 0);
            SHAProvider.TransformFinalBlock(TickChecksum, 0, 20);
            byte[] HeaderChecksum = SHAProvider.Hash;

            RSACryptoServiceProvider   Key       = LoadConsolePrivateKey(Exponent, KeyParams);
            RSAPKCS1SignatureFormatter Formatter = new RSAPKCS1SignatureFormatter(Key);

            Formatter.SetHashAlgorithm("SHA1");
            byte[] Signature = Formatter.CreateSignature(HeaderChecksum);
            Array.Reverse(Signature);
            // Build the final packet
            Array.Copy(TimeTick, 0, DestBuffer, 300, 8);
            Array.Copy(InputBuffer, 0, DestBuffer, 0x134, 12);
            Array.Copy(Signature, 0, DestBuffer, 320, 0x80);
            Array.Copy(Source, 0, DestBuffer, 0x1C0, 0x1A8);
            Array.Copy(EncryptedHMAC, 0, DestBuffer, 0x3E0, 0x34);
            Array.Copy(ClientName, 0, DestBuffer, 0x430, 15);
            // Connect and send packet
            UdpClient XEAS = new UdpClient();

            XEAS.Connect("XEAS.XBOXLIVE.COM", 0x58);
            XEAS.Send(DestBuffer, DestBuffer.Length);
            IPEndPoint RemoteEP = new IPEndPoint(0L, 0);
            int        Wait     = 0;

            while (true)
            {
                try {
                    Thread.Sleep(10);
                    if (XEAS.Available > 0)
                    {
                        byte[] RecBuffer = XEAS.Receive(ref RemoteEP);
                        byte[] Buffer    = new byte[0x6C];
                        Array.Copy(RecBuffer, 0x35, Buffer, 0, 0x6C);
                        byte[] DecryptNoonce   = RC4HMACDecrypt(ComputeKdcNoonce(TimeTick, 0x10), 0x10, RecBuffer, 0x6C, 0x4B3);
                        byte[] SecondaryBuffer = new byte[0x10];
                        Array.Copy(DecryptNoonce, 0x4C, SecondaryBuffer, 0, 0x10);
                        return(SecondaryBuffer);
                    }
                    Thread.Sleep(500);

                    if (Wait++ == 10)
                    {
                        return(null);
                    }
                } catch { }
            }
        }
示例#36
0
        /// <summary>
        /// Create the hash.
        /// This method is written with the help of Lyquidity library, many thanks for this nice sample
        /// </summary>
        /// <param name="password">The password</param>
        /// <param name="encryptionInfo">The encryption info extracted from the ENCRYPTIOINFO stream inside the OLE document</param>
        /// <returns>The hash to encrypt the document</returns>
        private byte[] GetPasswordHashBinary(string password, EncryptionInfoBinary encryptionInfo)
        {
            byte[] hash     = null;
            byte[] tempHash = new byte[4 + 20];    //Iterator + prev. hash
            try
            {
                HashAlgorithm hashProvider;
                if (encryptionInfo.Header.AlgIDHash == AlgorithmHashID.SHA1 || encryptionInfo.Header.AlgIDHash == AlgorithmHashID.App && (encryptionInfo.Flags & Flags.fExternal) == 0)
                {
#if (Core)
                    hashProvider = SHA1.Create();
#else
                    hashProvider = new SHA1CryptoServiceProvider();
#endif
                }
                else if (encryptionInfo.Header.KeySize > 0 && encryptionInfo.Header.KeySize < 80)
                {
                    throw new NotSupportedException("RC4 Hash provider is not supported. Must be SHA1(AlgIDHash == 0x8004)");
                }
                else
                {
                    throw new NotSupportedException("Hash provider is invalid. Must be SHA1(AlgIDHash == 0x8004)");
                }

                hash = GetPasswordHash(hashProvider, encryptionInfo.Verifier.Salt, password, 50000, 20);

                // Append "block" (0)
                Array.Copy(hash, tempHash, hash.Length);
                Array.Copy(System.BitConverter.GetBytes(0), 0, tempHash, hash.Length, 4);
                hash = hashProvider.ComputeHash(tempHash);

                /***** Now use the derived key algorithm *****/
                byte[] derivedKey   = new byte[64];
                int    keySizeBytes = encryptionInfo.Header.KeySize / 8;

                //First XOR hash bytes with 0x36 and fill the rest with 0x36
                for (int i = 0; i < derivedKey.Length; i++)
                {
                    derivedKey[i] = (byte)(i < hash.Length ? 0x36 ^ hash[i] : 0x36);
                }


                byte[] X1 = hashProvider.ComputeHash(derivedKey);

                //if verifier size is bigger than the key size we can return X1
                if ((int)encryptionInfo.Verifier.VerifierHashSize > keySizeBytes)
                {
                    return(FixHashSize(X1, keySizeBytes));
                }

                //Else XOR hash bytes with 0x5C and fill the rest with 0x5C
                for (int i = 0; i < derivedKey.Length; i++)
                {
                    derivedKey[i] = (byte)(i < hash.Length ? 0x5C ^ hash[i] : 0x5C);
                }

                byte[] X2 = hashProvider.ComputeHash(derivedKey);

                //Join the two and return
                byte[] join = new byte[X1.Length + X2.Length];

                Array.Copy(X1, 0, join, 0, X1.Length);
                Array.Copy(X2, 0, join, X1.Length, X2.Length);


                return(FixHashSize(join, keySizeBytes));
            }
            catch (Exception ex)
            {
                throw (new Exception("An error occured when the encryptionkey was created", ex));
            }
        }
示例#37
0
        public static List <MBFileRecord> ReadMBDB(string BackupPath)
        {
            try
            {
                List <MBFileRecord> files;
                byte[]                    signature = new byte[6];           // buffer signature
                byte[]                    buf       = new byte[26];          // buffer for .mbdx record
                StringBuilder             sb        = new StringBuilder(40); // stringbuilder for the Key
                byte[]                    data      = new byte[40];          // buffer for the fixed part of .mbdb record
                SHA1CryptoServiceProvider hasher    = new SHA1CryptoServiceProvider();

                System.DateTime unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);


                // open the database
                FileStream mbdb = new FileStream(Path.Combine(BackupPath, "Manifest.mbdb"), FileMode.Open, FileAccess.Read);

                // skip signature
                mbdb.Read(signature, 0, 6);
                if (BitConverter.ToString(signature, 0) != "6D-62-64-62-05-00")     // "mbdb\5\0"
                {
                    throw new Exception("bad .mbdb file");
                }

                files = new List <MBFileRecord>();

                // loop through the records
                for (int i = 0; mbdb.Position < mbdb.Length; ++i)
                {
                    MBFileRecord rec = new MBFileRecord();

                    rec.Domain     = getS(mbdb);
                    rec.Path       = getS(mbdb);
                    rec.LinkTarget = getS(mbdb);
                    rec.DataHash   = getD(mbdb);
                    rec.alwaysNull = getD(mbdb);

                    mbdb.Read(data, 0, 40);

                    rec.data = toHex(data, 2, 4, 4, 4, 4, 4, 4, 4, 8, 1, 1);

                    rec.Mode       = BigEndianBitConverter.ToUInt16(data, 0);
                    rec.alwaysZero = BigEndianBitConverter.ToInt32(data, 2);
                    rec.inode      = BigEndianBitConverter.ToUInt32(data, 6);
                    rec.UserId     = BigEndianBitConverter.ToUInt32(data, 10);  // or maybe GroupId (don't care...)
                    rec.GroupId    = BigEndianBitConverter.ToUInt32(data, 14);  // or maybe UserId

                    rec.aTime = unixEpoch.AddSeconds(BigEndianBitConverter.ToUInt32(data, 18));
                    rec.bTime = unixEpoch.AddSeconds(BigEndianBitConverter.ToUInt32(data, 22));
                    rec.cTime = unixEpoch.AddSeconds(BigEndianBitConverter.ToUInt32(data, 26));

                    rec.FileLength = BigEndianBitConverter.ToInt64(data, 30);

                    rec.flag          = data[38];
                    rec.PropertyCount = data[39];

                    rec.Properties = new MBFileRecord.Property[rec.PropertyCount];
                    for (int j = 0; j < rec.PropertyCount; ++j)
                    {
                        rec.Properties[j].Name  = getS(mbdb);
                        rec.Properties[j].Value = getD(mbdb);
                    }

                    StringBuilder fileName = new StringBuilder();
                    byte[]        fb       = hasher.ComputeHash(ASCIIEncoding.UTF8.GetBytes(rec.Domain + "-" + rec.Path));
                    for (int k = 0; k < fb.Length; k++)
                    {
                        fileName.Append(fb[k].ToString("x2"));
                    }

                    rec.key = fileName.ToString();

                    files.Add(rec);
                }

                return(files);
            }
            catch (Exception e)
            {
                Console.WriteLine("exception: {0}", e.Message);
            }

            return(null);
        }
示例#38
0
 /// <summary>
 /// 计算字符串的 SHA1 签名
 /// </summary>
 /// <param name="text"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public static string Sha1(this string text, Encoding encoding = null)
 {
     using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider()) {
         return(HashString(sha1, text, encoding));
     }
 }
示例#39
0
        private static byte[] firmaDocumento(byte[] pdfData, X509Certificate2 cert)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                var reader = new PdfReader(pdfData);
                var stp    = PdfStamper.CreateSignature(reader, stream, '\0');
                var sap    = stp.SignatureAppearance;

                //Protect certain features of the document
                stp.SetEncryption(null,
                                  Guid.NewGuid().ToByteArray(), //random password
                                  PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_SCREENREADERS,
                                  PdfWriter.ENCRYPTION_AES_256);

                //Get certificate chain
                var cp        = new Org.BouncyCastle.X509.X509CertificateParser();
                var certChain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) };

                sap.SetCrypto(null, certChain, null, PdfSignatureAppearance.WINCER_SIGNED);

                //Set signature appearance
                //BaseFont helvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
                //Font font = new Font(helvetica, 12, iTextSharp.text.Font.NORMAL);
                //sap.Layer2Font = font;
                sap.SetVisibleSignature(new iTextSharp.text.Rectangle(415, 100, 585, 40), 1, null);

                var dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
                //Set some stuff in the signature dictionary.
                dic.Date = new PdfDate(sap.SignDate);
                dic.Name = cert.Subject;    //Certificate name
                if (sap.Reason != null)
                {
                    dic.Reason = sap.Reason;
                }
                if (sap.Location != null)
                {
                    dic.Location = sap.Location;
                }

                //Set the crypto dictionary
                sap.CryptoDictionary = dic;

                //Set the size of the certificates and signature.
                int csize = 4096; //Size of the signature - 4K

                //Reserve some space for certs and signatures
                var reservedSpace = new Dictionary <PdfName, int>();
                reservedSpace[PdfName.CONTENTS] = csize * 2 + 2; //*2 because binary data is stored as hex strings. +2 for end of field
                sap.PreClose(reservedSpace);                     //Actually reserve it

                //Build the signature
                HashAlgorithm sha = new SHA1CryptoServiceProvider();

                var    sapStream = sap.GetRangeStream();
                int    read      = 0;
                byte[] buff      = new byte[8192];
                while ((read = sapStream.Read(buff, 0, 8192)) > 0)
                {
                    sha.TransformBlock(buff, 0, read, buff, 0);
                }
                sha.TransformFinalBlock(buff, 0, 0);

                byte[] pk = SignMsg(sha.Hash, cert, false);

                //Put the certs and signature into the reserved buffer
                byte[] outc = new byte[csize];
                Array.Copy(pk, 0, outc, 0, pk.Length);

                //Put the reserved buffer into the reserved space
                PdfDictionary certificateDictionary = new PdfDictionary();
                certificateDictionary.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));

                //Write the signature
                sap.Close(certificateDictionary);
                //Close the stamper and save it
                stp.Close();

                reader.Close();

                //Return the saved pdf
                return(stream.GetBuffer());
            }
        }
示例#40
0
 public void Setup()
 {
     HashAdapterInstance   = HashFactory.Adapter.CreateHashAlgorithmFromHash(HashFactory.Crypto.CreateSHA1());
     HashAlgorithmInstance = new SHA1CryptoServiceProvider();
 }
        /// <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;
        }
示例#42
0
        private static byte[] ComputeSHA1Hash(string src)
        {
            SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();

            return(SHA1.ComputeHash(Encoding.Default.GetBytes(src)));
        }
示例#43
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;
    }
示例#44
0
        /// <summary>
        ///     Creates a signature value given a signature base and the consumer secret and a known token secret.
        /// </summary>
        /// <param name="signatureMethod">The hashing method</param>
        /// <param name="signatureTreatment">The treatment to use on a signature value</param>
        /// <param name="signatureBase">The signature base</param>
        /// <param name="consumerSecret">The consumer secret</param>
        /// <param name="tokenSecret">The token secret</param>
        /// <returns></returns>
        public static string GetSignature(OAuthSignatureMethod signatureMethod,
                                          OAuthSignatureTreatment signatureTreatment,
                                          string signatureBase, string consumerSecret, string tokenSecret)
        {
            if (tokenSecret.IsNullOrBlank())
            {
                tokenSecret = string.Empty;
            }

            var unencodedConsumerSecret = consumerSecret;

            consumerSecret = Uri.EscapeDataString(consumerSecret);
            tokenSecret    = Uri.EscapeDataString(tokenSecret);

            string signature;

            switch (signatureMethod)
            {
            case OAuthSignatureMethod.HmacSha1:
            {
                var crypto = new HMACSHA1();
                var key    = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

                crypto.Key = encoding.GetBytes(key);
                signature  = signatureBase.HashWith(crypto);
                break;
            }

            case OAuthSignatureMethod.HmacSha256:
            {
                var crypto = new HMACSHA256();
                var key    = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

                crypto.Key = encoding.GetBytes(key);
                signature  = signatureBase.HashWith(crypto);
                break;
            }

            case OAuthSignatureMethod.RsaSha1:
            {
                using (var provider = new RSACryptoServiceProvider {
                        PersistKeyInCsp = false
                    })
                {
                    provider.FromXmlString2(unencodedConsumerSecret);
                    SHA1CryptoServiceProvider hasher = new SHA1CryptoServiceProvider();
                    //System.Security.Cryptography.SHA1Cng hasher = new System.Security.Cryptography.SHA1Cng();

                    byte[] hash = hasher.ComputeHash(encoding.GetBytes(signatureBase));

                    signature = Convert.ToBase64String(provider.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")));
                }
                break;
            }

            case OAuthSignatureMethod.PlainText:
            {
                signature = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

                break;
            }

            default:
                throw new NotImplementedException("Only HMAC-SHA1, HMAC-SHA256, and RSA-SHA1 are currently supported.");
            }

            var result = signatureTreatment == OAuthSignatureTreatment.Escaped
                ? UrlEncodeRelaxed(signature)
                : signature;

            return(result);
        }
示例#45
0
        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="provider"></param>
        /// <param name="base64DecodingSignStr"></param>
        /// <param name="srcByte"></param>
        /// <returns></returns>
        public static bool ValidateBySoft(RSACryptoServiceProvider provider, byte[] base64DecodingSignStr, byte[] srcByte)
        {
            HashAlgorithm hashalg = new SHA1CryptoServiceProvider();

            return(provider.VerifyData(srcByte, hashalg, base64DecodingSignStr));
        }
示例#46
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
    }
示例#47
0
文件: RSA.cs 项目: cangjie/lq_yeepay
    private static string encrypt(byte[] data, string publicKey, string input_charset)
    {
        RSACryptoServiceProvider rsa = DecodePemPublicKey(publicKey);
            SHA1 sh = new SHA1CryptoServiceProvider();
            byte[] result = rsa.Encrypt(data, false);

            return Convert.ToBase64String(result);
    }
示例#48
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);
 }
示例#49
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            while (true)
            {
                if (_isWebSocket)
                {
                    IByteBuffer buffer;
                    _lastReadBuffer?.ResetReaderIndex();
                    if (_lastReadBuffer != null && _lastReadBuffer.ReadableBytes != 0)
                    {
                        buffer = ByteBufferUtil.DefaultAllocator.HeapBuffer(
                            _lastReadBuffer.ReadableBytes + ((IByteBuffer)message).ReadableBytes);
                        buffer.WriteBytes(_lastReadBuffer);
                        buffer.WriteBytes((IByteBuffer)message);
                        _lastReadBuffer = buffer;
                    }
                    else
                    {
                        buffer          = (IByteBuffer)message;
                        _lastReadBuffer = buffer;
                    }

                    if (buffer.ReadableBytes < 2)
                    {
                        return;
                    }

                    IByteBuffer bufferCopy = ByteBufferUtil.DefaultAllocator.HeapBuffer(buffer.Capacity);
                    buffer.ReadBytes(bufferCopy, 2);
                    if ((bufferCopy.GetByte(0) & 8) == 8)
                    {
                        //操作码位8表示断开连接
                        context.CloseAsync();

                        return;
                    }

                    byte[] maskKey = { 0, 0, 0, 0 };
                    bool   masked  = false;
                    byte   lenMark = bufferCopy.GetByte(1);
                    if (lenMark >= 128)
                    {
                        masked   = true;
                        lenMark -= 128;
                    }

                    int offset = 0;
                    int len    = 0;
                    if (lenMark <= 125)
                    {
                        offset = 2;
                        len    = lenMark;
                    }
                    else if (lenMark == 126)
                    {
                        offset = 4;

                        if (buffer.ReadableBytes < 2)
                        {
                            return;
                        }

                        buffer.ReadBytes(bufferCopy, 2);
                        len = bufferCopy.GetUnsignedShort(2);
                    }
                    else if (lenMark == 127)
                    {
                        offset = 10;

                        if (buffer.ReadableBytes < 8)
                        {
                            return;
                        }

                        buffer.ReadBytes(bufferCopy, 8);
                        len = (int)bufferCopy.GetLong(2);
                    }

                    if (masked)
                    {
                        if (buffer.ReadableBytes < 4)
                        {
                            return;
                        }

                        buffer.ReadBytes(bufferCopy, 4);
                        for (int i = 0; i < 4; i++)
                        {
                            maskKey[i] = bufferCopy.GetByte(offset + i);
                        }

                        offset += 4;
                    }

                    if (buffer.ReadableBytes < len)
                    {
                        return;
                    }

                    buffer.ReadBytes(bufferCopy, len);
                    IByteBuffer output = ByteBufferUtil.DefaultAllocator.HeapBuffer(len);
                    for (int i = 0; i < len; i++)
                    {
                        output.WriteByte(bufferCopy.GetByte(offset + i) ^ maskKey[i % 4]);
                    }

                    _lastReadBuffer.MarkReaderIndex();
                    base.ChannelRead(context, output);

                    if (_lastReadBuffer.ReadableBytes <= 0)
                    {
                        return;
                    }

                    _lastReadBuffer = null;
                    message         = buffer;

                    continue;
                }

                try
                {
                    var         buffer     = (IByteBuffer)message;
                    IByteBuffer bufferCopy = buffer.Copy();
                    var         bytes      = new byte[bufferCopy.ReadableBytes];
                    bufferCopy.ReadBytes(bytes);
                    string       data = Encoding.ASCII.GetString(bytes);
                    const string requestWebSocketMark = "Sec-WebSocket-Key:";
                    int          index = data.IndexOf(requestWebSocketMark, StringComparison.Ordinal);
                    if (index < 0)
                    {
                        throw new Exception();
                    }

                    data = data.Substring(index + requestWebSocketMark.Length + 1);
                    var key = new StringBuilder();
                    foreach (char t in data)
                    {
                        if (IsBase64Char(t))
                        {
                            key.Append(t);
                        }
                        else
                        {
                            break;
                        }
                    }

                    key.Append("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    data = Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(key.ToString())));
                    sha1.Dispose();
                    StringBuilder ret = new StringBuilder();
                    ret.Append("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ");
                    ret.Append(data);
                    ret.Append("\r\nUpgrade: websocket\r\n\r\n");
                    IByteBuffer output = ByteBufferUtil.DefaultAllocator.HeapBuffer();
                    output.WriteBytes(Encoding.UTF8.GetBytes(ret.ToString()));
                    context.WriteAndFlushAsync(output);

                    _isWebSocket = true;
                }
                catch
                {
                    base.ChannelRead(context, message);
                }
                finally
                {
                    if (_isWebSocket)
                    {
                        context.Channel.Pipeline.Remove <LengthFieldBasedFrameDecoder>();
                        context.Channel.Pipeline.Remove <LengthFieldPrepender>();
                    }
                    else
                    {
                        context.Channel.Pipeline.Remove(this);
                    }
                }

                break;
            }
        }
示例#50
0
        public CrossServerTestMulticonn(RemoteServer server1, RemoteServer server2, RemoteServer server3,
                                        RemoteServer[] allConnections, bool putDupesToAll)
        {
            _server1        = server1;
            _server2        = server2;
            _server3        = server3;
            _allConnections = allConnections;

            Console.WriteLine("Putting 100 random assets to server1");
            Console.WriteLine(DateTime.Now);
            SHA1 sha = new SHA1CryptoServiceProvider();


            for (int i = 0; i < 100; i++)
            {
                string uuidstr       = OpenMetaverse.UUID.Random().ToString();
                byte[] randomBytes   = TestUtil.RandomBytes(500, 800000);
                byte[] challengeHash = sha.ComputeHash(randomBytes);
                _assetUuids.Add(uuidstr);
                _existingAssets.Add(uuidstr, challengeHash);

                Asset asset = new Asset(uuidstr, 1,
                                        false, false, 0, "Random Asset", "Radom Asset Desc", randomBytes);
                _server1.PutAsset(asset);
            }

            Console.WriteLine("Done: " + DateTime.Now);

            Console.WriteLine("Putting 100 random assets to server2");
            Console.WriteLine(DateTime.Now);


            for (int i = 0; i < 100; i++)
            {
                string uuidstr       = OpenMetaverse.UUID.Random().ToString();
                byte[] randomBytes   = TestUtil.RandomBytes(500, 800000);
                byte[] challengeHash = sha.ComputeHash(randomBytes);
                _assetUuids.Add(uuidstr);
                _existingAssets.Add(uuidstr, challengeHash);

                Asset asset = new Asset(uuidstr, 1,
                                        false, false, 0, "Random Asset", "Radom Asset Desc", randomBytes);
                _server2.PutAsset(asset);
            }

            Console.WriteLine("Done: " + DateTime.Now);

            Console.WriteLine("Putting 100 random assets to server3");
            Console.WriteLine(DateTime.Now);


            for (int i = 0; i < 100; i++)
            {
                string uuidstr       = OpenMetaverse.UUID.Random().ToString();
                byte[] randomBytes   = TestUtil.RandomBytes(500, 800000);
                byte[] challengeHash = sha.ComputeHash(randomBytes);
                _assetUuids.Add(uuidstr);
                _existingAssets.Add(uuidstr, challengeHash);

                Asset asset = new Asset(uuidstr, 1,
                                        false, false, 0, "Random Asset", "Radom Asset Desc", randomBytes);
                _server3.PutAsset(asset);
            }

            Console.WriteLine("Putting  duplicate assets to all servers");

            for (int i = 0; i < 20; i++)
            {
                string uuidstr       = OpenMetaverse.UUID.Random().ToString();
                byte[] randomBytes   = TestUtil.RandomBytes(500, 800000);
                byte[] challengeHash = sha.ComputeHash(randomBytes);
                _assetUuids.Add(uuidstr);
                _existingAssets.Add(uuidstr, challengeHash);

                Asset asset = new Asset(uuidstr, 1,
                                        false, false, 0, "Random Asset", "Radom Asset Desc", randomBytes);
                _server1.PutAsset(asset);

                if (putDupesToAll)
                {
                    _server2.PutAsset(asset);
                    _server3.PutAsset(asset);
                }

                _assetsThatExistOnAll.Add(uuidstr);
            }

            Console.WriteLine("Done: " + DateTime.Now);
        }
示例#51
0
        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())
            {
                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);

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

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

            asm = Assembly.LoadFile(tempFile);

            _dic.Add(asm.FullName, asm);
        }
示例#52
0
        void ProcessRecieved(byte[] data, int ClientID)
        {
            int t;

            switch (data[0])
            {
            case 0x00:     //LOGIN
            {
                ColoredConsole.ConsoleWriteGreenWithOut("Recieved Logon Challenge!");
                int clientVersion = (((int)data[11]) * 256) + data[12];
                if (clientVersion == 55574)
                {
                    ColoredConsole.ConsoleWriteBlueWithOutAndWithDate("Cient version accepted: 2.0.0, ID = 56085!");
                }
                else
                {
                    ColoredConsole.ConsoleWriteErrorWithOne("Wrong client version {0}. Excpected is 2.0.0, ID = 56085!", clientVersion);
                    //return;
                }
                byte userlenght = data[33];
                username = new byte[userlenght];
                string usern = "";
                for (t = 0; t < userlenght; t++)
                {
                    username[t] = data[34 + t];
                    usern      += "" + (char)data[34 + t];
                    //ColoredConsole.ConsoleWriteGreenWithOne("{0}", "" + ((char)username[t]).ToString());
                }
                ColoredConsole.ConsoleWriteGreenWithOne("Recieved AUTH_CHALLENGE from user: {0}", usern);
                userNumber = World.FindUserByUsername(usern);
                if (userNumber == -1)
                {
                    SendToOneClient(new byte[] { 0x00, 0x00, 0x15 }, ClientID);
                    ColoredConsole.ConsoleWriteErrorWithOut("Wrong login.");
                    return;
                }
                string pass     = "******" + Database.Data.AccountArray.pass[userNumber];
                char[] passchar = pass.ToCharArray();
                byte[] passbyte = new byte[passchar.Length];
                int    ti       = 0;
                foreach (char c in passchar)
                {
                    passbyte[ti++] = (byte)c;
                }
                byte[] user = Concat(username, passbyte);
                SHA1   sha  = new SHA1CryptoServiceProvider();
                byte[] hash = sha.ComputeHash(user, 0, user.Length);
                byte[] res  = new Byte[hash.Length + salt.Length];
                t = 0;
                rand.NextBytes(salt);
                foreach (byte s in salt)
                {
                    res[t++] = s;
                }
                foreach (byte s in hash)
                {
                    res[t++] = s;
                }
                byte[] hash2 = sha.ComputeHash(res, 0, res.Length);
                byte[] x     = Reverse(hash2);

                rN = Reverse(N);
                rand.NextBytes(b);
                rb = Reverse(b);

                BigInteger bi  = new BigInteger(x);
                BigInteger bi2 = new BigInteger(rN);
                BigInteger g   = new BigInteger(new byte[] { 7 });
                v = g.modPow(bi, bi2);

                K     = new BigInteger(new Byte[] { 3 });
                temp1 = K * v;
                temp2 = g.modPow(new BigInteger(rb), new BigInteger(rN));
                temp3 = temp1 + temp2;
                B     = temp3 % new BigInteger(rN);
                byte[] pack = new byte[119];
                pack[0] = pack[1] = 0;
                byte[] tB = Reverse(B.getBytes());
                for (t = 0; t < tB.Length; t++)
                {
                    pack[3 + t] = tB[t];
                }
                pack[35] = 1;        // g_length
                pack[36] = 7;        // g
                pack[37] = 32;       // n_len
                for (t = 0; t < N.Length; t++)
                {
                    pack[38 + t] = N[t];
                }
                for (t = 0; t < salt.Length; t++)
                {
                    pack[70 + t] = salt[t];
                }
                //for( t = 0;t < 16;t++ )
                for (t = 0; t < 17; t++)
                {
                    pack[102 + t] = 0;
                }

                SendToOneClient(pack, ClientID);
                LoginAccount.user = usern;
                LoginAccount.pass = Database.Data.AccountArray.pass[userNumber];
                return;
            }

            case 0x01:     //LOGON PROOF
            {
                ColoredConsole.ConsoleWriteGreenWithOut("Logon proof!");
                //Console.WriteLine("Logon proof" );
                byte[] A = new byte[32];
                for (t = 0; t < 32; t++)
                {
                    A[t] = data[t + 1];
                }
                byte[] kM1 = new byte[20];
                for (t = 0; t < 20; t++)
                {
                    kM1[t] = data[t + 1 + 32];
                }

                //A = new byte[] { 0x23, 0x2f, 0xb1, 0xb8, 0x85, 0x29, 0x64, 0x3d, 0x95, 0xb8, 0xdc, 0xe7, 0x8f, 0x27, 0x50, 0xc7, 0x5b, 0x2d, 0xf3, 0x7a, 0xcb, 0xa8, 0x73, 0xeb, 0x31, 0x07, 0x38, 0x39, 0xed, 0xa0, 0x73, 0x8d };
                byte[] rA = Reverse(A);
                //	B = new BigInteger( new byte[] { 0x64, 0x5d, 0x1f, 0x78, 0x97, 0x30, 0x73, 0x70, 0x1e, 0x12, 0xbc, 0x98, 0xaa, 0x38, 0xea, 0x99, 0xb4, 0xbc, 0x43, 0x5c, 0x32, 0xe8, 0x44, 0x7c, 0x73, 0xab, 0x07, 0x7a, 0xe4, 0xd7, 0x59, 0x64 } );
                byte[] AB = Concat(A, Reverse(B.getBytes()));

                SHA1   shaM1 = new SHA1CryptoServiceProvider();
                byte[] U     = shaM1.ComputeHash(AB);
                //	U = new byte[] { 0x2f, 0x49, 0x69, 0xac, 0x9f, 0x38, 0x7f, 0xd6, 0x72, 0x23, 0x6f, 0x94, 0x91, 0xa5, 0x16, 0x77, 0x7c, 0xdd, 0xe1, 0xc1 };
                byte[] rU = Reverse(U);

                temp1 = v.modPow(new BigInteger(rU), new BigInteger(rN));
                temp2 = temp1 * new BigInteger(rA);
                temp3 = temp2.modPow(new BigInteger(rb), new BigInteger(rN));

                byte[] S1   = new byte[16];
                byte[] S2   = new byte[16];
                byte[] S    = new byte[32];
                byte[] temp = temp3.getBytes();

                /*	Console.WriteLine("temp");
                 *  HexViewer.View( temp, 0, temp.Length );
                 *  Console.WriteLine("temp1 {0}", temp1.ToHexString());
                 *  Console.WriteLine("temp2 {0}", temp2.ToHexString());
                 *  Console.WriteLine("temp3 {0}", temp3.ToHexString());*/
                Buffer.BlockCopy(temp, 0, S, 0, temp.Length);
                byte[] rS = Reverse(S);


                for (t = 0; t < 16; t++)
                {
                    S1[t] = rS[t * 2];
                    S2[t] = rS[(t * 2) + 1];
                }
                byte[] hashS1 = shaM1.ComputeHash(S1);
                byte[] hashS2 = shaM1.ComputeHash(S2);
                SS_Hashs[userNumber].SS_Hash = new byte[hashS1.Length + hashS2.Length];
                for (t = 0; t < hashS1.Length; t++)
                {
                    SS_Hashs[userNumber].SS_Hash[t * 2]       = hashS1[t];
                    SS_Hashs[userNumber].SS_Hash[(t * 2) + 1] = hashS2[t];
                }

                //	SS_Hash = new byte[] { 0x02, 0x61, 0xf4, 0xeb, 0x48, 0x91, 0xb6, 0x6a, 0x1a, 0x82, 0x6e, 0xb7, 0x79, 0x28, 0xd8, 0x64, 0xb7, 0xea, 0x14, 0x54, 0x38, 0xdb, 0x7c, 0xfd, 0x0d, 0x3d, 0x2f, 0xc0, 0x22, 0xce, 0xcc, 0x46, 0x83, 0x79, 0xf2, 0xc0, 0x87, 0x78, 0x7f, 0x14 };

                byte[] NHash    = shaM1.ComputeHash(N);
                byte[] GHash    = shaM1.ComputeHash(new byte[] { 7 });
                byte[] userHash = shaM1.ComputeHash(username);
                byte[] NG_Hash  = new byte[20];
                for (t = 0; t < 20; t++)
                {
                    NG_Hash[t] = (byte)(NHash[t] ^ GHash[t]);
                }
                byte[] Temp = Concat(NG_Hash, userHash);
                Temp = Concat(Temp, salt);
                Temp = Concat(Temp, A);
                Temp = Concat(Temp, B.getBytes());
                Temp = Concat(Temp, K.getBytes());        //SS_Hash );

                byte[] M1 = shaM1.ComputeHash(Temp);

                Temp = Concat(A, kM1);
                Temp = Concat(Temp, SS_Hashs[userNumber].SS_Hash);

                byte[] M2 = shaM1.ComputeHash(Temp);

                byte[] retur = new byte[M2.Length + 4 /*NG_Hash.Length */ + 2];
                //	byte []retur = new byte[ M2.Length + NG_Hash.Length + 2 ];
                retur[0] = 0x1;
                retur[1] = 0x0;
                for (t = 0; t < M2.Length; t++)
                {
                    retur[t + 2] = M2[t];
                }

                //for(t = 0;t < NG_Hash.Length;t++ )
                //	retur[ t + 2 + 20 ] = NG_Hash[ t ];

                //	set the account properties
                //Console.WriteLine("Logon proof for {0}", IP.ToString());
                LoginAccount.Ip   = IP;
                LoginAccount.Port = 0;
                LoginAccount.K    = SS_Hashs[userNumber].SS_Hash;

                SendToOneClient(retur, ClientID);
                return;
            }

            case 0x02:    //Reconnect challenge
            {
                ColoredConsole.ConsoleWriteGreenWithOut("Reconnect challenge!");
                byte[] packRecoChallenge = new byte[34];
                packRecoChallenge[0] = 0x02;
                packRecoChallenge[1] = 0x00;
                for (t = 0; t < 16; t++)
                {
                    packRecoChallenge[18 + t] = 0;
                }
                SendToOneClient(packRecoChallenge, ClientID);
                return;
            }

            case 0x03:    //Reconnect proof
            {
                ColoredConsole.ConsoleWriteGreenWithOut("Reconnect proof!");
                SendToOneClient(new byte[] { 0x03, 0x00 }, ClientID);
                return;
            }

            case 0x04:    //Update server
                //	Console.WriteLine( "Update server" );
                break;

            case 0x10:    //Realm List
                ColoredConsole.ConsoleWriteGreenWithOut("Client requested realmlist!");
                string ip      = World.DNS.AddressList[0].ToString();
                byte[] retData = new byte[25 + ip.Length + World.ServerName.Length + World.WorldPort.ToString().Length];
                int    offset  = 0;
                Converter.ToBytes((byte)0x10, retData, ref offset);
                Converter.ToBytes((byte)43, retData, ref offset);
                Converter.ToBytes(1 /*World.allConnectedChars.Count*/, retData, ref offset);
                Converter.ToBytes((byte)0, retData, ref offset);
                Converter.ToBytes(1, retData, ref offset);
                Converter.ToBytes((short)0, retData, ref offset);
                Converter.ToBytes(World.ServerName, retData, ref offset);
                Converter.ToBytes((byte)0, retData, ref offset);
                Converter.ToBytes(ip, retData, ref offset);
                Converter.ToBytes((byte)':', retData, ref offset);
                Converter.ToBytes(World.ServerPort.ToString(), retData, ref offset);
                Converter.ToBytes((byte)0, retData, ref offset);
                Converter.ToBytes(0, retData, ref offset);
                //	Converter.ToBytes( (short)0, retData, ref offset );//	cr erreir
                //Converter.ToBytes( (short)1, retData, ref offset );
                //Converter.ToBytes( (short)2, retData, ref offset );

                Converter.ToBytes((short)ClientsConnected, retData, ref offset);
                Converter.ToBytes((byte)0, retData, ref offset);
                Converter.ToBytes((short)1, retData, ref offset);
                int atlen = 1;
                offset -= 3;
                Converter.ToBytes(offset, retData, ref atlen);
                //Console.WriteLine("Connected player(s) {0}", ClientsConnected);
                /*	if ( World.allConnectedChars.Count < 3 )*/
                //Thread.Sleep( 500 );
                SendToOneClient(retData, ClientID);
                return;

            default:    //UNKNOWN OPCODE
            {
                ColoredConsole.ConsoleWriteErrorWithOne("Recieve unknown OPCode: {0}", data[0]);
                return;
            }
            }
        }
示例#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;
    }
示例#54
0
        private static byte[] GetSHA1(string password)
        {
            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();

            return(sha.ComputeHash(System.Text.Encoding.ASCII.GetBytes(password)));
        }
示例#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);
    }
示例#56
0
        public string OneWayEncrypt(string plainText)
        {
            SHA1 sha = new SHA1CryptoServiceProvider();

            return(Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(plainText))));
        }
示例#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);
    }
示例#58
0
        private void updateTextFile(int buttonId, String url, String path, String filename, String description, Button button, PictureBox pic, ref String newContents)
        {
            enableButtons(false);
            shouldBeEnabled[buttonId] = false;

            if (readyToGo[buttonId])
            {
                readyToGo[buttonId] = false;

                if (newContents == null)
                {
                    MessageBox.Show(this, "Sorry, no data found. Please close the update window and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    enableButtons(true);
                    pic.Image = Properties.Resources.x;
                    return;
                }

                button.Text = String.Format("Writing updates to {0}.", filename);
                button.Refresh();

                using (StreamWriter sw = new StreamWriter(path, false))
                {
                    sw.Write(newContents);
                    sw.Close();
                }

                button.Text = String.Format("You now have the latest {0}.", description);
                pic.Image   = Properties.Resources.check;
                if (buttonId == Blocks)
                {
                    ColorPalette.Reset();
                    ColorPalette.Preload();
                }
                else if (buttonId == Biomes)
                {
                    BiomeType.Reset();
                    ((Form1)Owner).FillLists();
                }

                enableButtons(true);
                return;
            }

            enableButtons(false);
            shouldBeEnabled[buttonId] = false;
            button.Text = String.Format("Checking for updates to {0}.", filename);
            button.Refresh();

            String json = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.Headers["Accept-Encoding"] = "gzip,deflate";
                request.AutomaticDecompression     = DecompressionMethods.GZip | DecompressionMethods.Deflate;
                request.UserAgent = userAgent;
                request.Proxy     = null;

                HttpWebResponse response       = (HttpWebResponse)request.GetResponse();
                StreamReader    responseStream = new StreamReader(response.GetResponseStream());
                json = responseStream.ReadToEnd();
                response.Close();
                responseStream.Close();
            }
            catch (Exception)
            {
                button.Text = "Unable to connect to GitHub. Please try again later.";
                shouldBeEnabled[buttonId] = true;
                readyToGo[buttonId]       = false;
                enableButtons(true);
                pic.Image = Properties.Resources.x;
                return;
            }

            json = json.Replace("\\n", "");

            String serverSha = new Regex("[\"']sha[\"']: ?\"([^\"']+)[\"']", RegexOptions.IgnoreCase | RegexOptions.Multiline).Match(json).Groups[1].Value;

            byte[] raw      = File.ReadAllBytes(path);
            byte[] head     = Encoding.UTF8.GetBytes("blob " + raw.Length.ToString() + "\0");
            byte[] combined = new byte[head.Length + raw.Length];
            head.CopyTo(combined, 0);
            raw.CopyTo(combined, head.Length);

            SHA1   sha1     = new SHA1CryptoServiceProvider();
            String localSha = BitConverter.ToString(sha1.ComputeHash(combined)).Replace("-", "").ToLower();

            if (serverSha == localSha)
            {
                button.Text = String.Format("You have the latest {0}. No action is necessary.", description);
                shouldBeEnabled[buttonId] = false;
                readyToGo[buttonId]       = false;
                enableButtons(true);
                pic.Image = Properties.Resources.check;
            }
            else
            {
                newContents = new Regex("[\"']content[\"']: ?\"([^\"']+)[\"']", RegexOptions.IgnoreCase | RegexOptions.Multiline).Match(json).Groups[1].Value;
                newContents = Encoding.UTF8.GetString(Convert.FromBase64String(newContents));
                button.Text = String.Format("Updated {0} available! Click to save a new copy of {1}.", description, filename);
                shouldBeEnabled[buttonId] = true;
                readyToGo[buttonId]       = true;
                enableButtons(true);
                pic.Image = Properties.Resources.bang;
            }
        }
示例#59
0
        /// <summary>
        /// Computes the Hash code of a string.
        /// </summary>
        /// <param name="input">The string.</param>
        /// <returns>The Hash code.</returns>
        private static byte[] ComputeBytes(string input)
        {
            SHA1 sha1 = SHA1CryptoServiceProvider.Create();

            return(sha1.ComputeHash(Encoding.ASCII.GetBytes(input)));
        }
示例#60
0
 private void CalEncHash_Click(object sender, EventArgs e)
 {
     if (HashAlg.Text == "SHA1")
     {
         string     inName = EncFile.Text;
         FileStream fin    = new FileStream(inName, FileMode.Open, FileAccess.Read);
         byte[]     HashData;
         byte[]     CypherText;
         SHA1       sha = new SHA1CryptoServiceProvider();
         HashData = sha.ComputeHash(fin);
         fin.Close();
         System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
         SendRsaKey   = rsa.ToXmlString(true);
         ARsaKey.Text = SendRsaKey;
         rsa.FromXmlString(SendRsaKey);
         CypherText      = rsa.Encrypt(HashData, false);
         EncHash.Text    = Convert.ToBase64String(HashData);
         EncRsaHash.Text = Convert.ToBase64String(CypherText);
         if (EncAlg.Text == "DES")
         {
             DES    des = new DESCryptoServiceProvider();
             byte[] key = new byte[8];
             for (int i = 0; i < 8; i++)
             {
                 key[i] = (byte)EncKey.Text[i];
             }
             byte[] inputByteArray     = Convert.FromBase64String(EncRsaHash.Text);
             System.IO.MemoryStream ms = new System.IO.MemoryStream();
             using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, key), CryptoStreamMode.Write))
             {
                 cs.Write(inputByteArray, 0, inputByteArray.Length);
                 cs.FlushFinalBlock();
                 cs.Close();
             }
             EncAlgHash.Text = Convert.ToBase64String(ms.ToArray());
         }
         else if (EncAlg.Text == "AES")
         {
             AesManaged aes = new AesManaged();
             byte[]     key = new byte[16];
             for (int i = 0; i < 16; i++)
             {
                 key[i] = (byte)EncKey.Text[i];
             }
             byte[] inputByteArray     = Convert.FromBase64String(EncRsaHash.Text);
             System.IO.MemoryStream ms = new System.IO.MemoryStream();
             using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(key, key), CryptoStreamMode.Write))
             {
                 cs.Write(inputByteArray, 0, inputByteArray.Length);
                 cs.FlushFinalBlock();
                 cs.Close();
             }
             EncAlgHash.Text = Convert.ToBase64String(ms.ToArray());
         }
         else
         {
             MessageBox.Show("请选择加密算法");
         }
     }
     if (HashAlg.Text == "MD5")
     {
         string     inName = EncFile.Text;
         FileStream fin    = new FileStream(inName, FileMode.Open, FileAccess.Read);
         byte[]     HashData;
         byte[]     CypherText;
         MD5        md5 = new MD5CryptoServiceProvider();
         HashData = md5.ComputeHash(fin);
         fin.Close();
         System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
         SendRsaKey   = rsa.ToXmlString(true);
         ARsaKey.Text = SendRsaKey;
         rsa.FromXmlString(SendRsaKey);
         CypherText      = rsa.Encrypt(HashData, false);
         EncHash.Text    = Convert.ToBase64String(HashData);
         EncRsaHash.Text = Convert.ToBase64String(CypherText);
         if (EncAlg.Text == "DES")
         {
             DES    des = new DESCryptoServiceProvider();
             byte[] key = new byte[8];
             for (int i = 0; i < 8; i++)
             {
                 key[i] = (byte)EncKey.Text[i];
             }
             byte[] inputByteArray     = Convert.FromBase64String(EncRsaHash.Text);
             System.IO.MemoryStream ms = new System.IO.MemoryStream();
             using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, key), CryptoStreamMode.Write))
             {
                 cs.Write(inputByteArray, 0, inputByteArray.Length);
                 cs.FlushFinalBlock();
                 cs.Close();
             }
             EncAlgHash.Text = Convert.ToBase64String(ms.ToArray());
         }
         else if (EncAlg.Text == "AES")
         {
             AesManaged aes = new AesManaged();
             byte[]     key = new byte[16];
             for (int i = 0; i < 16; i++)
             {
                 key[i] = (byte)EncKey.Text[i];
             }
             byte[] inputByteArray     = Convert.FromBase64String(EncRsaHash.Text);
             System.IO.MemoryStream ms = new System.IO.MemoryStream();
             using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(key, key), CryptoStreamMode.Write))
             {
                 cs.Write(inputByteArray, 0, inputByteArray.Length);
                 cs.FlushFinalBlock();
                 cs.Close();
             }
             EncAlgHash.Text = Convert.ToBase64String(ms.ToArray());
         }
         else
         {
             MessageBox.Show("请选择加密算法");
         }
     }
 }