C++

Add licensing to a native Windows app with the C++ PwfClient source files

The PWF Auth C++ client is two source files, PwfClient.h and PwfClient.cpp, for native Windows programs in C++17. It handles the encryption, the heartbeat and the kill switch with Windows' own WinHTTP and CNG, and needs one outside library, nlohmann-json

Add it to your project

Download the source of version 1.5.0 from GitHub and copy four files into one folder of your project:

FileWhat it is
PwfClient.h / PwfClient.cppThe client
ServerPublicKey.hThe public key the client checks every reply with
ProductionPolicy.hThe two addresses the client may use: https://pwfauth.com, and https://pwfauth.net when pwfauth.com gives no reply at all (some networks block the name)

Then, in Visual Studio:

  • Set the C++ language standard to C++17 or newer
  • Put nlohmann-json on the include path, since PwfClient.h includes <nlohmann/json.hpp>. vcpkg installs it, and the sample project does that from its vcpkg.json on the first build
  • Link winhttp.lib, bcrypt.lib, crypt32.lib and advapi32.lib (Linker → Input → Additional Dependencies)
Use version 1.2 or newer. Every reply from the server is signed, and the client checks the signature with the key in ServerPublicKey.h; older copies carry an older key and refuse every reply from the current server. Customer accounts need 1.3 and protected files 1.5

Keep the secret out of your repository

The 64-character app secret of your application (see Applications) goes into your build. Keep it in a header that your repository ignores, so a real secret is never committed:

C++
// PwfSecret.h, listed in .gitignore
#pragma once
inline constexpr char PwfAppSecret[] = "YOUR_64_CHARACTER_APP_SECRET";

Sign in and start the heartbeat

C++
#include "PwfClient.h"
#include "PwfSecret.h"

constexpr UINT WM_APP_SIGNED_OUT = WM_APP + 1;
PwfClient client(PwfAppSecret);          // one client for the life of the program

// the callback runs on the heartbeat thread, so it hands the message to the window
client.SetSessionEndedCallback([hwnd](const std::string& code, const std::string& message) {
    auto* text = new std::string(message);
    if (!PostMessageW(hwnd, WM_APP_SIGNED_OUT, 0, reinterpret_cast<LPARAM>(text)))
        delete text;
});

PwfResponse login = client.Login(licenseKey);
if (!login.Success()) {
    ShowError(login.Message());          // written for the customer
    return;
}

client.StartHeartbeat();                 // the kill switch: never skip it
Always call StartHeartbeat(). Without it the program never learns that a key was banned, paused or expired, and the server drops the silent session

The callback gets the code and the message when the key is banned, paused, expired, deleted or reset, when you end the session from the panel, when the app goes into maintenance, when an account's password changes, and when three heartbeats in a row get no encrypted answer (NETWORK_LOST, or CLOCK_SKEW when the PC's clock is the reason). How often it checks is in How protection works

In the window procedure, take the string back with std::unique_ptr, show it and close the program. PostQuitMessage inside the callback would not do it, because it posts to the heartbeat thread. Every call waits for the server's answer, so in a window make it from a worker thread, as the sample program does

Show the license

The sign-in reply is in login.data, an nlohmann::json object:

C++
const nlohmann::json user = login.data.value("user", nlohmann::json::object());
std::string status = "Lifetime license";               // expires_at is null for lifetime keys
if (user.contains("expires_at") && user["expires_at"].is_string())
    status = "Expires " + user["expires_at"].get<std::string>();

const nlohmann::json texts = login.data.value("texts", nlohmann::json::object());
const std::string title = texts.is_object() ? texts.value("welcome", "Welcome") : "Welcome";

Other fields: user.key_type, user.days_remaining, app.name, app.version, app.message (your welcome message), features, addons and slides. texts holds your remote texts with the key's own values applied (see Texts & slides)

There are no separate calls for texts, slides, app info, trials, update checks, user variables or add-on keys in the C++ client. The sign-in reply carries the texts, the slides and the customer's add-ons, and API reference describes the rest

Move the license to a new PC

When the key belongs to another PC, offer to move it. This works when self-service is on for the app (see HWID resets). In C++ the codes are plain strings:

C++
if (login.ErrorCode() == "HWID_MISMATCH" || login.ErrorCode() == "DEVICE_LIMIT") {
    if (AskUser(login.Message() + "\nMove your license to this PC?")) {
        PwfResponse moved = client.ResetHardwareId(licenseKey, "Moved to a new PC");
        ShowMessage(moved.Message());
        if (moved.Success())
            login = client.Login(licenseKey);
    }
}

