Skip to content

Commit

Permalink
feat(crypto): ✨ add SodiumString
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonboukheir committed Sep 25, 2023
1 parent 11762f6 commit fdd3ccb
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
71 changes: 71 additions & 0 deletions Runtime/Algorand.Unity.Crypto/SodiumString.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using System;
using System.Diagnostics;
using Unity.Collections;
using Unity.Jobs;

namespace Algorand.Unity.Crypto
{
public struct SodiumString : INativeDisposable
{
private readonly SecureMemoryHandle handle;

private readonly int totalCapacity;

private int length;

public bool IsCreated => handle.IsCreated;

public int Length => length;

public int Capacity => totalCapacity - 1;

public unsafe byte* GetUnsafePtr()
{
return (byte*)handle.GetUnsafePtr();
}

public SodiumString(ReadOnlySpan<char> source)
{
totalCapacity = source.Length * sizeof(char);
var totalCapacityNUint = (UIntPtr)totalCapacity;
handle = SecureMemoryHandle.Create(totalCapacityNUint);
unsafe
{
fixed (char* sourceptr = source)
{
sodium.sodium_mlock((IntPtr)sourceptr, totalCapacityNUint);
var error = UTF8ArrayUnsafeUtility.Copy(
handle.GetUnsafePtr(),
out length,
totalCapacity - 1,
sourceptr,
source.Length
);
sodium.sodium_munlock((IntPtr)sourceptr, totalCapacityNUint);
if (error != CopyError.None)
{
if (handle.IsCreated) handle.Dispose();
length = 0;
ThrowCopyError(error, source);
}
}
}
}

public JobHandle Dispose(JobHandle inputDeps)
{
return handle.Dispose(inputDeps);
}

public void Dispose()
{
handle.Dispose();
}

[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
void ThrowCopyError(CopyError error, ReadOnlySpan<char> source)
{
throw new ArgumentException($"NativeText: {error} while copying \"{source.ToString()}\"");
}
}
}
11 changes: 11 additions & 0 deletions Runtime/Algorand.Unity.Crypto/SodiumString.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit fdd3ccb

Please sign in to comment.