using System.Security.Cryptography;
using DodoSSH.Client.Domain;
using DodoSSH.Contracts;
using DodoSSH.Crypto;
namespace DodoSSH.Client.Sync;
///
/// Turns a Spelunk key into an item payload and back.
///
///
///
/// Mirrors exactly, including the version rule in .
///
///
/// The resource type is named, never cast. SyncEntityType.SpelunkKey is 14 and
/// CryptoSpec.AadResourceType.SpelunkKey is 17; 14 in the crypto enum is a connection log entry, and a
/// cast would seal an API key under that — which decrypts perfectly on the machine that wrote it and violates
/// docs/crypto.md everywhere else.
///
///
public static class SpelunkKeyCipher
{
private const CryptoSpec.AadResourceType Resource = CryptoSpec.AadResourceType.SpelunkKey;
/// Encrypts a Spelunk key.
/// The key. Must be valid for storage.
/// The vault key, which the data key is wrapped under.
/// The item id, which the AAD binds.
/// The vault's current key generation.
/// The version this payload will hold once the server accepts it.
public static EncryptedPayload Seal(
SpelunkKeySecret key,
ReadOnlySpan vaultKey,
Guid entityId,
uint keyGeneration,
int itemVersion)
{
ArgumentNullException.ThrowIfNull(key);
ArgumentOutOfRangeException.ThrowIfLessThan(itemVersion, 1);
var plaintext = SpelunkKeySecretCodec.Encode(key);
var dataKey = ItemKeys.CreateDataKey();
try
{
var dataKeyId = Guid.CreateVersion7();
var wrappedDataKey = ItemKeys.WrapDataKey(
dataKey, vaultKey, Resource, entityId, keyGeneration, (uint)itemVersion);
var envelope = ItemKeys.SealPayload(
dataKey, plaintext, Resource, entityId, dataKeyId, keyGeneration, (uint)itemVersion);
return new EncryptedPayload(
envelope, wrappedDataKey, dataKeyId, keyGeneration, CryptoSpec.CurrentAadVersion);
}
finally
{
CryptographicOperations.ZeroMemory(dataKey);
// It holds an API key, which is live on the Spelunk it belongs to.
CryptographicOperations.ZeroMemory(plaintext);
}
}
/// Decrypts a Spelunk key.
///
public static SpelunkKeySecretDocument? TryOpen(
EncryptedPayload payload,
ReadOnlySpan vaultKey,
Guid entityId,
int itemVersion)
{
ArgumentNullException.ThrowIfNull(payload);
if (itemVersion < 1 || payload.WrappedDataKey.Length == 0)
{
return null;
}
var dataKey = ItemKeys.TryUnwrapDataKey(
vaultKey,
payload.WrappedDataKey,
Resource,
entityId,
payload.KeyGeneration,
(uint)itemVersion);
if (dataKey is null)
{
return null;
}
try
{
var plaintext = ItemKeys.TryOpenPayload(
dataKey,
payload.Envelope,
Resource,
entityId,
payload.DataKeyId,
payload.KeyGeneration,
(uint)itemVersion);
if (plaintext is null)
{
return null;
}
try
{
return SpelunkKeySecretCodec.TryDecode(plaintext, out var document) ? document : null;
}
finally
{
CryptographicOperations.ZeroMemory(plaintext);
}
}
finally
{
CryptographicOperations.ZeroMemory(dataKey);
}
}
}