Skip to content

Commit

Permalink
make use of SpanHelper in salsa
Browse files Browse the repository at this point in the history
  • Loading branch information
ZingBallyhoo committed Nov 15, 2024
1 parent eedda3a commit def7d29
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions TACTLib/Core/Salsa20.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.IO;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using CommunityToolkit.HighPerformance;
using TACTLib.Helpers;

namespace TACTLib.Core
{
Expand Down Expand Up @@ -55,15 +57,17 @@ public Salsa20(ReadOnlySpan<byte> key, ReadOnlySpan<byte> iv, ulong startOffset=

public void TransformBlocks(ReadOnlySpan<byte> input, Span<byte> output) {
while (input.Length > 0) {
TransformBlock(input, output);

var blockSize = Math.Min(BLOCK_SIZE, input.Length);
input = input.Slice(blockSize);
output = output.Slice(blockSize);

var blockInput = SpanHelper.Advance(ref input, blockSize);
var blockOutput = SpanHelper.Advance(ref output, blockSize);
TransformBlock(blockInput, blockOutput);
}
}

public void TransformBlock(ReadOnlySpan<byte> input, Span<byte> output) {
if (input.Length > 64) throw new InvalidDataException("should only be one block");

var hashOutput = new UIntArray();
var hashOutputBytes = ((ReadOnlySpan<uint>)hashOutput).AsBytes();

Expand All @@ -73,8 +77,7 @@ public void TransformBlock(ReadOnlySpan<byte> input, Span<byte> output) {

// todo: TensorPrimitives?
// or.. full vectorized algorithm? https://github.com/HMBSbige/CryptoBase/blob/master/src/CryptoBase/SymmetricCryptos/StreamCryptos/Salsa20Utils.cs
var blockSize = Math.Min(BLOCK_SIZE, input.Length);
for (var i = 0; i < blockSize; i++)
for (var i = 0; i < input.Length; i++)
output[i] = (byte) (input[i] ^ hashOutputBytes[i]);
}

Expand Down

0 comments on commit def7d29

Please sign in to comment.