Snippets

Gauntlet Get User Token

Created by Gauntlet
protected Task GetUserToken()
{
    // Get the index page of the ubooquity server (not with /opds-comics/)
    var response = await Client.GetAsync("comic.server.url");
    if (response.StatusCode == HttpStatusCode.OK)
    {
        // Load the html into a DOM class to make parsing the website easier (I'm using library)
        var data = await response.Content.ReadAsStringAsync();
        var doc = new HtmlDocument();
        doc?.LoadHtml(data);

        // Navigating to the html body of the page. 
        var html = doc?.DocumentNode?.ChildNodes.FirstOrDefault(n => n.Name.Equals("html"));
        var body = html?.ChildNodes?.FirstOrDefault(n => n.Name.Equals("body"));
        
        // The login form contains the serversalt and servertime values.
        var serversalt = body?.ChildNodes?.FirstOrDefault(n => n.Id.Equals("serversalt"))?.Attributes?.FirstOrDefault(a => a.Name.Equals("value"))?.Value;
        var servertime = body?.ChildNodes?.FirstOrDefault(n => n.Id.Equals("servertime"))?.Attributes?.FirstOrDefault(a => a.Name.Equals("value"))?.Value;

        // Hash the password with the server salt and then hash the result with the servertime.
        var hashed_password = Hash(Hash(Credentials.Password, serversalt), servertime);
        
        // Create a HttpRequest
        var request = new HttpRequestMessage(HttpMethod.Post, "/");
        
        // Include the "entered" values for the form in the request.
        var formData = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("servertime", servertime),
            new KeyValuePair<string, string>("login", Credentials.UserName),
            new KeyValuePair<string, string>("hash", hashed_password)
        };
        request.Content = new FormUrlEncodedContent(formData);
        
        // Send the request, the response automatically adds the cookie to Client object and any future
        // requests through Client.
        response = await Client.SendAsync(request);
             
        // var content = await response.Content.ReadAsStringAsync();
    }
}

protected string Hash(string Key, string Msg)
{
    // Transform strings into binary arrays.
    var bKey = Key.ToBinaryByteArray();
    var bMsg = Msg.ToBinaryByteArray();

    // Create a hasher(?) using the binary key.
    var hmac = new HMACSHA256(bKey);
    // Use the hasher to hash the binary message.
    var hash = hmac.ComputeHash(bMsg);

    // Encode the hash as a hex string.
    var buff = CryptographicBuffer.CreateFromByteArray(hash);
    var res = CryptographicBuffer.EncodeToHexString(buff);

    return res;
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.