public void WhenICyptWordShouldBeDifferent() { var word = "teste"; var encryptedResult = rsaCrypto.Encrypt(word); Assert.AreEqual(encryptedResult.Count, 5); }
public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { Token = TokenSecure = String.Empty; SessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); _cookies = new CookieContainer(); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // userAuth.Timeout = TimeSpan.FromSeconds(5); // Generate an AES session key. var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // AES encrypt the loginkey with our session key. byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; // Get the Authentification Result. try { Dictionary <string, object> sessionArgs = new Dictionary <string, object>() { { "steamid", client.SteamID.ConvertToUInt64() }, { "sessionkey", cryptedSessionKey }, { "encrypted_loginkey", cryptedLoginKey } }; authResult = userAuth.Call(HttpMethod.Post, "AuthenticateUser", args: sessionArgs); } catch (Exception hehe) { Console.WriteLine("Unable to make AuthenticateUser API Request: {0}", hehe.Message); Token = TokenSecure = null; return(false); } Token = authResult["token"].AsString(); TokenSecure = authResult["tokensecure"].AsString(); // Adding cookies to the cookie container. _cookies.Add(new Cookie("sessionid", SessionID, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLogin", Token, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("Steam_Language", "english", string.Empty, SteamCommunityDomain)); Console.WriteLine("Crukies: " + VerifyCookies()); return(true); } }
private static bool AuthenticateUser() { // 32 byte random blob of data var sessionKey = CryptoHelper.GenerateRandomBlock(32); byte[] encryptedSessionKey; // ... which is then encrypted with RSA using the Steam system's public key using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(Steam.Instance.Client.Universe))) { encryptedSessionKey = rsa.Encrypt(sessionKey); } // users hashed loginkey, AES encrypted with the sessionkey var encryptedLoginKey = CryptoHelper.SymmetricEncrypt(Encoding.ASCII.GetBytes(WebAPIUserNonce), sessionKey); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { KeyValue result; try { result = userAuth.AuthenticateUser( steamid: Steam.Instance.Client.SteamID.ConvertToUInt64(), sessionkey: WebHelpers.UrlEncode(encryptedSessionKey), encrypted_loginkey: WebHelpers.UrlEncode(encryptedLoginKey), method: "POST", secure: true ); } catch (WebException e) { var response = (HttpWebResponse)e.Response; if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) { IsAuthorized = false; if (Steam.Instance.Client.IsConnected) { Steam.Instance.User.RequestWebAPIUserNonce(); } } Log.WriteWarn("WebAuth", "Failed to authenticate: {0}", e.Message); return(false); } Cookies = new CookieContainer(); Cookies.Add(new Cookie("steamLogin", result["token"].AsString(), "/", "store.steampowered.com")); Cookies.Add(new Cookie("steamLoginSecure", result["tokensecure"].AsString(), "/", "store.steampowered.com")); } IsAuthorized = true; Log.WriteInfo("WebAuth", "Authenticated"); return(true); }
private void PublicKeyEncrypt_Click(object sender, EventArgs e) { String body = textBox_Body.Text.Trim(), publicKey = textBox_PublicKey.Text.Trim(); if (String.IsNullOrEmpty(body)) { MessageBox.Show("待处理文本不能为空", "温馨提示"); return; } if (String.IsNullOrEmpty(publicKey)) { MessageBox.Show("公钥不能为空", "温馨提示"); return; } try { textBox_CryptBody.Text = RSACrypto.Encrypt(body, publicKey, false); } catch (Exception ex) { MessageBox.Show(ex.Message, "错误"); logSaveProvider.SaveLog(LogProvider.Factories.LogEntityFactory.Create(ex)); } }
private static string encryptDiffieHellmanKeys(BigInteger key, RSACrypto rsa) { byte[] sKeyBytes = convertKeyToBytes(key); byte[] sKeyRsaBytes = rsa.Encrypt(sKeyBytes); string sKeyRsa = Converter.BytesToHexString(sKeyRsaBytes); return(sKeyRsa); }
public void Authorize(License license) { var specText = JsonConvert.SerializeObject(license.Specification); var hash = Hash.KnuthHash(specText); var ctx = _crypto.Encrypt(BitConverter.GetBytes(hash), true, true); license.AuthorizationCode = Convert.ToBase64String(ctx); }
public static async Task <WebSession> AuthenticateWebSession( this SteamClient client, string userNonce ) { // Generate random SessionId var sessionId = Guid.NewGuid().ToString("N"); // Generate an AES SessionKey. var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] encryptedSessionKey; using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe))) { encryptedSessionKey = rsa.Encrypt(sessionKey); } // AES encrypt the loginkey with our session key. var encryptedLoginKey = CryptoHelper.SymmetricEncrypt( Encoding.ASCII.GetBytes(userNonce), sessionKey ); try { using (var steamUserAuth = WebAPI.GetAsyncInterface("ISteamUserAuth")) { var result = await steamUserAuth.CallAsync( HttpMethod.Post, "AuthenticateUser", 1, new Dictionary <string, object> { { "steamid", client.SteamID.ConvertToUInt64().ToString() }, { "sessionkey", encryptedSessionKey }, { "encrypted_loginkey", encryptedLoginKey } } ).ConfigureAwait(false); return(new WebSession( client.SteamID.ConvertToUInt64(), result["token"]?.Value?.ToUpper(), result["tokensecure"]?.Value?.ToUpper(), sessionId, null, null )); } } catch { return(null); } }
public async Task <bool> AuthenticateAsync(ulong steamId, SteamClient client, string myLoginKey) { mToken = mTokenSecure = ""; mSessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamId.ToString())); mCookieContainer = new CookieContainer(); KeyValue response; using (WebAPI.AsyncInterface iSteamUserAuth = client.Configuration.GetAsyncWebAPIInterface("ISteamUserAuth")) { // generate an AES session key var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = Encoding.UTF8.GetBytes(myLoginKey); // aes encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); try { response = await iSteamUserAuth.CallAsync( HttpMethod.Post, "AuthenticateUser", args : new Dictionary <string, object>(3, StringComparer.Ordinal) { { "encrypted_loginkey", cryptedLoginKey }, { "sessionkey", cryptedSessionKey }, { "steamid", client.SteamID.ConvertToUInt64() } }); } catch (TaskCanceledException e) { mToken = mTokenSecure = null; return(false); } catch (Exception e) { mToken = mTokenSecure = null; return(false); } mToken = response["token"].AsString(); mTokenSecure = response["tokensecure"].AsString(); mCookieContainer.Add(new Cookie("sessionid", mSessionId, String.Empty, mSteamCommunityDomain)); mCookieContainer.Add(new Cookie("steamLogin", mToken, String.Empty, mSteamCommunityDomain)); mCookieContainer.Add(new Cookie("steamLoginSecure", mTokenSecure, String.Empty, mSteamCommunityDomain)); return(true); } }
///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> /// <param name="myUniqueId">Id what you get to login.</param> /// <param name="client">An instance of a SteamClient.</param> /// <param name="myLoginKey">Login Key of your account.</param> /// <returns>A bool, which is true if the login was successful.</returns> public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { Token = TokenSecure = ""; SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); _cookies = new CookieContainer(); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // Generate an AES session key. var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // AES encrypt the loginkey with our session key. byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; // Get the Authentification Result. try { authResult = userAuth.AuthenticateUser( steamid: client.SteamID.ConvertToUInt64(), sessionkey: HttpUtility.UrlEncode(cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey), method: "POST", secure: true ); } catch (Exception e) { Token = TokenSecure = null; return(false); } Token = authResult["token"].AsString(); TokenSecure = authResult["tokensecure"].AsString(); // Adding cookies to the cookie container. _cookies.Add(new Cookie("sessionid", SessionId, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLogin", Token, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("Steam_Language", "english", string.Empty, SteamCommunityDomain)); return(true); } }
public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { mToken = mTokenSecure = ""; mSessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); mCookieContainer = new CookieContainer(); using (var userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // generate an AES session key var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // aes encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; try { var dict = new System.Collections.Generic.Dictionary <string, object>() { { "steamid", client.SteamID.ConvertToUInt64() }, { "sessionkey", cryptedSessionKey }, { "encrypted_loginkey", cryptedLoginKey }, { "secure", true } }; authResult = userAuth.Call(System.Net.Http.HttpMethod.Post, "AuthenticateUser", 1, dict); } catch (Exception) { mToken = mTokenSecure = null; return(false); } mToken = authResult["token"].AsString(); mTokenSecure = authResult["tokensecure"].AsString(); mCookieContainer.Add(new Cookie("sessionid", mSessionId, string.Empty, mSteamCommunityDomain)); mCookieContainer.Add(new Cookie("steamLogin", mToken, string.Empty, mSteamCommunityDomain)); mCookieContainer.Add(new Cookie("steamLoginSecure", mTokenSecure, string.Empty, mSteamCommunityDomain)); return(true); } }
static void Main(string[] args) { string plaintext = "abc"; string strmd5 = "900150983CD24FB0D6963F7D28E17F72"; string strdes = "Wr+MOY7jM8M="; //MD5 var s1 = MD5Crypto.Encrypt(plaintext); Console.WriteLine("MD5 加密:{0} {1} {2}", s1 == strmd5, strmd5, s1); Console.WriteLine(); //DES var s2 = DESCrypto.Encrypt(plaintext); Console.WriteLine("DES 加密:{0} {1} {2}", s2 == strdes, strdes, s2); var s3 = DESCrypto.Decrypt(s2); Console.WriteLine("DES 解密:{0} {1} {2}", s3 == plaintext, plaintext, s3); Console.WriteLine(); //RSA string modulus = "nJDcBWNIV+DzZb8ZY5h4JJInVwVy5NvJ9hG0qH0TUM36j5DUFeUivBIdX+7fxwKIxPRkRyvwVjGjnMxna3Kq53Y5BLGpl84DvRqPGjxly2kAitbuHRIR5iiuza0rbA+ZPo/8kNrbRCYquaqnL1KIrDcIh7bZDWN6qY22+RVaVvs="; string publicExponent = "AQAB"; string privateExponent = "ZZTTPCerc2D/ar9vYKA3KzssjRh68CPuSFo6hasJEj9iVy2XfVE6lR2Hs4uP41YwmOEcAtVuTO5OAljYrO0sFpdYNrEthZG5UBkC2wH+SsXOAaTDb2YRCEsdxFA8MRqRQLux/9/Fef/oIk+od1sjC3WzBwMqvVHBO232u9V9suE="; //公钥加密 var s4 = RSACrypto.EncryptByPublicExponent(plaintext, modulus, publicExponent); Console.WriteLine("RSA 公钥加密:" + s4); string p = "y8v6G7Ap6jeTHILLAjQT0auvd9kRh91txQ4YkGf8ocijRbThKgAtWUrvNx27km6PEetWqw0VnA2YN53v6WCBMQ=="; string q = "xKuz+9vgOYZf9WvA0vU8byCmZd93mYrw+uAymUiT6jvG1MQ0vAQMW7wwoifJYIqWFNZo356R6g2OeOz8Edfv6w=="; string dp = "vqI3et721ljWC71tGMqOH3txz7IFbAn9PG9LGwmqj8uWrwXb+eXghb5KtkvhwcAZpLF3iNncdPViheP/H1degQ=="; string dq = "dZ+ruYo7hKwVYBbd8E2zo1MHsg4A3df3YFQObxa1QHYX6NCgKYLSUVswSws4qYC5WiUR/Aw+gJkzCKfT6mgXmQ=="; string inverseQ = "Fohpu2QfkHBCy11L0MV88pX3+EszJWWSgXqsGUzxTx0c2WK33o5wZkjq0AEKgk19aOOJc0RoKwcw6vtRRux/+Q=="; //私钥解密 var s5 = RSACrypto.DecryptByPrivateExponent(s4, modulus, privateExponent, publicExponent, p, q, dp, dq, inverseQ); var s55 = RSACrypto.Decrypt(s4, modulus, privateExponent); Console.WriteLine("RSA 私钥解密 : {0} {1} {2}", s5 == plaintext, plaintext, s5); Console.WriteLine("RSA 私钥解密2: {0} {1} {2}", s55 == plaintext, plaintext, s55); Console.WriteLine(); //私钥加密 var s6 = RSACrypto.Encrypt(plaintext, modulus, privateExponent); Console.WriteLine("RSA 私钥加密:" + s6); //公钥解密 var str6 = RSACrypto.Decrypt(s6, modulus, publicExponent); Console.WriteLine("RSA 公钥解密2:{0} {1} {2}", str6 == plaintext, plaintext, str6); Console.ReadKey(); }
private void enc_btn_rsa_Click(object sender, EventArgs e) { if (check_file_rsa == true) { rsa_enc_path = rsa.Encrypt_File(message_rsa.Text); enc_message_rsa.Text = rsa_enc_path; } else { rsa_enc_message = rsa.Encrypt(message_rsa.Text); enc_message_rsa.Text = rsa_enc_message; } }
///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> public static bool Authenticate(string myUniqueId, SteamClient client, out string sessionId, out string token, out string tokensecure, string myLoginKey) { sessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // generate an AES session key var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // aes encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; try { authResult = userAuth.AuthenticateUser( steamid: client.SteamID.ConvertToUInt64(), sessionkey: HttpUtility.UrlEncode(cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey), method: "POST", secure: true ); } catch (Exception) { token = null; tokensecure = null; return(false); } token = authResult ["token"].AsString(); tokensecure = authResult["tokensecure"].AsString(); return(true); } }
public void Test() { using (var rsaCrypto = new RSACrypto()) { rsaCrypto.Initialize(new Dictionary <string, object> { { "Algorithm", "RSA" }, { "PublicKey", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD2KXcCt30MrOOt4F1vhtfNViBGapFRmxaOnSVK9FMPV63Pr8Y3EzFpLFH58TzbNtwoB5aWRy4zjImbwsy5S2eqmSkJQWbWZiyxMLEYy1+dQDr27SihLp7BvrDUj8uy+LIO6fwCDMKJ2sQtXh+Uk6AO9meqdpA5riUEDVQKbpw6IQIDAQAB" }, { "PrivateKey", "MIICXQIBAAKBgQD2KXcCt30MrOOt4F1vhtfNViBGapFRmxaOnSVK9FMPV63Pr8Y3EzFpLFH58TzbNtwoB5aWRy4zjImbwsy5S2eqmSkJQWbWZiyxMLEYy1+dQDr27SihLp7BvrDUj8uy+LIO6fwCDMKJ2sQtXh+Uk6AO9meqdpA5riUEDVQKbpw6IQIDAQABAoGBAL0EW+kPIgtgmjdCaByiKwT11DSd0dYawzhg/GjQsRK/3avzKb3SlAdRS+UjUvp05poqMXxVTemxSVz8OJ0zhHYePa+wE0E31sBfnMxpOo5LIraTQuKGhE5IXNgUB0xYyAkG4vLLmoGDFCUHWPHYw5591C66eNyhJMSkPcqSCbMNAkEA+8HXhp3Ut1LVqBFnSpUIoRkUfXotWvfJjat6GGtmyglSRqTcUkVwIlBabVEMDyoMS9/LQcXM2QQ3bJiTKpDY3wJBAPpPe8Tfjm2o1Oxz8aGjnt+u2b4SZ9WXXkbZY1qsMNAkrP7ZFF5MTIm9L18V+yrvZ0mU7YC5Mck+F5eEbIxOTP8CQQDf0X1i2H58XNBGEvLZg5WgY0OsKiqYbSJrKL/rZdCEXbUfyQF2wvTmDLnX5e3qrV8xNUzmtIthhDYh/aMYfJ3RAkAMy39SIvNO27B2nb6eOpTmbjOnKZ2xJ1mkWXxgqCiemyFUrZgC8fd/mvIO9DqwiShIdJpnWBAZb1kZX6WEzoPVAkAz0CHiCH5JGdf71zCifbfFfcXA9+IXqQxvU9+3yGLAQW1S7xd94f8uOX+CsWsUchOpwmgzXYpvMLEtu822WqfF" } }); var plainText = "SmartSql"; var cipherText = rsaCrypto.Encrypt(plainText); var decryptText = rsaCrypto.Decrypt(cipherText); Assert.Equal(plainText, decryptText); } }
public byte[] EnPwd_UTF8(List <byte[]> data) { string input_str = Encoding.UTF8.GetString(data[0]); string public_key = Encoding.UTF8.GetString(data[1]); try { RSACrypto rsaCrypto = new RSACrypto("", public_key); // StartWith -----BEGIN PUBLIC KEY----- 216 EndWith -----END PUBLIC KEY----- return(Encoding.UTF8.GetBytes(rsaCrypto.Encrypt(input_str))); } catch (Exception) { return(Encoding.UTF8.GetBytes("")); } }
void HandleEncryptRequest(IPacketMsg packetMsg) { var encRequest = new Msg <MsgChannelEncryptRequest>(packetMsg); EUniverse eUniv = encRequest.Body.Universe; uint protoVersion = encRequest.Body.ProtocolVersion; DebugLog.WriteLine("CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion); DebugLog.Assert(protoVersion == 1, "CMClient", "Encryption handshake protocol version mismatch!"); byte[] pubKey = KeyDictionary.GetPublicKey(eUniv); if (pubKey == null) { DebugLog.WriteLine("CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion); return; } ConnectedUniverse = eUniv; var encResp = new Msg <MsgChannelEncryptResponse>(); tempSessionKey = CryptoHelper.GenerateRandomBlock(32); byte[] cryptedSessKey = null; using (var rsa = new RSACrypto(pubKey)) { cryptedSessKey = rsa.Encrypt(tempSessionKey); } byte[] keyCrc = CryptoHelper.CRCHash(cryptedSessKey); encResp.Write(cryptedSessKey); encResp.Write(keyCrc); encResp.Write(( uint )0); this.Send(encResp); }
public ActionResult Download(string publikKeyVal, string publicKey) { var passwords = _repository.GetAll(); CaesarChipherEncryptor ce = new CaesarChipherEncryptor(); string pass = ""; foreach (var p in passwords) { string line = p.System + "," + p.User + "," + ce.Decrypt(p.Password, 5); var crypt = _rsaCrypto.Encrypt(line, new KeyValuePair <uint, uint>(uint.Parse(publikKeyVal), uint.Parse(publicKey))); foreach (var c in crypt) { pass += c + " "; } pass += "\r\n"; } return(File(Encoding.UTF8.GetBytes(pass), "text/plain", "rsaEncryptedPassword.csv")); }
public void EncryptDecryptTests() { // Arrange var sectionText = $@"{{ ""RSA"": {{ ""PublicKey"": ""{publicKey}"", ""PrivateKey"": ""{privateKey}"" }} }}"; using var stream = new MemoryStream(Encoding.UTF8.GetBytes(sectionText)); var section = new ConfigurationBuilder().AddJsonStream(stream).Build().GetSection("RSA"); var crypto = new RSACrypto(section); var input = "Hello, Etsoo"; // Act var result = crypto.Encrypt(input); var decryptResult = Encoding.UTF8.GetString(crypto.Decrypt(result)); // Assert Assert.AreEqual(input, decryptResult); }
public string GetEncryptedData() { return(RSACrypto.Encrypt(GetJson())); }
//////////////////////////////////////////////////// // STEAM WEB INTERFACE //////////////////////////////////////////////////// // Copied this shit straight from ArchisSteamFarm, credit to him public override async void LoginWebInterface(ulong steamID) { if (!IsAuthenticated) { SteamUser.WebAPIUserNonceCallback callback; try { callback = await _steamUser.RequestWebAPIUserNonce(); } catch (Exception ex) { _log.Error(ex, "Unable to request Web API Nonce. Titan won't be able to execute Web API actions."); return; } if (string.IsNullOrWhiteSpace(callback?.Nonce)) { _log.Error("Received empty Web API Nonce. Titan won't be able to execute Web API actions."); return; } var sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString())); var sessionKey = CryptoHelper.GenerateRandomBlock(32); byte[] cryptedSessionKey; using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(_steamClient.Universe))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } var loginKey = new byte[callback.Nonce.Length]; Array.Copy(Encoding.ASCII.GetBytes(callback.Nonce), loginKey, callback.Nonce.Length); // AES encrypt the login key with our session key var cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); if (!Titan.Instance.WebHandle.AuthentificateUser( steamID, cryptedLoginKey, cryptedSessionKey, out var result )) { _log.Error("Failed to authentificate with Web API Nonce. " + "Titan won't be able to execute Web API actions."); return; } var token = result["token"].Value; var secureToken = result["tokensecure"].Value; if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(secureToken)) { _log.Error("Failed to authentificate with Web API Nonce. " + "Titan won't be able to execute Web API actions."); return; } Cookies.Add("sessionid", sessionID); Cookies.Add("steamLogin", token); Cookies.Add("steamLoginSecure", secureToken); if (!Titan.Instance.Options.Secure) { _log.Debug("Authorized with Steam Web API. Session ID: {id}", sessionID); } _log.Information("Successfully authorized with Steam Web API."); IsAuthenticated = true; } }
void HandleEncryptRequest( IPacketMsg packetMsg ) { var encRequest = new Msg<MsgChannelEncryptRequest>( packetMsg ); EUniverse eUniv = encRequest.Body.Universe; uint protoVersion = encRequest.Body.ProtocolVersion; DebugLog.WriteLine( "CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion ); byte[] pubKey = KeyDictionary.GetPublicKey( eUniv ); if ( pubKey == null ) { DebugLog.WriteLine( "CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion ); return; } ConnectedUniverse = eUniv; var encResp = new Msg<MsgChannelEncryptResponse>(); tempSessionKey = CryptoHelper.GenerateRandomBlock( 32 ); byte[] cryptedSessKey = null; using ( var rsa = new RSACrypto( pubKey ) ) { cryptedSessKey = rsa.Encrypt( tempSessionKey ); } byte[] keyCrc = CryptoHelper.CRCHash( cryptedSessKey ); encResp.Write( cryptedSessKey ); encResp.Write( keyCrc ); encResp.Write( ( uint )0 ); this.Send( encResp ); }
internal async Task <bool> Init(ulong steamID, EUniverse universe, string webAPIUserNonce, string parentalPin) { if ((steamID == 0) || (universe == EUniverse.Invalid) || string.IsNullOrEmpty(webAPIUserNonce) || string.IsNullOrEmpty(parentalPin)) { Logging.LogNullError(nameof(steamID) + " || " + nameof(universe) + " || " + nameof(webAPIUserNonce) + " || " + nameof(parentalPin), Bot.BotName); return(false); } SteamID = steamID; string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString())); // Generate an AES session key byte[] sessionKey = SteamKit2.CryptoHelper.GenerateRandomBlock(32); // RSA encrypt it with the public key for the universe we're on byte[] cryptedSessionKey; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(universe))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } // Copy our login key byte[] loginKey = new byte[webAPIUserNonce.Length]; Array.Copy(Encoding.ASCII.GetBytes(webAPIUserNonce), loginKey, webAPIUserNonce.Length); // AES encrypt the loginkey with our session key byte[] cryptedLoginKey = SteamKit2.CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); // Do the magic Logging.LogGenericInfo("Logging in to ISteamUserAuth...", Bot.BotName); KeyValue authResult; using (dynamic iSteamUserAuth = WebAPI.GetInterface("ISteamUserAuth")) { iSteamUserAuth.Timeout = Timeout; try { authResult = iSteamUserAuth.AuthenticateUser( steamid: steamID, sessionkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedSessionKey, 0, cryptedSessionKey.Length)), encrypted_loginkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedLoginKey, 0, cryptedLoginKey.Length)), method: WebRequestMethods.Http.Post, secure: !Program.GlobalConfig.ForceHttp ); } catch (Exception e) { Logging.LogGenericException(e, Bot.BotName); return(false); } } if (authResult == null) { Logging.LogNullError(nameof(authResult), Bot.BotName); return(false); } string steamLogin = authResult["token"].Value; if (string.IsNullOrEmpty(steamLogin)) { Logging.LogNullError(nameof(steamLogin), Bot.BotName); return(false); } string steamLoginSecure = authResult["tokensecure"].Value; if (string.IsNullOrEmpty(steamLoginSecure)) { Logging.LogNullError(nameof(steamLoginSecure), Bot.BotName); return(false); } WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunityHost)); WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunityHost)); WebBrowser.CookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamCommunityHost)); Logging.LogGenericInfo("Success!", Bot.BotName); // Unlock Steam Parental if needed if (!parentalPin.Equals("0")) { if (!await UnlockParentalAccount(parentalPin).ConfigureAwait(false)) { return(false); } } Ready = true; LastSessionRefreshCheck = DateTime.Now; return(true); }
bool HandleEncryptRequest( IPacketMsg packetMsg ) { var encRequest = new Msg<MsgChannelEncryptRequest>( packetMsg ); EUniverse eUniv = encRequest.Body.Universe; uint protoVersion = encRequest.Body.ProtocolVersion; DebugLog.WriteLine( "CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion ); DebugLog.Assert( protoVersion == 1, "CMClient", "Encryption handshake protocol version mismatch!" ); byte[] randomChallenge; if ( encRequest.Payload.Length >= 16 ) { randomChallenge = encRequest.Payload.ToArray(); } else { randomChallenge = null; } byte[] pubKey = KeyDictionary.GetPublicKey( eUniv ); if ( pubKey == null ) { connection.Disconnect(); DebugLog.WriteLine( "CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion ); return false; } ConnectedUniverse = eUniv; var encResp = new Msg<MsgChannelEncryptResponse>(); var tempSessionKey = CryptoHelper.GenerateRandomBlock( 32 ); byte[] encryptedHandshakeBlob = null; using ( var rsa = new RSACrypto( pubKey ) ) { if ( randomChallenge != null ) { var blobToEncrypt = new byte[ tempSessionKey.Length + randomChallenge.Length ]; Array.Copy( tempSessionKey, blobToEncrypt, tempSessionKey.Length ); Array.Copy( randomChallenge, 0, blobToEncrypt, tempSessionKey.Length, randomChallenge.Length ); encryptedHandshakeBlob = rsa.Encrypt( blobToEncrypt ); } else { encryptedHandshakeBlob = rsa.Encrypt( tempSessionKey ); } } var keyCrc = CryptoHelper.CRCHash( encryptedHandshakeBlob ); encResp.Write( encryptedHandshakeBlob ); encResp.Write( keyCrc ); encResp.Write( ( uint )0 ); if (randomChallenge != null) { pendingNetFilterEncryption = new NetFilterEncryptionWithHMAC( tempSessionKey ); } else { pendingNetFilterEncryption = new NetFilterEncryption( tempSessionKey ); } this.Send( encResp ); return true; }
bool HandleEncryptRequest(IPacketMsg packetMsg) { var encRequest = new Msg <MsgChannelEncryptRequest>(packetMsg); EUniverse eUniv = encRequest.Body.Universe; uint protoVersion = encRequest.Body.ProtocolVersion; DebugLog.WriteLine("CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion); DebugLog.Assert(protoVersion == 1, "CMClient", "Encryption handshake protocol version mismatch!"); byte[] randomChallenge; if (encRequest.Payload.Length >= 16) { randomChallenge = encRequest.Payload.ToArray(); } else { randomChallenge = null; } byte[] pubKey = KeyDictionary.GetPublicKey(eUniv); if (pubKey == null) { connection.Disconnect(); DebugLog.WriteLine("CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion); return(false); } ConnectedUniverse = eUniv; var encResp = new Msg <MsgChannelEncryptResponse>(); var tempSessionKey = CryptoHelper.GenerateRandomBlock(32); byte[] encryptedHandshakeBlob = null; using (var rsa = new RSACrypto(pubKey)) { if (randomChallenge != null) { var blobToEncrypt = new byte[tempSessionKey.Length + randomChallenge.Length]; Array.Copy(tempSessionKey, blobToEncrypt, tempSessionKey.Length); Array.Copy(randomChallenge, 0, blobToEncrypt, tempSessionKey.Length, randomChallenge.Length); encryptedHandshakeBlob = rsa.Encrypt(blobToEncrypt); } else { encryptedHandshakeBlob = rsa.Encrypt(tempSessionKey); } } var keyCrc = CryptoHelper.CRCHash(encryptedHandshakeBlob); encResp.Write(encryptedHandshakeBlob); encResp.Write(keyCrc); encResp.Write(( uint )0); if (randomChallenge != null) { pendingNetFilterEncryption = new NetFilterEncryptionWithHMAC(tempSessionKey); } else { pendingNetFilterEncryption = new NetFilterEncryption(tempSessionKey); } this.Send(encResp); return(true); }
private async Task <ActionResult> RunEntryAsync(IVRConfig ivrConfig, ScriptData script, string called, string extension, ScriptEntry entry, int errCount) { string extensionName = null; string extensionSpaced = null; if (!string.IsNullOrWhiteSpace(extension)) { extensionSpaced = Spaced(extension); Extension e = script.FindExtension(extension); if (e != null) { extensionName = e.Name; } } string digits; TryGetForm("Digits", out digits); string actionUrl = Utility.UrlFor(typeof(CallController), nameof(Process)); #if DEBUG actionUrl = Manager.CurrentSite.MakeFullUrl(actionUrl, SecurityType: YetaWF.Core.Pages.PageDefinition.PageSecurityType.Any); #else actionUrl = Manager.CurrentSite.MakeFullUrl(actionUrl, SecurityType: YetaWF.Core.Pages.PageDefinition.PageSecurityType.httpsOnly); #endif string token = DateTime.UtcNow.Ticks.ToString(); string encryptedToken; RSACrypto.Encrypt(ivrConfig.PublicKey, token, out encryptedToken); object parms = new { Url = actionUrl, Caller = GetForm("Caller"), CallerSpaced = Spaced(GetForm("Caller").TruncateStart("+1")), CallerCity = GetForm("CallerCity"), CallerCountry = GetForm("CallerCountry"), Digits = digits, Extension = extension, ExtensionSpaced = extensionSpaced, ExtensionName = extensionName, ErrCount = errCount, ErrCountPlus1 = errCount + 1, Token = encryptedToken, Voice = ivrConfig.Voice, VoiceInternal = ivrConfig.VoiceInternal, }; string text = entry.Text; Variables vars = new Variables(Manager, parms) { EncodingType = Variables.EncodingTypeEnum.XML }; Extension ext = script.FindExtension(digits); if (ext != null) { text = RepeatableNumbers(ext, text); } if (text.Contains("RECORDVOICEMAIL")) { text = text.Replace("RECORDVOICEMAIL", ""); VoiceMailData voiceMail; using (VoiceMailDataProvider voiceMailDP = new VoiceMailDataProvider()) { voiceMail = new VoiceMailData { Caller = GetForm("Caller").Truncate(Globals.MaxPhoneNumber), CallerCity = GetForm("CallerCity").Truncate(VoiceMailData.MaxCity), CallerState = GetForm("CallerState").Truncate(VoiceMailData.MaxState), CallerZip = GetForm("CallerZip").Truncate(VoiceMailData.MaxZip), CallerCountry = GetForm("CallerCountry").Truncate(VoiceMailData.MaxCountry), CallSid = GetForm("CallSid"), RecordingSid = GetForm("RecordingSid"), Duration = ConvertToInt(GetForm("RecordingDuration")), To = called, Extension = extension, RecordingUrl = GetForm("RecordingUrl").Truncate(Globals.MaxUrl) }; if (!await voiceMailDP.AddItemAsync(voiceMail)) { Logging.AddErrorLog($"Couldn't record voice mail status for call from {GetForm("Caller")}"); } } if (!string.IsNullOrWhiteSpace(extension)) { ext = script.FindExtension(extension); if (ext != null) { DisplayVoiceMailModule dispMod = (DisplayVoiceMailModule)await ModuleDefinition.LoadAsync(ModuleDefinition.GetPermanentGuid(typeof(DisplayVoiceMailModule))); ModuleAction displayAction = await dispMod.GetAction_DisplayAsync(null, voiceMail.Id); if (displayAction != null) { string viewUrl = displayAction.GetCompleteUrl(); foreach (ExtensionNumber extNumber in ext.Numbers) { if (extNumber.SendSMSVoiceMail) { SendSMS sendSMS = new SendSMS(); await sendSMS.SendMessageAsync(extNumber.Number, this.__ResStr("voiceSMS", "A voice mail was received for extension {0} ({1}) from {2}, {3}, {4}, {5} {6} - {7}", extension, GetForm("To"), GetForm("Caller"), GetForm("CallerCity"), GetForm("CallerState"), GetForm("CallerZip"), GetForm("CallerCountry"), viewUrl), ThrowError : false); } } } } } } text = vars.ReplaceVariables(text); Logging.AddLog($"{nameof(RunEntryAsync)}: {text}"); return(Content(text, "text/xml")); }
public static async Task <bool> AuthenticateUser() { SteamUser.WebAPIUserNonceCallback nonce; try { nonce = await Steam.Instance.User.RequestWebAPIUserNonce(); } catch (Exception e) { IsAuthorized = false; Log.WriteWarn("WebAuth", "Failed to get nonce: {0}", e.Message); return(false); } // 32 byte random blob of data var sessionKey = CryptoHelper.GenerateRandomBlock(32); byte[] encryptedSessionKey; // ... which is then encrypted with RSA using the Steam system's public key using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(Steam.Instance.Client.Universe))) { encryptedSessionKey = rsa.Encrypt(sessionKey); } // users hashed loginkey, AES encrypted with the sessionkey var encryptedLoginKey = CryptoHelper.SymmetricEncrypt(Encoding.ASCII.GetBytes(nonce.Nonce), sessionKey); using (dynamic userAuth = WebAPI.GetAsyncInterface("ISteamUserAuth")) { KeyValue result; try { result = await userAuth.AuthenticateUser( steamid : Steam.Instance.Client.SteamID.ConvertToUInt64(), sessionkey : WebHelpers.UrlEncode(encryptedSessionKey), encrypted_loginkey : WebHelpers.UrlEncode(encryptedLoginKey), method : "POST", secure : true ); } catch (HttpRequestException e) { IsAuthorized = false; Log.WriteWarn("WebAuth", "Failed to authenticate: {0}", e.Message); return(false); } File.WriteAllText(Path.Combine(Application.Path, "files", ".support", "cookie.txt"), $"steamLogin={result["token"].AsString()}; steamLoginSecure={result["tokensecure"].AsString()}"); Cookies = new CookieContainer(); Cookies.Add(new Cookie("steamLogin", result["token"].AsString(), "/", "store.steampowered.com")); Cookies.Add(new Cookie("steamLoginSecure", result["tokensecure"].AsString(), "/", "store.steampowered.com")); } IsAuthorized = true; Log.WriteInfo("WebAuth", "Authenticated"); if (!Settings.IsFullRun) { await AccountInfo.RefreshAppsToIdle(); } return(true); }
///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> /// <param name="myUniqueId">Id what you get to login.</param> /// <param name="client">An instance of a SteamClient.</param> /// <param name="myLoginKey">Login Key of your account.</param> /// <returns>A bool, which is true if the login was successful.</returns> public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey) { Token = TokenSecure = ""; SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId)); _cookies = new CookieContainer(); using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth")) { // Generate an AES session key. var sessionKey = CryptoHelper.GenerateRandomBlock(32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length); // AES encrypt the loginkey with our session key. byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); KeyValue authResult; // Get the Authentification Result. try { authResult = userAuth.AuthenticateUser( steamid: client.SteamID.ConvertToUInt64(), sessionkey: HttpUtility.UrlEncode(cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey), method: "POST", secure: true ); } catch (Exception) { Token = TokenSecure = null; return(false); } Token = authResult["token"].AsString(); TokenSecure = authResult["tokensecure"].AsString(); // Adding cookies to the cookie container. _cookies.Add(new Cookie("sessionid", SessionId, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLogin", Token, string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, string.Empty, SteamCommunityDomain)); //Add custom shit to the cookie _cookies.Add(new Cookie("webTradeEligibility", "%7B%22allowed%22%3A1%2C%22allowed_at_time%22%3A0%2C%22steamguard_required_days%22%3A15%2C%22sales_this_year%22%3A6%2C%22max_sales_per_year%22%3A200%2C%22forms_requested%22%3A0%2C%22new_device_cooldown_days%22%3A7%7D", string.Empty, SteamCommunityDomain)); _cookies.Add(new Cookie("strInventoryLastContext", "730_2", string.Empty, SteamCommunityDomain)); return(true); } }
static void Main(string[] args) { var mm = HttpCommon.HttpPost("http://api.1cloudsp.com/intl/api/v2/send", "accesskey=as5xjYLRv6ehVZL7&secret=GwxOKj0WOOon4NAJi52s0I4GnZqlGZ2u&sign=【IDCM】&templateId=999&mobile=8615019400599&content=27672"); string param = "json=kfPL3B20IkN2F7W85/3qrJjUfphS83IZp9VwT3no/AxLfwG46DUu3+cmzxgyGxoUmjpnKtmbzkdsDLQrIiISJGRpv2L4oJRhcpXjYKbeopqhNJ16Mnk0qH2Z2Y3LvSJAPi/4tgcjNY52uED7etWgAoeOWKlR1VBq88eJBH0wlr/nGesDHH2lMl4VAu99xE8CKwnfsI2R+BJxTdZzQIAjQjGWeTvNqArcXN+VBD/9o16x9OTpMXqNg7itaWZ1ddWbC4nIdO9KoXv7vd02dhNwY2ovAzUorNj+J5xnLfVZZqp44jxcLw2a7AGZ3TMlfinTU76mbm4+n/rhMpdryWTwyw=="; HttpCommon.HttpPost("http://preapi.idcm.io:8303/api/ExternalAPI/SignIn", param); //2048 公钥 string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwnsbSgsVdgscvfHpcwIE+3/Ny5swzVlUpJMveQDmdNool++SESap8r9Vhsc1lvO8W3omj6KAQ0j6as8ZTSGS3ngp0uf7nTgnuVxLfCF8UNhtOkbWomGZWoobM8LM+RX0VzzbPsVB7q0gmUPkH4M2TcPV2cjDyl2t3Om0ZDh0qaQjtTCUrc6BmCfYoAZpBoMIlM8gUViBi9TxxW2HvKlreUkM/IOyikRRmkIm/rkhqHO4z5HQoZzz0+QkxoqFMmkV5YZaoM0DQ7957vMNZUOxvmjg17GjJHVJzF/Keo25bEYdvnTVnjmAc+EMc+6qjrFIVuhE+T5l3rfE+4jqdzkN+QIDAQAB"; //2048 私钥 string privateKey = "MIIEogIBAAKCAQEAwnsbSgsVdgscvfHpcwIE+3/Ny5swzVlUpJMveQDmdNool++SESap8r9Vhsc1lvO8W3omj6KAQ0j6as8ZTSGS3ngp0uf7nTgnuVxLfCF8UNhtOkbWomGZWoobM8LM+RX0VzzbPsVB7q0gmUPkH4M2TcPV2cjDyl2t3Om0ZDh0qaQjtTCUrc6BmCfYoAZpBoMIlM8gUViBi9TxxW2HvKlreUkM/IOyikRRmkIm/rkhqHO4z5HQoZzz0+QkxoqFMmkV5YZaoM0DQ7957vMNZUOxvmjg17GjJHVJzF/Keo25bEYdvnTVnjmAc+EMc+6qjrFIVuhE+T5l3rfE+4jqdzkN+QIDAQABAoIBAHUJwRJ+ORwg89sbinI79OOltiOh8WyjJd0k9pzLfeU0pNlKw4yux/feTYoeuJFvfRtQF4S5NpdHg+xjVcalPc3EYucZ1MJ42O8kLAk33aiJlrJLjz+JnNBv7I7p3JDKNZGKfib4bwVECyoxQUf1nuiNwlSeDbXrSoZ33qexkgPER1zm2TUUi/17Wo62p1/J5l8SoxebaATzme0YWdP6rdbGIQ3ujYsgBxql+txWgNgiy0Yfduv/msdzL4X4oiZZa1XV8ivW8KyNs4XiUm5rIehQFmlYf1an/1qhHQvQXM+k0Bh8v5VJ8LflxkYddLdVnW+dPjT9FRegI4mrfjfgTkECgYEA41h2bwWFIn6CbeF+4eJxpdZENt5GKDDjCQB0jMj2Lx4hrE2cfOEybORAsE8RL2nLGKiTII2+bMqvHY1Sover5C/NraKCXyHPTji27eubTbPUWFfgIB/EvucXs/MqTn9W1xtZZGdDq1Ioxy87/0f9ervwSo1IKEZYQNkYNnEhulsCgYEA2v47TUCNE8r7Je12qf526jcpljIsNgrm6HQOObQcvVVP7wpmqvPcSlCPMEIUzbJupygRS/3p6E0kDgS4FzOaFKK1MlSI+eSsxN+H4eKQ6uzdcmvIG8sAyFww+4v5iNXeWXPFMOp2Qsog95y96zgYgrFU8Q91ZXHPMMetnUIGQTsCgYBlSW5KfD0aZx6Y8dPjs01KwzFU+KZtFYqw4gELECWOTHBYIaPMh1A971tasX9Ijmurqr8Ry9TBB3QJSIM+k/WDDkEmULagx6FiiiYFzeg9MBc03MG/zieLnc2ToIyCuHzqDQdAkjk1xL7iLwsd6ublnYGq1VMGjoCXM6Fz7+dE7QKBgEPnKrokdtoZSVCUVgQV7AdpvVJeEklbjger3LFVwMeQSW3EWttNLBQ68Hs1MkApwJfCG8LlY37tVG2oVvCSxob5gJevkJ1zo4KUEQ0gdHDzqyKMewrrIj3+IA4Pc/tS3VP9SrqFKNBC3oAIsPbbePYlSEJK2crvxB/K+nFVhJz7AoGAFx/SJsinfHcuvSrgSQdNbORmJbqnYULh2LDKp/z15D29Anya3Qzq/pHdTb8wOC7FM388pMy9eyNaga50GzfhhAiqm5CnKoMRjFWwTUVe33w+JA2an/ZHObeb/DyRuf8KrPJT7QuLCveQg5RA4mXNeBW1dBS0ebUqn1vOs8R8+X0="; //1024 私钥 string publicKey2 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCA++n8NNERrGNAq9w+sKYCW/2gc5yfBDvfwf1W6P1zA4VANyQr9Kr3WmJRi6TUFfrHpOKNApJRNgcKegxJAvxAih1v6z2KGS/OFaojBr+/06MbZ/vVNpQrMr00z5wRFI1hQ8C8o7xRmMuDQtfHr5DAM5nF7tIUNjD2N2AT2c3FwIDAQAB"; string privateKey2 = "MIICXAIBAAKBgQDCA++n8NNERrGNAq9w+sKYCW/2gc5yfBDvfwf1W6P1zA4VANyQr9Kr3WmJRi6TUFfrHpOKNApJRNgcKegxJAvxAih1v6z2KGS/OFaojBr+/06MbZ/vVNpQrMr00z5wRFI1hQ8C8o7xRmMuDQtfHr5DAM5nF7tIUNjD2N2AT2c3FwIDAQABAoGAcVd3VDb+VO6vnt8ouunjcIpi3DFs97i+9ArUDWRh3qA8wcxlDimI+1o34zga0XioQ/Ty4FQShkcvsRRSTxLt3fM61VSq0Aa8/8vtgzGHS8tnLc3kNJniJuhP6EDHowyEC7lsOxiwH6dr2GNH4Yts0x/Xz9GzZB9KV4wIY57tjtECQQDsYFoIeevJxmeoxUHfdtePKiZTnkVG1Qu01+m/b+PKu0bJLEtdgDvMYxeaB+potHRDLNKxWBUWfWPN9XE3kG2NAkEA0h9L9Jt+HcCgfbujlOMviZWloTUzXlWAmIb/rc+6CS6RWoRQOrN5y7aCskr7lTERL9gQTeuNgTewuDiv8tP0MwJAcE3C2N4cQYxrOYsmpeYPuiw7c2Tx4xpbanteyh596pcZpYDO+chwIMY/s2XpX//EcRn9rFZ+BmZiobroJI8RDQJBAJIfwaqyF9qJAxNtUi1QcNa1gyHA5aBMxclM2LH/K9kG0X6pVUH9Xk4U9n8XNi5imRk0oOIPVbDvEa6LfZDZZZECQF/BcEVRB7txuIryMUQTHoguAn9yIdmiyEAdfujlFcEo7b9vyh3grr29vAC95jy4fjXNBPSgffE76MTGNmCykvE="; var rsa = new RSAHelper(RSAType.RSA, Encoding.UTF8, privateKey, publicKey); var test = new RSACrypto(privateKey, publicKey); string str = "123456"; Console.WriteLine("原始字符串:" + str); //加密 string enStr = rsa.Encrypt(str); enStr = "NR4tG5D/sRriuNoonT5AqRMNetmpcnndgQ8Rr8c3AJbkBwSSejlYl7Xraqi4UDiYZfAxLMf2sPpwT9IJmTGBO+xRpaHN0BumgRE1w+5quB7wae6zagIE5DC+M8dkC+kuBSPD8FLn7Vgo8r84vFGTsYKpUt7JvpoqkypU1nEsN4akv/mpGXCQOFqN9EWKggq3uniDXiZ5Wg35ls4AqmPSY5A/XMf84WKNR6xcBt+rUz/Z8lRn7mEBphhyEmHr0tDs3sY23hGnU9kKmV9rjcqh4rgQ+N7SnY+koJYHd32pOTdmrcXYRuWv4szk86wWp+GTj1wZ2bLe5j44idfWSuQkPw=="; //enStr = "NR4tG5D/sRriuNoonT5AqRMNetmpcnndgQ8Rr8c3AJbkBwSSejlYl7Xraqi4UDiYZfAxLMf2sPpwT9IJmTGBO xRpaHN0BumgRE1w 5quB7wae6zagIE5DC M8dkC kuBSPD8FLn7Vgo8r84vFGTsYKpUt7JvpoqkypU1nEsN4akv/mpGXCQOFqN9EWKggq3uniDXiZ5Wg35ls4AqmPSY5A/XMf84WKNR6xcBt rUz/Z8lRn7mEBphhyEmHr0tDs3sY23hGnU9kKmV9rjcqh4rgQ N7SnY koJYHd32pOTdmrcXYRuWv4szk86wWp GTj1wZ2bLe5j44idfWSuQkPw=="; string enStr2 = test.Encrypt(str); string enStr3 = "t3N885z0IL9aASYjcJppftNoF5eoDfVyuJsxcQSRc3C+/otctMs8azKgPo12zHERr/3AOLoVXNk4GQX2o36ksqhf2BbrDFphVqEBbC/sh175XLXVSKcXP2Tb4EoE1B4QtzoRymV1nlTGERDrzeJ5vZUTEJStVpgNpp2UoDp3CIT4ASoIGhbnVieRLtDS/EukdYz2GKRAoygf9UBlzZkooit6Grb7JeF0zxcfY4X5EO4oehylvNDYTJcP9yfPF9NybW05DMpoNMNYHgDamYbKRwcv9SWIhZ6kY59NO4FO4Gv6/PYsNaLE6hMY4LE+0ITL0X8QAFhrG3j3fCWOw076mQ=="; Console.WriteLine("A生成的加密字符串a:" + enStr); Console.WriteLine("B生成的加密字符串b:" + enStr2); Console.WriteLine("JS生成的加密字符串js:" + enStr3); //解密 string deStr = rsa.Decrypt(enStr); string deStr2 = rsa.Decrypt(enStr2); string deStr3 = rsa.Decrypt(enStr3); Console.WriteLine("A解密字符串a:" + deStr); Console.WriteLine("A解密字符串b:" + deStr2); Console.WriteLine("A解密字符js:" + deStr3); string deStr4 = test.Decrypt(enStr); string deStr5 = test.Decrypt(enStr2); string deStr6 = test.Decrypt(enStr3); Console.WriteLine("B解密字符串a:" + deStr4); Console.WriteLine("B解密字符串b:" + deStr5); Console.WriteLine("B解密字符js:" + deStr6); Console.ReadKey(); }
public static async Task <bool> AuthenticateUser() { SteamUser.WebAPIUserNonceCallback nonce; ulong steamid; try { nonce = await Steam.Instance.User.RequestWebAPIUserNonce(); steamid = Steam.Instance.Client.SteamID.ConvertToUInt64(); } catch (Exception e) { IsAuthorized = false; Log.WriteWarn("WebAuth", "Failed to get nonce: {0}", e.Message); return(false); } // 32 byte random blob of data var sessionKey = CryptoHelper.GenerateRandomBlock(32); byte[] encryptedSessionKey; // ... which is then encrypted with RSA using the Steam system's public key using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(Steam.Instance.Client.Universe))) { encryptedSessionKey = rsa.Encrypt(sessionKey); } // users hashed loginkey, AES encrypted with the sessionkey var encryptedLoginKey = CryptoHelper.SymmetricEncrypt(Encoding.ASCII.GetBytes(nonce.Nonce), sessionKey); using (var userAuth = Steam.Configuration.GetAsyncWebAPIInterface("ISteamUserAuth")) { KeyValue result; try { result = await userAuth.CallAsync(HttpMethod.Post, "AuthenticateUser", 1, new Dictionary <string, object> { { "steamid", steamid }, { "sessionkey", encryptedSessionKey }, { "encrypted_loginkey", encryptedLoginKey }, } ); } catch (HttpRequestException e) { IsAuthorized = false; Log.WriteWarn("WebAuth", "Failed to authenticate: {0}", e.Message); return(false); } Cookies = new CookieContainer(); Cookies.Add(new Cookie("steamLogin", result["token"].AsString(), "/", "store.steampowered.com")); Cookies.Add(new Cookie("steamLoginSecure", result["tokensecure"].AsString(), "/", "store.steampowered.com")); } IsAuthorized = true; Log.WriteInfo("WebAuth", "Authenticated"); return(true); }
internal async Task <bool> Init(SteamClient steamClient, string webAPIUserNonce, string parentalPin) { if (steamClient == null || steamClient.SteamID == null || string.IsNullOrEmpty(webAPIUserNonce)) { return(false); } SteamID = steamClient.SteamID; string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(SteamID.ToString())); // Generate an AES session key byte[] sessionKey = CryptoHelper.GenerateRandomBlock(32); // RSA encrypt it with the public key for the universe we're on byte[] cryptedSessionKey; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(steamClient.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } // Copy our login key byte[] loginKey = new byte[webAPIUserNonce.Length]; Array.Copy(Encoding.ASCII.GetBytes(webAPIUserNonce), loginKey, webAPIUserNonce.Length); // AES encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); // Do the magic Logging.LogGenericInfo("Logging in to ISteamUserAuth...", Bot.BotName); KeyValue authResult; using (dynamic iSteamUserAuth = WebAPI.GetInterface("ISteamUserAuth")) { iSteamUserAuth.Timeout = Timeout; try { authResult = iSteamUserAuth.AuthenticateUser( steamid: SteamID, sessionkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedSessionKey, 0, cryptedSessionKey.Length)), encrypted_loginkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedLoginKey, 0, cryptedLoginKey.Length)), method: WebRequestMethods.Http.Post, secure: !Program.GlobalConfig.ForceHttp ); } catch (Exception e) { Logging.LogGenericException(e, Bot.BotName); return(false); } } if (authResult == null) { return(false); } Logging.LogGenericInfo("Success!", Bot.BotName); string steamLogin = authResult["token"].AsString(); string steamLoginSecure = authResult["tokensecure"].AsString(); Cookie["sessionid"] = sessionID; Cookie["steamLogin"] = steamLogin; Cookie["steamLoginSecure"] = steamLoginSecure; // The below is used for display purposes only Cookie["webTradeEligibility"] = "{\"allowed\":0,\"reason\":0,\"allowed_at_time\":0,\"steamguard_required_days\":0,\"sales_this_year\":0,\"max_sales_per_year\":0,\"forms_requested\":0}"; await UnlockParentalAccount(parentalPin).ConfigureAwait(false); return(true); }
internal async Task Init(SteamClient steamClient, string webAPIUserNonce, string vanityURL, string parentalPin) { if (steamClient == null || steamClient.SteamID == null || string.IsNullOrEmpty(webAPIUserNonce)) { return; } SteamID = steamClient.SteamID; VanityURL = vanityURL; string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(SteamID.ToString(CultureInfo.InvariantCulture))); // Generate an AES session key byte[] sessionKey = CryptoHelper.GenerateRandomBlock(32); // RSA encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(steamClient.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt(sessionKey); } // Copy our login key byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(webAPIUserNonce), loginKey, webAPIUserNonce.Length); // AES encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); // Send the magic KeyValue authResult; Logging.LogGenericInfo(Bot.BotName, "Logging in to ISteamUserAuth..."); using (dynamic iSteamUserAuth = WebAPI.GetInterface("ISteamUserAuth")) { iSteamUserAuth.Timeout = Timeout; try { authResult = iSteamUserAuth.AuthenticateUser( steamid: SteamID, sessionkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedSessionKey, 0, cryptedSessionKey.Length)), encrypted_loginkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedLoginKey, 0, cryptedLoginKey.Length)), method: WebRequestMethods.Http.Post, secure: true ); } catch (Exception e) { Logging.LogGenericException(Bot.BotName, e); steamClient.Disconnect(); // We may get 403 if we use the same webAPIUserNonce twice return; } } if (authResult == null) { steamClient.Disconnect(); // Try again return; } Logging.LogGenericInfo(Bot.BotName, "Success!"); string steamLogin = authResult["token"].AsString(); string steamLoginSecure = authResult["tokensecure"].AsString(); SteamCookieDictionary.Clear(); SteamCookieDictionary.Add("sessionid", sessionID); SteamCookieDictionary.Add("steamLogin", steamLogin); SteamCookieDictionary.Add("steamLoginSecure", steamLoginSecure); SteamCookieDictionary.Add("birthtime", "-473356799"); // ( ͡° ͜ʖ ͡°) if (!string.IsNullOrEmpty(parentalPin) && !parentalPin.Equals("0")) { Logging.LogGenericInfo(Bot.BotName, "Unlocking parental account..."); Dictionary <string, string> postData = new Dictionary <string, string>() { { "pin", parentalPin } }; HttpResponseMessage response = await Utilities.UrlPostRequestWithResponse("https://steamcommunity.com/parental/ajaxunlock", postData, SteamCookieDictionary, "https://steamcommunity.com/").ConfigureAwait(false); if (response != null && response.IsSuccessStatusCode) { Logging.LogGenericInfo(Bot.BotName, "Success!"); var setCookieValues = response.Headers.GetValues("Set-Cookie"); foreach (string setCookieValue in setCookieValues) { if (setCookieValue.Contains("steamparental=")) { string setCookie = setCookieValue.Substring(setCookieValue.IndexOf("steamparental=") + 14); setCookie = setCookie.Substring(0, setCookie.IndexOf(';')); SteamCookieDictionary.Add("steamparental", setCookie); break; } } } else { Logging.LogGenericInfo(Bot.BotName, "Failed!"); } } Bot.Trading.CheckTrades(); }
/// <summary> /// Encrypts a string with the server's public key and convert it to base64. /// </summary> /// <param name="s">The string to be encrypted.</param> /// <returns>The encrypted string in base64 format.</returns> private String PpEncryptAndBase64(String s) { Contract.Requires(!ReferenceEquals(s, null)); RSACrypto rsa = new RSACrypto(); rsa.ImportCspBlob(_publicKey); byte[] sEncrypted = rsa.Encrypt(_utf8.GetBytes(s)); return Convert.ToBase64String(sEncrypted); }
internal async Task Init(string webAPIUserNonce) { steamID = _bot.steamClient.SteamID; sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString())); // Generate an AES session key byte[] sessionKey = CryptoHelper.GenerateRandomBlock(32); // RSA encrypt it with the public key for the universe we're on byte[] cryptedSessionKey; using (var crypto = new RSACrypto(KeyDictionary.GetPublicKey(_bot.steamClient.ConnectedUniverse))) { cryptedSessionKey = crypto.Encrypt(sessionKey); } // Copy our login key byte[] loginKey = new byte[webAPIUserNonce.Length]; Array.Copy(Encoding.ASCII.GetBytes(webAPIUserNonce), loginKey, webAPIUserNonce.Length); // AES encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey); _bot.Log("Logging in to ISteamUserAuth", LogType.Info); KeyValue autResult; using (dynamic iSteamUserAuth = WebAPI.GetInterface("ISteamUserAuth")) { iSteamUserAuth.Timeout = 60000; try { autResult = iSteamUserAuth.AuthenticateUser( steamid: steamID.ConvertToUInt64(), sessionkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedSessionKey, 0, cryptedSessionKey.Length)), encrypted_loginkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedLoginKey, 0, cryptedLoginKey.Length)), method: WebRequestMethods.Http.Post, secure: true); } catch (Exception e) { _bot.Log("Cant AuthenticateUser " + e.Message, LogType.Error); return; } } if (autResult == null) { return; } _bot.Log("Success", LogType.Info); string steamLogin = autResult["token"].Value; string steamLoginSecure = autResult["tokensecure"].Value; webClient.cookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunityHOST)); webClient.cookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunityHOST)); webClient.cookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamCommunityHOST)); gameminerBot = new GameminerBot(webClient, _bot.BotConfig); Initialized = true; //GiveawayBotInit().Forget(); }