## C example: Store a password

Here's how to store a password in the running secret service, like gnome-keyring or ksecretservice.

Each stored password has a set of attributes which are later used to lookup the password. The attributes should not contain secrets, as they are not stored in an encrypted fashion.

These examples use the example schema.

This first example stores a password asynchronously, and is appropriate for GUI applications so that the UI does not block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    static void
    on_password_stored (GObject *source,
                        GAsyncResult *result,
                        gpointer unused)
    {
        GError *error = NULL;

        secret_password_store_finish (result, &error);
        if (error != NULL) {
            /* ... handle the failure here */
            g_error_free (error);
        } else {
            /* ... do something now that the password has been stored */
        }
    }

    /*
     * The variable argument list is the attributes used to later
     * lookup the password. These attributes must conform to the schema.
     */
    secret_password_store (EXAMPLE_SCHEMA, SECRET_COLLECTION_DEFAULT, "The label",
                           "the password", NULL, on_password_stored, NULL,
                           "number", 8,
                           "string", "eight",
                           "even", TRUE,
                           NULL);

This next example stores a password synchronously. The function call will block until the password is stored. So this is appropriate for non GUI applications.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    GError *error = NULL;

    /*
     * The variable argument list is the attributes used to later
     * lookup the password. These attributes must conform to the schema.
     */
    secret_password_store_sync (EXAMPLE_SCHEMA, SECRET_COLLECTION_DEFAULT,
                                "The label", "the password", NULL, &error,
                                "number", 9,
                                "string", "nine",
                                "even", FALSE,
                                NULL);

    if (error != NULL) {
        /* ... handle the failure here */
        g_error_free (error);
    } else {
        /* ... do something now that the password has been stored */
    }