The move unbinds the key from every PC and ends its sessions. A refusal names the reason in moved.ErrorCode(): SELF_RESET_DISABLED, RATE_LIMITED (the message says how long to wait), KEY_NOT_ACTIVE or NO_HWID

Customer accounts

Instead of a key, a customer can sign in with a username and password (see Users). The session and the heartbeat work exactly as with a key:

C++
PwfResponse login = client.AccountLogin(username, password);
if (!login.Success()) {
    ShowError(login.Message());          // INVALID_CREDENTIALS, BANNED, PAUSED, EXPIRED, HWID_MISMATCH …
    return;
}
client.StartHeartbeat();

Sign-up, keys and password changes, when sign-up is on for the app:

C++
PwfResponse r = client.RegisterAccount(username, password, email);      // REGISTRATION_DISABLED when sign-up is off
if (r.ErrorCode() == "KEY_REQUIRED")                                     // "Sign-up needs a license key" is on
    r = client.RegisterAccountWithKey(username, password, key, email);

PwfResponse more = client.RedeemKey(key);                                // signed in: adds the key's time
PwfResponse back = client.RedeemKey(username, password, key);            // signed out, works after expiry too
PwfResponse c = client.ChangeAccountPassword(username, currentPassword, newPassword);

A changed password signs out every copy using the account, the one that changed it too: sign in again with the new password. An account is bound to one PC; when it moves, you reset its machine in Users. A key spent on an account cannot sign in on its own any more: Login answers KEY_REDEEMED

Protected files

A protected file is a file your program needs, kept on the server and given only to a signed-in program (see App settings → Files). Fetch it after Login or AccountLogin:

C++
PwfResource core = client.GetResource("core.dat");
if (!core.Success()) {
    ShowError(core.Message());           // NOT_FOUND, SESSION_EXPIRED, RATE_LIMITED
    return;
}
UseCore(core.bytes.data(), core.bytes.size());

PwfResourceList files = client.ListResources();   // files.names: what this customer can fetch

The bytes are checked against the SHA-256 the server sends, and a mismatch throws PwfSecurityError. Each customer's copy carries their own mark, so do not compare the bytes with a fixed hash. A session can fetch 60 files an hour: fetch a file once at start

Sign out

C++
if (client.IsSignedIn())
    client.Logout();                     // ends the session; the key stays bound to this PC

Logout() throws when there is no session, and when the server cannot be told; the session is cleared on this PC either way

Errors and what the customer sees

A refusal is a normal reply: Success() is false, ErrorCode() is for your code and Message() is written for the customer, in your own words if you set them in Applications → Messages. Show the message; branch on the code (see Error codes). An exception means the reply never came or cannot be trusted:

ExceptionMeans
PwfNetworkErrorNo connection at all: offline, DNS, a firewall, a proxy or TLS
PwfHttpErrorA reply that is not the API's JSON. Status() is the HTTP status, and 401 means the app secret was refused
PwfSecurityErrorNo valid PWF Auth signature, a plain "success" where an encrypted reply was due, a reply over the size limit or a protected file that does not match its SHA-256. Never unlock the program on it
std::invalid_argumentA required argument left empty, or a server address other than https://pwfauth.com

The three Pwf errors derive from std::runtime_error, so put their catch blocks before a catch of std::exception, as the sample program does

Signed replies

Every request carries a fresh random nonce, and every reply, plain or encrypted, must carry PWF Auth's RSA-3072 signature over that exact request and reply. The client checks it with the key in ServerPublicKey.h before it reads anything, so knowing your app secret is not enough to fake an answer. That stops a fake server, not someone who patches the program on their own PC: keep the part that matters on the server, as a protected file

More calls

CallDoes
SetAutoCorrectClock(enabled)On by default: when the server refuses the PC's clock, the client shifts by the server's time and sends the request once more
HardwareId()This PC's ID, the Windows MachineGuid, which the other official clients use too, so one PC counts as one device
IsSignedIn() / SessionId() / HeartbeatSeconds()The session and the heartbeat interval
PwfClient::ProtocolSelfTest()An offline check of the encryption, which the sample runs before it shows the sign-in window

The constructor also takes the timeout in milliseconds (15000), and how many heartbeats in a row may go unanswered (3) or be answered with HTTP 429 (10) before the session ends

Step by step

For a walk-through from a new application to a protected program, with a video, read How to add license keys with an HWID lock to a C++ Windows app. The source and a sample Windows program are on GitHub

Something missing or unclear? Tell us on Telegram