SetKey

Summary: Set the 32-byte protection key from bytes or Base64 text.

Description

Set the 32-byte protection key from bytes or Base64 text.

The session key becomes the key for subsequent protected writes. Save System can still read saves protected with the configured project key or a key in the configured Previous Keys list.

Calling SetKey again replaces the session key. Saves protected with the earlier session key can return UnknownEncryptionKey unless that key is also configured as the project key or in Previous Keys.

Declaration

C#
public static void SetKey(byte[] key);

public static void SetKey(string base64Key);

Parameters

ParameterTypeDescription
keybyte[]Byte-array overload only. The 32-byte key.
base64KeystringBase64 overload only. The 32-byte key, written as base64 text.

Exceptions

ExceptionThrown when
ArgumentExceptionThe key is not exactly 32 bytes, or the Base64 text does not decode to a 32-byte key.
InvalidOperationExceptionThe method is called from a thread other than Unity’s main thread.

Example

Create either SetSaveKeyFromText.cs or SetSaveKeyFromBytes.cs using the matching block. Attach the script to an active GameObject. Use a test project and enter the Base64 form of the 32-byte key in the Inspector before entering Play mode. The example sets the key for the current session. Keep real keys out of source control.

Base64 text · C#
using Gley.SaveSystem;
using UnityEngine;

public class SetSaveKeyFromText : MonoBehaviour
{
    [SerializeField] private string _base64Key = "";

    private void Start()
    {
        if (string.IsNullOrWhiteSpace(_base64Key))
        {
            Debug.LogWarning("Enter a Base64-encoded 32-byte key first.", this);
            return;
        }

        API.SetKey(_base64Key);
        Debug.Log("Set the save protection key.", this);
    }
}
Byte array · C#
using System;
using Gley.SaveSystem;
using UnityEngine;

public class SetSaveKeyFromBytes : MonoBehaviour
{
    [SerializeField] private string _base64Key = "";

    private void Start()
    {
        if (string.IsNullOrWhiteSpace(_base64Key))
        {
            Debug.LogWarning("Enter a Base64-encoded 32-byte key first.", this);
            return;
        }

        byte[] key = Convert.FromBase64String(_base64Key);
        API.SetKey(key);
        Debug.Log("Set the save protection key.", this);
    }
}
On This Page