repo
stringclasses
245 values
file_path
stringlengths
29
241
code
stringlengths
100
233k
tokens
int64
14
69.4k
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Utilities/CSPRNG/init.luau
--[=[ Cryptography library: Cryptographically Secure RNG Usage: local RandomFloat = CSPRNG.Random() local RandomInt = CSPRNG.RandomInt(1, 100) local RandomNumber = CSPRNG.RandomNumber(0.5, 10.5) local RandomBytes = CSPRNG.RandomBytes(32) local RandomHex = CSPRNG.RandomHex(16) local FastString = CSPRNG.RandomString(16, false) local FastBuffer = CSPRNG.RandomString(32, true) local Ed25519Clamped = CSPRNG.Ed25519ClampedBytes(SomeBuffer) local Ed25519Random = CSPRNG.Ed25519Random() CSPRNG.AddEntropyProvider(function) CSPRNG.RemoveEntropyProvider(function) CSPRNG.Reseed() CSPRNG.BytesLeft --]=] --!strict --!optimize 2 --!native local Conversions = require("@self/Conversions") local ChaCha20 = require("@self/ChaCha20") local Blake3 = require("@self/Blake3") export type EntropyProvider = (BytesLeft: number) -> buffer? type CSPRNGModule = { BlockExpansion: boolean, SizeTarget: number, RekeyAfter: number, Key: buffer, Nonce: buffer, Buffer: buffer, Counter: number, BufferPosition: number, BufferSize: number, BytesLeft: number, EntropyProviders: { EntropyProvider }, Reseed: (CustomEntropy: buffer?) -> (), AddEntropyProvider: (ProviderFunction: EntropyProvider) -> (), RemoveEntropyProvider: (ProviderFunction: EntropyProvider) -> (), Random: () -> number, RandomInt: (Min: number, Max: number?) -> number, RandomNumber: (Min: number, Max: number?) -> number, RandomBytes: (Count: number) -> buffer, RandomString: (Length: number, AsBuffer: boolean?) -> string | buffer, RandomHex: (Length: number) -> string, Ed25519ClampedBytes: (Input: buffer) -> buffer, Ed25519Random: () -> buffer, } local BLOCK_SIZE = 64 local KEY_SIZE = 32 local NONCE_SIZE = 12 local CSPRNG: CSPRNGModule = { BlockExpansion = true, SizeTarget = 2048, RekeyAfter = 1024, Key = buffer.create(0), Nonce = buffer.create(0), Buffer = buffer.create(0), Counter = 0, BufferPosition = 0, BufferSize = 0, BytesLeft = 0, EntropyProviders = {} } :: CSPRNGModule local INPUT_BUFFER = buffer.create(BLOCK_SIZE) local function Reset() CSPRNG.Key = buffer.create(0) CSPRNG.Nonce = buffer.create(0) CSPRNG.Buffer = buffer.create(0) CSPRNG.Counter = 0 CSPRNG.BufferPosition = 0 CSPRNG.BufferSize = 0 end local function GatherEntropy(CustomEntropy: buffer?): number local EntropyBuffers = buffer.create(1024) local Offset = 0 local function WriteToBuffer(Source: buffer) local Size = buffer.len(Source) buffer.copy(EntropyBuffers, Offset, Source, 0, Size) Offset += Size end local CurrentTime = 1.234 if tick then CurrentTime = tick() local TimeBuffer = buffer.create(8) buffer.writef64(TimeBuffer, 0, CurrentTime) WriteToBuffer(TimeBuffer) end local ClockTime = os.clock() local ClockBuffer = buffer.create(8) buffer.writef64(ClockBuffer, 0, ClockTime) WriteToBuffer(ClockBuffer) local UnixTime = os.time() local UnixBuffer = buffer.create(8) buffer.writeu32(UnixBuffer, 0, UnixTime % 0x100000000) buffer.writeu32(UnixBuffer, 4, math.floor(UnixTime / 0x100000000)) WriteToBuffer(UnixBuffer) local DateTimeMillis = 5.678 if DateTime then DateTimeMillis = DateTime.now().UnixTimestampMillis local DateTimeBuffer = buffer.create(8) buffer.writef64(DateTimeBuffer, 0, DateTimeMillis) WriteToBuffer(DateTimeBuffer) local DateTimePrecisionBuffer = buffer.create(16) buffer.writef32(DateTimePrecisionBuffer, 0, DateTimeMillis / 1000) buffer.writef32(DateTimePrecisionBuffer, 4, (DateTimeMillis % 1000) / 100) buffer.writef32(DateTimePrecisionBuffer, 8, DateTimeMillis / 86400000) buffer.writef32(DateTimePrecisionBuffer, 12, (DateTimeMillis * 0.001) % 1) WriteToBuffer(DateTimePrecisionBuffer) else WriteToBuffer(buffer.create(24)) end local FracTimeBuffer = buffer.create(16) buffer.writef32(FracTimeBuffer, 0, ClockTime / 100) buffer.writef32(FracTimeBuffer, 4, CurrentTime / 1000) buffer.writef32(FracTimeBuffer, 8, (ClockTime * 12345.6789) % 1) buffer.writef32(FracTimeBuffer, 12, (CurrentTime * 98765.4321) % 1) WriteToBuffer(FracTimeBuffer) local NoiseBuffer = buffer.create(32) for Index = 0, 7 do local Noise1 = math.noise(ClockTime + Index, UnixTime + Index, ClockTime + UnixTime + Index) local Noise2 = math.noise(CurrentTime + Index * 0.1, DateTimeMillis * 0.0001 + Index, ClockTime * 1.5 + Index) local Noise3 = math.noise(UnixTime * 0.01 + Index, ClockTime + DateTimeMillis * 0.001, CurrentTime + Index * 2) local Noise4 = math.noise(DateTimeMillis * 0.00001 + Index, UnixTime + ClockTime + Index, CurrentTime * 0.1 + Index) buffer.writef32(NoiseBuffer, Index * 4, Noise1 + Noise2 + Noise3 + Noise4) end WriteToBuffer(NoiseBuffer) local BenchmarkTimings = buffer.create(32) for Index = 0, 7 do local StartTime = os.clock() local Sum = 0 local Iterations = 50 + (Index * 25) for Iteration = 1, Iterations do Sum += Iteration * Iteration + math.sin(Iteration / 10) * math.cos(Iteration / 7) end local EndTime = os.clock() local TimingDelta = EndTime - StartTime buffer.writef32(BenchmarkTimings, Index * 4, TimingDelta * 1000000) end WriteToBuffer(BenchmarkTimings) local AllocTimings = buffer.create(24) for Index = 0, 5 do local AllocStart = os.clock() for AllocIndex = 1, 20 do local _TempBuf = buffer.create(64 + AllocIndex) end local AllocEnd = os.clock() buffer.writef32(AllocTimings, Index * 4, (AllocEnd - AllocStart) * 10000000) end WriteToBuffer(AllocTimings) local MicroTime = math.floor(CurrentTime * 1000000) local MicroTimeBuffer = buffer.create(8) buffer.writeu32(MicroTimeBuffer, 0, MicroTime % 0x100000000) buffer.writeu32(MicroTimeBuffer, 4, math.floor(MicroTime / 0x100000000)) WriteToBuffer(MicroTimeBuffer) if game then if game.JobId and #game.JobId > 0 then local JobIdBuffer = buffer.fromstring(game.JobId) WriteToBuffer(JobIdBuffer) end if game.PlaceId then local PlaceIdBuffer = buffer.create(8) buffer.writeu32(PlaceIdBuffer, 0, game.PlaceId % 0x100000000) buffer.writeu32(PlaceIdBuffer, 4, math.floor(game.PlaceId / 0x100000000)) WriteToBuffer(PlaceIdBuffer) end if workspace and workspace.DistributedGameTime then local DistTimeBuffer = buffer.create(8) buffer.writef64(DistTimeBuffer, 0, workspace.DistributedGameTime) WriteToBuffer(DistTimeBuffer) local DistMicroTime = math.floor(workspace.DistributedGameTime * 1000000) local DistMicroBuffer = buffer.create(8) buffer.writeu32(DistMicroBuffer, 0, DistMicroTime % 0x100000000) buffer.writeu32(DistMicroBuffer, 4, math.floor(DistMicroTime / 0x100000000)) WriteToBuffer(DistMicroBuffer) end end local AddressEntropy = buffer.create(128) for Index = 0, 7 do local TempTable = {} local TempFunc = function() end local TempBuffer = buffer.create(0) local TempUserdata = newproxy() local TableAddr = string.gsub(tostring(TempTable), "table: ", "") local FuncAddr = string.gsub(tostring(TempFunc), "function: ", "") local BufferAddr = string.gsub(tostring(TempBuffer), "buffer: ", "") local UserdataAddr = string.gsub(tostring(TempUserdata), "userdata: ", "") local TableHash = 0 local ThreadHash = 0 local FuncHash = 0 local BufferHash = 0 local UserdataHash = 0 for AddrIndex = 1, #TableAddr do TableHash = bit32.bxor(TableHash, string.byte(TableAddr, AddrIndex)) * 31 end if coroutine then local ThreadAddr = string.gsub(tostring(coroutine.create(function() end)), "thread: ", "") for AddrIndex = 1, #ThreadAddr do ThreadHash = bit32.bxor(ThreadHash, string.byte(ThreadAddr, AddrIndex)) * 31 end end for AddrIndex = 1, #FuncAddr do FuncHash = bit32.bxor(FuncHash, string.byte(FuncAddr, AddrIndex)) * 37 end for AddrIndex = 1, #BufferAddr do BufferHash = bit32.bxor(BufferHash, string.byte(BufferAddr, AddrIndex)) * 41 end for AddrIndex = 1, #UserdataAddr do UserdataHash = bit32.bxor(UserdataHash, string.byte(UserdataAddr, AddrIndex)) * 43 end buffer.writeu32(AddressEntropy, Index * 16, TableHash) buffer.writeu32(AddressEntropy, Index * 16 + 4, ThreadHash) buffer.writeu32(AddressEntropy, Index * 16 + 8, FuncHash) buffer.writeu32(AddressEntropy, Index * 16 + 12, bit32.bxor(BufferHash, UserdataHash)) end WriteToBuffer(AddressEntropy) local function AddExtraEntropy(Entropy: buffer?, Warn: boolean, Provider: string?) if not Entropy then return end local BytesLeft = 1024 - Offset if BytesLeft > 0 then local Extra = buffer.len(Entropy) - BytesLeft local Truncated = math.min(BytesLeft, buffer.len(Entropy)) if Extra > 0 and Warn and Provider then warn(`CSPRNG: {Provider} returned {Extra} bytes more than available and was truncated to {Truncated} bytes`) end buffer.copy(EntropyBuffers, Offset, Entropy, 0, Truncated) end end for Index, Provider in CSPRNG.EntropyProviders do local BytesLeft = 1024 - Offset if BytesLeft > 0 then local Success: boolean, ExtraEntropy: buffer? = pcall(Provider, BytesLeft) if not Success then warn(`CSPRNG Provider errored with {ExtraEntropy}`) end AddExtraEntropy(ExtraEntropy, true, `Entropy Provider #{Index}`) end end if CustomEntropy then AddExtraEntropy(CustomEntropy, false) end local KeyMaterial = Blake3(EntropyBuffers, KEY_SIZE + NONCE_SIZE) CSPRNG.Key = buffer.create(KEY_SIZE) buffer.copy(CSPRNG.Key, 0, KeyMaterial, 0, KEY_SIZE) CSPRNG.Nonce = buffer.create(NONCE_SIZE) buffer.copy(CSPRNG.Nonce, 0, KeyMaterial, KEY_SIZE, NONCE_SIZE) return buffer.len(EntropyBuffers) - Offset end local function GenerateBlock() buffer.fill(INPUT_BUFFER, 0, 0, BLOCK_SIZE) local ChaChaOutput = ChaCha20(INPUT_BUFFER, CSPRNG.Key, CSPRNG.Nonce, CSPRNG.Counter, 20) local RekeyThreshold = math.max(math.floor(CSPRNG.RekeyAfter), 2) local SizeTargetClamped = math.clamp(math.floor(CSPRNG.SizeTarget), 64, 4294967295) CSPRNG.Buffer = if CSPRNG.BlockExpansion then Blake3(ChaChaOutput, SizeTargetClamped) else ChaChaOutput CSPRNG.BufferPosition = 0 CSPRNG.BufferSize = buffer.len(CSPRNG.Buffer) CSPRNG.Counter += 1 if CSPRNG.Counter % RekeyThreshold == 0 then GatherEntropy() CSPRNG.Counter = 0 end end local function GetBytes(Count: number): buffer local Result = buffer.create(Count) local ResultPosition = 0 while ResultPosition < Count do if CSPRNG.BufferPosition >= CSPRNG.BufferSize then GenerateBlock() end local BytesNeeded = Count - ResultPosition local BytesAvailable = CSPRNG.BufferSize - CSPRNG.BufferPosition local BytesToCopy = math.min(BytesNeeded, BytesAvailable) buffer.copy(Result, ResultPosition, CSPRNG.Buffer, CSPRNG.BufferPosition, BytesToCopy) ResultPosition += BytesToCopy CSPRNG.BufferPosition += BytesToCopy end return Result end local function GetFloat(): number if CSPRNG.BufferPosition + 8 > CSPRNG.BufferSize then GenerateBlock() end local Value1 = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition) local Value2 = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition + 4) CSPRNG.BufferPosition += 8 local High = bit32.rshift(Value1, 5) local Low = bit32.rshift(Value2, 6) return (High * 67108864.0 + Low) / 9007199254740992.0 end local function GetIntRange(Min: number, Max: number): number local Range = Max - Min + 1 local MaxUInt32 = 0xFFFFFFFF local Limit = MaxUInt32 - (MaxUInt32 % Range) if CSPRNG.BufferPosition + 4 > CSPRNG.BufferSize then GenerateBlock() end local Value = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition) CSPRNG.BufferPosition += 4 if bit32.band(Range, Range - 1) == 0 then return Min + bit32.band(Value, Range - 1) else while Value > Limit do if CSPRNG.BufferPosition + 4 > CSPRNG.BufferSize then GenerateBlock() end Value = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition) CSPRNG.BufferPosition += 4 end return Min + (Value % Range) end end local function GetNumberRange(Min: number, Max: number): number if Min > Max then Min, Max = Max, Min end local Range = Max - Min if Range <= 0 then return Min end return Min + (GetFloat() * Range) end local function GetRandomString(Length: number, AsBuffer: boolean?): string | buffer local Characters = buffer.create(Length) for Index = 0, Length - 1 do buffer.writeu8(Characters, Index, GetIntRange(36, 122)) end return if AsBuffer then Characters else buffer.tostring(Characters) end local function GetEd25519RandomBytes(): buffer local Output = buffer.create(32) for Index = 0, 31 do buffer.writeu8(Output, Index, GetIntRange(0, 255)) end return Output end local function GetEd25519ClampedBytes(Input: buffer): buffer local Output = buffer.create(32) buffer.copy(Output, 0, Input, 0, 32) local FirstByte = buffer.readu8(Output, 0) FirstByte = bit32.band(FirstByte, 0xF8) buffer.writeu8(Output, 0, FirstByte) local LastByte = buffer.readu8(Output, 31) LastByte = bit32.band(LastByte, 0x7F) LastByte = bit32.bor(LastByte, 0x40) buffer.writeu8(Output, 31, LastByte) local HasVariation = false local FirstMiddleByte = buffer.readu8(Output, 1) for Index = 2, 30 do if buffer.readu8(Output, Index) ~= FirstMiddleByte then HasVariation = true break end end if not HasVariation then buffer.writeu8(Output, 15, bit32.bxor(FirstMiddleByte, 0x55)) end return Output end local function GetHexString(Length: number): string local BytesNeeded = Length / 2 local Bytes = GetBytes(BytesNeeded) local Hex = Conversions.ToHex(Bytes) return Hex end function CSPRNG.AddEntropyProvider(ProviderFunction: EntropyProvider) table.insert(CSPRNG.EntropyProviders, ProviderFunction) end function CSPRNG.RemoveEntropyProvider(ProviderFunction: EntropyProvider) for Index = #CSPRNG.EntropyProviders, 1, -1 do if CSPRNG.EntropyProviders[Index] == ProviderFunction then table.remove(CSPRNG.EntropyProviders, Index) break end end end function CSPRNG.Random(): number return GetFloat() end function CSPRNG.RandomInt(Min: number, Max: number?): number if Max and type(Max) ~= "number" then error(`Max must be a number or nil, got {typeof(Max)}`, 2) end if type(Min) ~= "number" then error(`Min must be a number, got {typeof(Min)}`, 2) end if Max and Max < Min then error(`Max ({Max}) can't be less than Min ({Min})`, 2) end if Max and Max == Min then error(`Max ({Max}) can't be equal to Min ({Min})`, 2) end local ActualMax: number local ActualMin: number if Max == nil then ActualMax = Min ActualMin = 1 else ActualMax = Max ActualMin = Min end return GetIntRange(ActualMin, ActualMax) end function CSPRNG.RandomNumber(Min: number, Max: number?): number if Max and type(Max) ~= "number" then error(`Max must be a number or nil, got {typeof(Max)}`, 2) end if type(Min) ~= "number" then error(`Min must be a number, got {typeof(Min)}`, 2) end if Max and Max < Min then error(`Max ({Max}) must be bigger than Min ({Min})`, 2) end if Max and Max == Min then error(`Max ({Max}) can't be equal to Min ({Min})`, 2) end local ActualMax: number local ActualMin: number if Max == nil then ActualMax = Min ActualMin = 0 else ActualMax = Max ActualMin = Min end return GetNumberRange(ActualMin, ActualMax) end function CSPRNG.RandomBytes(Count: number): buffer if type(Count) ~= "number" then error(`Count must be a number, got {typeof(Count)}`, 2) end if Count <= 0 then error(`Count must be bigger than 0, got {Count}`, 2) end if Count % 1 ~= 0 then error("Count must be an integer", 2) end return GetBytes(Count) end function CSPRNG.RandomString(Length: number, AsBuffer: boolean?): string | buffer if type(Length) ~= "number" then error(`Length must be a number, got {typeof(Length)}`, 2) end if Length <= 0 then error(`Length must be bigger than 0, got {Length}`, 2) end if Length % 1 ~= 0 then error("Length must be an integer", 2) end if AsBuffer ~= nil and type(AsBuffer) ~= "boolean" then error(`AsBuffer must be a boolean or nil, got {typeof(AsBuffer)}`, 2) end return GetRandomString(Length, AsBuffer) end function CSPRNG.RandomHex(Length: number): string if type(Length) ~= "number" then error(`Length must be a number, got {typeof(Length)}`, 2) end if Length <= 0 then error(`Length must be bigger than 0, got {Length}`, 2) end if Length % 1 ~= 0 then error("Length must be an integer", 2) end if Length % 2 ~= 0 then error(`Length must be even, got {Length}`, 2) end return GetHexString(Length) end function CSPRNG.Ed25519ClampedBytes(Input: buffer): buffer if type(Input) ~= "buffer" then error(`Input must be a buffer, got {typeof(Input)}`, 2) end return GetEd25519ClampedBytes(Input) end function CSPRNG.Ed25519Random(): buffer return GetEd25519ClampedBytes(GetEd25519RandomBytes()) end function CSPRNG.Reseed(CustomEntropy: buffer?) if CustomEntropy ~= nil and type(CustomEntropy) ~= "buffer" then error(`CustomEntropy must be a buffer or nil, got {typeof(CustomEntropy)}`, 2) end Reset() GatherEntropy(CustomEntropy) end CSPRNG.BytesLeft = GatherEntropy() GenerateBlock() return CSPRNG
5,064
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Utilities/RandomString.luau
--[=[ Cryptography library: Random String Generator ⚠️WARNING: This is not using cryptographically secure random numbers. For Security use CSPRNG.⚠️ Return type: string | buffer Example Usage: local String = RandomString(500) --]=] --!strict --!optimize 2 --!native local function RandomString(Length: number, AsBuffer: boolean?): string | buffer local Characters = buffer.create(Length) for Index = 0, Length - 1 do buffer.writeu8(Characters, Index, math.random(36, 122)) end return if AsBuffer then Characters else buffer.tostring(Characters) end return RandomString
159
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Utilities/init.luau
--!strict local Algorithms = table.freeze({ RandomString = require("@self/RandomString"), Conversions = require("@self/Conversions"), Base64 = require("@self/Base64"), CSPRNG = require("@self/CSPRNG") }) return Algorithms
55
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/CSPRNG/Blake3.luau
--[=[ Cryptography library: Blake3 Sizes: Key: 32 bytes Output: variable Return type: string (hex) Example usage: local Message = buffer.fromstring("Hello World") local Key = buffer.fromstring(string.rep("k", 32)) --------Standard Hash-------- local Hash = Blake3.Digest(Message, 32) --------Keyed Hash-------- local KeyedHash = Blake3.DigestKeyed(Key, Message, 32) --------Key Derivation-------- local Context = buffer.fromstring("my context") local KeyDeriver = Blake3.DeriveKey(Context) local DerivedKey = KeyDeriver(Message, 32) --]=] --!strict --!optimize 2 --!native local BLOCK_SIZE = 64 local CV_SIZE = 32 local EXTENDED_CV_SIZE = 64 local MAX_STACK_DEPTH = 64 local STACK_BUFFER_SIZE = MAX_STACK_DEPTH * CV_SIZE local CHUNK_START = 0x01 local CHUNK_END = 0x02 local PARENT_FLAG = 0x04 local ROOT_FLAG = 0x08 local INITIAL_VECTORS = buffer.create(CV_SIZE) do local IV = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, } for Index, Value in ipairs(IV) do buffer.writeu32(INITIAL_VECTORS, (Index - 1) * 4, Value) end end local function Compress(Hash: buffer, MessageBlock: buffer, Counter: number, V14: number, V15: number, IsFull: boolean?): buffer local Hash00 = buffer.readu32(Hash, 0) local Hash01 = buffer.readu32(Hash, 4) local Hash02 = buffer.readu32(Hash, 8) local Hash03 = buffer.readu32(Hash, 12) local Hash04 = buffer.readu32(Hash, 16) local Hash05 = buffer.readu32(Hash, 20) local Hash06 = buffer.readu32(Hash, 24) local Hash07 = buffer.readu32(Hash, 28) local V00, V01, V02, V03 = Hash00, Hash01, Hash02, Hash03 local V04, V05, V06, V07 = Hash04, Hash05, Hash06, Hash07 local V08, V09, V10, V11 = 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a local V12 = Counter % (2 ^ 32) local V13 = (Counter - V12) * (2 ^ -32) local M00 = buffer.readu32(MessageBlock, 0) local M01 = buffer.readu32(MessageBlock, 4) local M02 = buffer.readu32(MessageBlock, 8) local M03 = buffer.readu32(MessageBlock, 12) local M04 = buffer.readu32(MessageBlock, 16) local M05 = buffer.readu32(MessageBlock, 20) local M06 = buffer.readu32(MessageBlock, 24) local M07 = buffer.readu32(MessageBlock, 28) local M08 = buffer.readu32(MessageBlock, 32) local M09 = buffer.readu32(MessageBlock, 36) local M10 = buffer.readu32(MessageBlock, 40) local M11 = buffer.readu32(MessageBlock, 44) local M12 = buffer.readu32(MessageBlock, 48) local M13 = buffer.readu32(MessageBlock, 52) local M14 = buffer.readu32(MessageBlock, 56) local M15 = buffer.readu32(MessageBlock, 60) local Temp for Index = 1, 7 do V00 += V04 + M00; V12 = bit32.lrotate(bit32.bxor(V12, V00), 16) V08 += V12; V04 = bit32.lrotate(bit32.bxor(V04, V08), 20) V00 += V04 + M01; V12 = bit32.lrotate(bit32.bxor(V12, V00), 24) V08 += V12; V04 = bit32.lrotate(bit32.bxor(V04, V08), 25) V01 += V05 + M02; V13 = bit32.lrotate(bit32.bxor(V13, V01), 16) V09 += V13; V05 = bit32.lrotate(bit32.bxor(V05, V09), 20) V01 += V05 + M03; V13 = bit32.lrotate(bit32.bxor(V13, V01), 24) V09 += V13; V05 = bit32.lrotate(bit32.bxor(V05, V09), 25) V02 += V06 + M04; V14 = bit32.lrotate(bit32.bxor(V14, V02), 16) V10 += V14; V06 = bit32.lrotate(bit32.bxor(V06, V10), 20) V02 += V06 + M05; V14 = bit32.lrotate(bit32.bxor(V14, V02), 24) V10 += V14; V06 = bit32.lrotate(bit32.bxor(V06, V10), 25) V03 += V07 + M06; V15 = bit32.lrotate(bit32.bxor(V15, V03), 16) V11 += V15; V07 = bit32.lrotate(bit32.bxor(V07, V11), 20) V03 += V07 + M07; V15 = bit32.lrotate(bit32.bxor(V15, V03), 24) V11 += V15; V07 = bit32.lrotate(bit32.bxor(V07, V11), 25) V00 += V05 + M08; V15 = bit32.lrotate(bit32.bxor(V15, V00), 16) V10 += V15; V05 = bit32.lrotate(bit32.bxor(V05, V10), 20) V00 += V05 + M09; V15 = bit32.lrotate(bit32.bxor(V15, V00), 24) V10 += V15; V05 = bit32.lrotate(bit32.bxor(V05, V10), 25) V01 += V06 + M10; V12 = bit32.lrotate(bit32.bxor(V12, V01), 16) V11 += V12; V06 = bit32.lrotate(bit32.bxor(V06, V11), 20) V01 += V06 + M11; V12 = bit32.lrotate(bit32.bxor(V12, V01), 24) V11 += V12; V06 = bit32.lrotate(bit32.bxor(V06, V11), 25) V02 += V07 + M12; V13 = bit32.lrotate(bit32.bxor(V13, V02), 16) V08 += V13; V07 = bit32.lrotate(bit32.bxor(V07, V08), 20) V02 += V07 + M13; V13 = bit32.lrotate(bit32.bxor(V13, V02), 24) V08 += V13; V07 = bit32.lrotate(bit32.bxor(V07, V08), 25) V03 += V04 + M14; V14 = bit32.lrotate(bit32.bxor(V14, V03), 16) V09 += V14; V04 = bit32.lrotate(bit32.bxor(V04, V09), 20) V03 += V04 + M15; V14 = bit32.lrotate(bit32.bxor(V14, V03), 24) V09 += V14; V04 = bit32.lrotate(bit32.bxor(V04, V09), 25) if Index ~= 7 then Temp = M02 M02 = M03 M03 = M10 M10 = M12 M12 = M09 M09 = M11 M11 = M05 M05 = M00 M00 = Temp Temp = M06 M06 = M04 M04 = M07 M07 = M13 M13 = M14 M14 = M15 M15 = M08 M08 = M01 M01 = Temp end end if IsFull then local Result = buffer.create(EXTENDED_CV_SIZE) buffer.writeu32(Result, 0, bit32.bxor(V00, V08)) buffer.writeu32(Result, 4, bit32.bxor(V01, V09)) buffer.writeu32(Result, 8, bit32.bxor(V02, V10)) buffer.writeu32(Result, 12, bit32.bxor(V03, V11)) buffer.writeu32(Result, 16, bit32.bxor(V04, V12)) buffer.writeu32(Result, 20, bit32.bxor(V05, V13)) buffer.writeu32(Result, 24, bit32.bxor(V06, V14)) buffer.writeu32(Result, 28, bit32.bxor(V07, V15)) buffer.writeu32(Result, 32, bit32.bxor(V08, Hash00)) buffer.writeu32(Result, 36, bit32.bxor(V09, Hash01)) buffer.writeu32(Result, 40, bit32.bxor(V10, Hash02)) buffer.writeu32(Result, 44, bit32.bxor(V11, Hash03)) buffer.writeu32(Result, 48, bit32.bxor(V12, Hash04)) buffer.writeu32(Result, 52, bit32.bxor(V13, Hash05)) buffer.writeu32(Result, 56, bit32.bxor(V14, Hash06)) buffer.writeu32(Result, 60, bit32.bxor(V15, Hash07)) return Result else local Result = buffer.create(CV_SIZE) buffer.writeu32(Result, 0, bit32.bxor(V00, V08)) buffer.writeu32(Result, 4, bit32.bxor(V01, V09)) buffer.writeu32(Result, 8, bit32.bxor(V02, V10)) buffer.writeu32(Result, 12, bit32.bxor(V03, V11)) buffer.writeu32(Result, 16, bit32.bxor(V04, V12)) buffer.writeu32(Result, 20, bit32.bxor(V05, V13)) buffer.writeu32(Result, 24, bit32.bxor(V06, V14)) buffer.writeu32(Result, 28, bit32.bxor(V07, V15)) return Result end end local function ProcessMessage(InitialHashVector: buffer, Flags: number, Message: buffer, Length: number): buffer local MessageLength = buffer.len(Message) local StateCvs = buffer.create(STACK_BUFFER_SIZE) local StackSize = 0 local StateCv = buffer.create(CV_SIZE) buffer.copy(StateCv, 0, InitialHashVector, 0, CV_SIZE) local StateCounter = 0 local StateChunkNumber = 0 local StateEndFlag = 0 local StateStartFlag = CHUNK_START local BlockBuffer = buffer.create(BLOCK_SIZE) for BlockOffset = 0, MessageLength - BLOCK_SIZE - 1, BLOCK_SIZE do buffer.copy(BlockBuffer, 0, Message, BlockOffset, BLOCK_SIZE) local StateFlags = Flags + StateStartFlag + StateEndFlag StateCv = Compress(StateCv, BlockBuffer, StateCounter, BLOCK_SIZE, StateFlags) StateStartFlag = 0 StateChunkNumber += 1 if StateChunkNumber == 15 then StateEndFlag = CHUNK_END elseif StateChunkNumber == 16 then local MergeCv = StateCv local MergeAmount = StateCounter + 1 while MergeAmount % 2 == 0 do StackSize = StackSize - 1 local PopCv = buffer.create(CV_SIZE) buffer.copy(PopCv, 0, StateCvs, StackSize * CV_SIZE, CV_SIZE) local Block = buffer.create(EXTENDED_CV_SIZE) buffer.copy(Block, 0, PopCv, 0, CV_SIZE) buffer.copy(Block, CV_SIZE, MergeCv, 0, CV_SIZE) MergeCv = Compress(InitialHashVector, Block, 0, BLOCK_SIZE, Flags + PARENT_FLAG) MergeAmount = MergeAmount / 2 end buffer.copy(StateCvs, StackSize * CV_SIZE, MergeCv, 0, CV_SIZE) StackSize = StackSize + 1 buffer.copy(StateCv, 0, InitialHashVector, 0, CV_SIZE) StateStartFlag = CHUNK_START StateCounter += 1 StateChunkNumber = 0 StateEndFlag = 0 end end local LastLength = MessageLength == 0 and 0 or ((MessageLength - 1) % BLOCK_SIZE + 1) local PaddedMessage = buffer.create(BLOCK_SIZE) if LastLength > 0 then buffer.copy(PaddedMessage, 0, Message, MessageLength - LastLength, LastLength) end local OutputCv: buffer local OutputBlock: buffer local OutputLength: number local OutputFlags: number if StateCounter > 0 then local StateFlags = Flags + StateStartFlag + CHUNK_END local MergeCv = Compress(StateCv, PaddedMessage, StateCounter, LastLength, StateFlags) for Index = StackSize, 2, -1 do local StackCv = buffer.create(CV_SIZE) buffer.copy(StackCv, 0, StateCvs, (Index - 1) * CV_SIZE, CV_SIZE) local Block = buffer.create(EXTENDED_CV_SIZE) buffer.copy(Block, 0, StackCv, 0, CV_SIZE) buffer.copy(Block, CV_SIZE, MergeCv, 0, CV_SIZE) MergeCv = Compress(InitialHashVector, Block, 0, BLOCK_SIZE, Flags + PARENT_FLAG) end OutputCv = InitialHashVector local FirstStackCv = buffer.create(CV_SIZE) buffer.copy(FirstStackCv, 0, StateCvs, 0, CV_SIZE) OutputBlock = buffer.create(EXTENDED_CV_SIZE) buffer.copy(OutputBlock, 0, FirstStackCv, 0, CV_SIZE) buffer.copy(OutputBlock, CV_SIZE, MergeCv, 0, CV_SIZE) OutputLength = BLOCK_SIZE OutputFlags = Flags + ROOT_FLAG + PARENT_FLAG else OutputCv = StateCv OutputBlock = PaddedMessage OutputLength = LastLength OutputFlags = Flags + StateStartFlag + CHUNK_END + ROOT_FLAG end local Output = buffer.create(Length) local OutputOffset = 0 for Index = 0, Length // BLOCK_SIZE do local MessageDigest = Compress(OutputCv, OutputBlock, Index, OutputLength, OutputFlags, true) local BytesToCopy = math.min(BLOCK_SIZE, Length - OutputOffset) buffer.copy(Output, OutputOffset, MessageDigest, 0, BytesToCopy) OutputOffset += BytesToCopy if OutputOffset >= Length then break end end return Output end return function(Message: buffer, Length: number?): buffer return ProcessMessage(INITIAL_VECTORS, 0, Message, Length or 32) end
3,543
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/CSPRNG/ChaCha20.luau
--[=[ Cryptography library: ChaCha20 Sizes: Nonce: 12 bytes Key: 16/32 bytes Return type: buffer Example usage: local Data = buffer.fromstring("Hello World") local Key = buffer.fromstring(string.rep("k", 32)) local Nonce = buffer.fromstring(string.rep("n", 12)) --------Usage Case 1-------- local Encrypted = ChaCha20(Data, Key, Nonce) --------Usage Case 2-------- local Decrypted = ChaCha20(Encrypted, Key, Nonce) --]=] --!strict --!native --!optimize 2 local DWORD = 4 local BLOCK_SIZE = 64 local STATE_SIZE = 16 local CHACHA20_NONCE_SIZE = 12 local CHACHA20_KEY_SIZE_16 = 16 local CHACHA20_KEY_SIZE_32 = 32 local SIGMA_CONSTANTS = buffer.create(16) do local SigmaBytes = { string.byte("expand 32-byte k", 1, -1) } for Index, ByteValue in SigmaBytes do buffer.writeu8(SIGMA_CONSTANTS, Index - 1, ByteValue) end end local TAU_CONSTANTS = buffer.create(16) do local TauBytes = { string.byte("expand 16-byte k", 1, -1) } for Index, ByteValue in TauBytes do buffer.writeu8(TAU_CONSTANTS, Index - 1, ByteValue) end end local function ProcessBlock(InitialState: buffer, Rounds: number) local S0: number, S1: number, S2: number, S3: number, S4: number, S5: number, S6: number, S7: number, S8: number, S9: number, S10: number, S11: number, S12: number, S13: number, S14: number, S15: number = buffer.readu32(InitialState, 0), buffer.readu32(InitialState, 4), buffer.readu32(InitialState, 8), buffer.readu32(InitialState, 12), buffer.readu32(InitialState, 16), buffer.readu32(InitialState, 20), buffer.readu32(InitialState, 24), buffer.readu32(InitialState, 28), buffer.readu32(InitialState, 32), buffer.readu32(InitialState, 36), buffer.readu32(InitialState, 40), buffer.readu32(InitialState, 44), buffer.readu32(InitialState, 48), buffer.readu32(InitialState, 52), buffer.readu32(InitialState, 56), buffer.readu32(InitialState, 60) for Round = 1, Rounds do local IsOddRound = Round % 2 == 1 if IsOddRound then S0 = bit32.bor(S0 + S4, 0); S12 = bit32.lrotate(bit32.bxor(S12, S0), 16) S8 = bit32.bor(S8 + S12, 0); S4 = bit32.lrotate(bit32.bxor(S4, S8), 12) S0 = bit32.bor(S0 + S4, 0); S12 = bit32.lrotate(bit32.bxor(S12, S0), 8) S8 = bit32.bor(S8 + S12, 0); S4 = bit32.lrotate(bit32.bxor(S4, S8), 7) S1 = bit32.bor(S1 + S5, 0); S13 = bit32.lrotate(bit32.bxor(S13, S1), 16) S9 = bit32.bor(S9 + S13, 0); S5 = bit32.lrotate(bit32.bxor(S5, S9), 12) S1 = bit32.bor(S1 + S5, 0); S13 = bit32.lrotate(bit32.bxor(S13, S1), 8) S9 = bit32.bor(S9 + S13, 0); S5 = bit32.lrotate(bit32.bxor(S5, S9), 7) S2 = bit32.bor(S2 + S6, 0); S14 = bit32.lrotate(bit32.bxor(S14, S2), 16) S10 = bit32.bor(S10 + S14, 0); S6 = bit32.lrotate(bit32.bxor(S6, S10), 12) S2 = bit32.bor(S2 + S6, 0); S14 = bit32.lrotate(bit32.bxor(S14, S2), 8) S10 = bit32.bor(S10 + S14, 0); S6 = bit32.lrotate(bit32.bxor(S6, S10), 7) S3 = bit32.bor(S3 + S7, 0); S15 = bit32.lrotate(bit32.bxor(S15, S3), 16) S11 = bit32.bor(S11 + S15, 0); S7 = bit32.lrotate(bit32.bxor(S7, S11), 12) S3 = bit32.bor(S3 + S7, 0); S15 = bit32.lrotate(bit32.bxor(S15, S3), 8) S11 = bit32.bor(S11 + S15, 0); S7 = bit32.lrotate(bit32.bxor(S7, S11), 7) else S0 = bit32.bor(S0 + S5, 0); S15 = bit32.lrotate(bit32.bxor(S15, S0), 16) S10 = bit32.bor(S10 + S15, 0); S5 = bit32.lrotate(bit32.bxor(S5, S10), 12) S0 = bit32.bor(S0 + S5, 0); S15 = bit32.lrotate(bit32.bxor(S15, S0), 8) S10 = bit32.bor(S10 + S15, 0); S5 = bit32.lrotate(bit32.bxor(S5, S10), 7) S1 = bit32.bor(S1 + S6, 0); S12 = bit32.lrotate(bit32.bxor(S12, S1), 16) S11 = bit32.bor(S11 + S12, 0); S6 = bit32.lrotate(bit32.bxor(S6, S11), 12) S1 = bit32.bor(S1 + S6, 0); S12 = bit32.lrotate(bit32.bxor(S12, S1), 8) S11 = bit32.bor(S11 + S12, 0); S6 = bit32.lrotate(bit32.bxor(S6, S11), 7) S2 = bit32.bor(S2 + S7, 0); S13 = bit32.lrotate(bit32.bxor(S13, S2), 16) S8 = bit32.bor(S8 + S13, 0); S7 = bit32.lrotate(bit32.bxor(S7, S8), 12) S2 = bit32.bor(S2 + S7, 0); S13 = bit32.lrotate(bit32.bxor(S13, S2), 8) S8 = bit32.bor(S8 + S13, 0); S7 = bit32.lrotate(bit32.bxor(S7, S8), 7) S3 = bit32.bor(S3 + S4, 0); S14 = bit32.lrotate(bit32.bxor(S14, S3), 16) S9 = bit32.bor(S9 + S14, 0); S4 = bit32.lrotate(bit32.bxor(S4, S9), 12) S3 = bit32.bor(S3 + S4, 0); S14 = bit32.lrotate(bit32.bxor(S14, S3), 8) S9 = bit32.bor(S9 + S14, 0); S4 = bit32.lrotate(bit32.bxor(S4, S9), 7) end end buffer.writeu32(InitialState, 0, buffer.readu32(InitialState, 0) + S0) buffer.writeu32(InitialState, 4, buffer.readu32(InitialState, 4) + S1) buffer.writeu32(InitialState, 8, buffer.readu32(InitialState, 8) + S2) buffer.writeu32(InitialState, 12, buffer.readu32(InitialState, 12) + S3) buffer.writeu32(InitialState, 16, buffer.readu32(InitialState, 16) + S4) buffer.writeu32(InitialState, 20, buffer.readu32(InitialState, 20) + S5) buffer.writeu32(InitialState, 24, buffer.readu32(InitialState, 24) + S6) buffer.writeu32(InitialState, 28, buffer.readu32(InitialState, 28) + S7) buffer.writeu32(InitialState, 32, buffer.readu32(InitialState, 32) + S8) buffer.writeu32(InitialState, 36, buffer.readu32(InitialState, 36) + S9) buffer.writeu32(InitialState, 40, buffer.readu32(InitialState, 40) + S10) buffer.writeu32(InitialState, 44, buffer.readu32(InitialState, 44) + S11) buffer.writeu32(InitialState, 48, buffer.readu32(InitialState, 48) + S12) buffer.writeu32(InitialState, 52, buffer.readu32(InitialState, 52) + S13) buffer.writeu32(InitialState, 56, buffer.readu32(InitialState, 56) + S14) buffer.writeu32(InitialState, 60, buffer.readu32(InitialState, 60) + S15) end local function InitializeState(Key: buffer, Nonce: buffer, Counter: number): buffer local KeyLength = buffer.len(Key) local State = buffer.create(STATE_SIZE * DWORD) local Constants = KeyLength == 32 and SIGMA_CONSTANTS or TAU_CONSTANTS buffer.copy(State, 0, Constants, 0, 16) buffer.copy(State, 16, Key, 0, math.min(KeyLength, 16)) if KeyLength == 32 then buffer.copy(State, 32, Key, 16, 16) else buffer.copy(State, 32, Key, 0, 16) end buffer.writeu32(State, 48, Counter) buffer.copy(State, 52, Nonce, 0, 12) return State end local function ChaCha20(Data: buffer, Key: buffer, Nonce: buffer, Counter: number?, Rounds: number?): buffer if Data == nil then error("Data cannot be nil", 2) end if typeof(Data) ~= "buffer" then error(`Data must be a buffer, got {typeof(Data)}`, 2) end if Key == nil then error("Key cannot be nil", 2) end if typeof(Key) ~= "buffer" then error(`Key must be a buffer, got {typeof(Key)}`, 2) end local KeyLength = buffer.len(Key) if KeyLength ~= CHACHA20_KEY_SIZE_16 and KeyLength ~= CHACHA20_KEY_SIZE_32 then error(`Key must be {CHACHA20_KEY_SIZE_16} or {CHACHA20_KEY_SIZE_32} bytes long, got {KeyLength} bytes`, 2) end if Nonce == nil then error("Nonce cannot be nil", 2) end if typeof(Nonce) ~= "buffer" then error(`Nonce must be a buffer, got {typeof(Nonce)}`, 2) end local NonceLength = buffer.len(Nonce) if NonceLength ~= CHACHA20_NONCE_SIZE then error(`Nonce must be exactly {CHACHA20_NONCE_SIZE} bytes long, got {NonceLength} bytes`, 2) end if Counter then if typeof(Counter) ~= "number" then error(`Counter must be a number, got {typeof(Counter)}`, 2) end if Counter < 0 then error(`Counter cannot be negative, got {Counter}`, 2) end if Counter ~= math.floor(Counter) then error(`Counter must be an integer, got {Counter}`, 2) end if Counter >= 2^32 then error(`Counter must be less than 2^32, got {Counter}`, 2) end end if Rounds then if typeof(Rounds) ~= "number" then error(`Rounds must be a number, got {typeof(Rounds)}`, 2) end if Rounds <= 0 then error(`Rounds must be positive, got {Rounds}`, 2) end if Rounds ~= math.floor(Rounds) then error(`Rounds must be an integer, got {Rounds}`, 2) end if Rounds % 2 ~= 0 then error(`Rounds must be even, got {Rounds}`, 2) end end local BlockCounter = Counter or 1 local BlockRounds = Rounds or 20 local DataLength = buffer.len(Data) if DataLength == 0 then return buffer.create(0) end local Output = buffer.create(DataLength) local DataOffset = 0 local State = InitializeState(Key, Nonce, BlockCounter) local StateBackup = buffer.create(64) buffer.copy(StateBackup, 0, State, 0) while DataOffset < DataLength do ProcessBlock(State, BlockRounds) local BytesToProcess = math.min(BLOCK_SIZE, DataLength - DataOffset) for Index = 0, BytesToProcess - 1 do local DataByte = buffer.readu8(Data, DataOffset + Index) local KeystreamByte = buffer.readu8(State, Index) buffer.writeu8(Output, DataOffset + Index, bit32.bxor(DataByte, KeystreamByte)) end DataOffset += BytesToProcess BlockCounter += 1 buffer.copy(State, 0, StateBackup, 0) buffer.writeu32(State, 48, BlockCounter) end return Output end return ChaCha20
3,202
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/CSPRNG/init.luau
--[=[ Cryptography library: Cryptographically Secure RNG Usage: local RandomFloat = CSPRNG.Random() local RandomInt = CSPRNG.RandomInt(1, 100) local RandomNumber = CSPRNG.RandomNumber(0.5, 10.5) local RandomBytes = CSPRNG.RandomBytes(32) local RandomHex = CSPRNG.RandomHex(16) local FastString = CSPRNG.RandomString(16, false) local FastBuffer = CSPRNG.RandomString(32, true) local Ed25519Clamped = CSPRNG.Ed25519ClampedBytes(SomeBuffer) local Ed25519Random = CSPRNG.Ed25519Random() CSPRNG.AddEntropyProvider(function) CSPRNG.RemoveEntropyProvider(function) CSPRNG.Reseed() CSPRNG.BytesLeft --]=] --!native --!optimize 2 --!strict local Conversions = require("@self/Conversions") local ChaCha20 = require("@self/ChaCha20") local Blake3 = require("@self/Blake3") export type EntropyProvider = (BytesLeft: number) -> buffer? type CSPRNGModule = { BlockExpansion: boolean, SizeTarget: number, RekeyAfter: number, Key: buffer, Nonce: buffer, Buffer: buffer, Counter: number, BufferPosition: number, BufferSize: number, BytesLeft: number, EntropyProviders: { EntropyProvider }, Reseed: (CustomEntropy: buffer?) -> (), AddEntropyProvider: (ProviderFunction: EntropyProvider) -> (), RemoveEntropyProvider: (ProviderFunction: EntropyProvider) -> (), Random: () -> number, RandomInt: (Min: number, Max: number?) -> number, RandomNumber: (Min: number, Max: number?) -> number, RandomBytes: (Count: number) -> buffer, RandomString: (Length: number, AsBuffer: boolean?) -> string | buffer, RandomHex: (Length: number) -> string, Ed25519ClampedBytes: (Input: buffer) -> buffer, Ed25519Random: () -> buffer, } local BLOCK_SIZE = 64 local KEY_SIZE = 32 local NONCE_SIZE = 12 local CSPRNG: CSPRNGModule = { BlockExpansion = true, SizeTarget = 2048, RekeyAfter = 1024, Key = buffer.create(0), Nonce = buffer.create(0), Buffer = buffer.create(0), Counter = 0, BufferPosition = 0, BufferSize = 0, BytesLeft = 0, EntropyProviders = {} } :: CSPRNGModule local INPUT_BUFFER = buffer.create(BLOCK_SIZE) local REKEY_THRESHOLD = math.max(math.floor(CSPRNG.RekeyAfter), 2) local SIZE_TARGET_CLAMPED = math.clamp(math.floor(CSPRNG.SizeTarget), 64, 4294967295) local function Reset() CSPRNG.Key = buffer.create(0) CSPRNG.Nonce = buffer.create(0) CSPRNG.Buffer = buffer.create(0) CSPRNG.Counter = 0 CSPRNG.BufferPosition = 0 CSPRNG.BufferSize = 0 end local function GatherEntropy(CustomEntropy: buffer?): number local EntropyBuffers = buffer.create(1024) local Offset = 0 local function WriteToBuffer(Source: buffer) local Size = buffer.len(Source) buffer.copy(EntropyBuffers, Offset, Source, 0, Size) Offset += Size end local CurrentTime = 1.234 if tick then CurrentTime = tick() local TimeBuffer = buffer.create(8) buffer.writef64(TimeBuffer, 0, CurrentTime) WriteToBuffer(TimeBuffer) end local ClockTime = os.clock() local ClockBuffer = buffer.create(8) buffer.writef64(ClockBuffer, 0, ClockTime) WriteToBuffer(ClockBuffer) local UnixTime = os.time() local UnixBuffer = buffer.create(8) buffer.writeu32(UnixBuffer, 0, UnixTime % 0x100000000) buffer.writeu32(UnixBuffer, 4, math.floor(UnixTime / 0x100000000)) WriteToBuffer(UnixBuffer) local DateTimeMillis = 5.678 if DateTime then DateTimeMillis = DateTime.now().UnixTimestampMillis local DateTimeBuffer = buffer.create(8) buffer.writef64(DateTimeBuffer, 0, DateTimeMillis) WriteToBuffer(DateTimeBuffer) local DateTimePrecisionBuffer = buffer.create(16) buffer.writef32(DateTimePrecisionBuffer, 0, DateTimeMillis / 1000) buffer.writef32(DateTimePrecisionBuffer, 4, (DateTimeMillis % 1000) / 100) buffer.writef32(DateTimePrecisionBuffer, 8, DateTimeMillis / 86400000) buffer.writef32(DateTimePrecisionBuffer, 12, (DateTimeMillis * 0.001) % 1) WriteToBuffer(DateTimePrecisionBuffer) else WriteToBuffer(buffer.create(24)) end local FracTimeBuffer = buffer.create(16) buffer.writef32(FracTimeBuffer, 0, ClockTime / 100) buffer.writef32(FracTimeBuffer, 4, CurrentTime / 1000) buffer.writef32(FracTimeBuffer, 8, (ClockTime * 12345.6789) % 1) buffer.writef32(FracTimeBuffer, 12, (CurrentTime * 98765.4321) % 1) WriteToBuffer(FracTimeBuffer) local NoiseBuffer = buffer.create(32) for Index = 0, 7 do local Noise1 = math.noise(ClockTime + Index, UnixTime + Index, ClockTime + UnixTime + Index) local Noise2 = math.noise(CurrentTime + Index * 0.1, DateTimeMillis * 0.0001 + Index, ClockTime * 1.5 + Index) local Noise3 = math.noise(UnixTime * 0.01 + Index, ClockTime + DateTimeMillis * 0.001, CurrentTime + Index * 2) local Noise4 = math.noise(DateTimeMillis * 0.00001 + Index, UnixTime + ClockTime + Index, CurrentTime * 0.1 + Index) buffer.writef32(NoiseBuffer, Index * 4, Noise1 + Noise2 + Noise3 + Noise4) end WriteToBuffer(NoiseBuffer) local BenchmarkTimings = buffer.create(32) for Index = 0, 7 do local StartTime = os.clock() local Sum = 0 local Iterations = 50 + (Index * 25) for Iteration = 1, Iterations do Sum += Iteration * Iteration + math.sin(Iteration / 10) * math.cos(Iteration / 7) end local EndTime = os.clock() local TimingDelta = EndTime - StartTime buffer.writef32(BenchmarkTimings, Index * 4, TimingDelta * 1000000) end WriteToBuffer(BenchmarkTimings) local AllocTimings = buffer.create(24) for Index = 0, 5 do local AllocStart = os.clock() for AllocIndex = 1, 20 do local _TempBuf = buffer.create(64 + AllocIndex) end local AllocEnd = os.clock() buffer.writef32(AllocTimings, Index * 4, (AllocEnd - AllocStart) * 10000000) end WriteToBuffer(AllocTimings) local MicroTime = math.floor(CurrentTime * 1000000) local MicroTimeBuffer = buffer.create(8) buffer.writeu32(MicroTimeBuffer, 0, MicroTime % 0x100000000) buffer.writeu32(MicroTimeBuffer, 4, math.floor(MicroTime / 0x100000000)) WriteToBuffer(MicroTimeBuffer) if game then if game.JobId and #game.JobId > 0 then local JobIdBuffer = buffer.fromstring(game.JobId) WriteToBuffer(JobIdBuffer) end if game.PlaceId then local PlaceIdBuffer = buffer.create(8) buffer.writeu32(PlaceIdBuffer, 0, game.PlaceId % 0x100000000) buffer.writeu32(PlaceIdBuffer, 4, math.floor(game.PlaceId / 0x100000000)) WriteToBuffer(PlaceIdBuffer) end if workspace and workspace.DistributedGameTime then local DistTimeBuffer = buffer.create(8) buffer.writef64(DistTimeBuffer, 0, workspace.DistributedGameTime) WriteToBuffer(DistTimeBuffer) local DistMicroTime = math.floor(workspace.DistributedGameTime * 1000000) local DistMicroBuffer = buffer.create(8) buffer.writeu32(DistMicroBuffer, 0, DistMicroTime % 0x100000000) buffer.writeu32(DistMicroBuffer, 4, math.floor(DistMicroTime / 0x100000000)) WriteToBuffer(DistMicroBuffer) end end local AddressEntropy = buffer.create(128) for Index = 0, 7 do local TempTable = {} local TempFunc = function() end local TempBuffer = buffer.create(0) local TempUserdata = newproxy() local TableAddr = string.gsub(tostring(TempTable), "table: ", "") local FuncAddr = string.gsub(tostring(TempFunc), "function: ", "") local BufferAddr = string.gsub(tostring(TempBuffer), "buffer: ", "") local UserdataAddr = string.gsub(tostring(TempUserdata), "userdata: ", "") local TableHash = 0 local ThreadHash = 0 local FuncHash = 0 local BufferHash = 0 local UserdataHash = 0 for AddrIndex = 1, #TableAddr do TableHash = bit32.bxor(TableHash, string.byte(TableAddr, AddrIndex)) * 31 end if coroutine then local ThreadAddr = string.gsub(tostring(coroutine.create(function() end)), "thread: ", "") for AddrIndex = 1, #ThreadAddr do ThreadHash = bit32.bxor(ThreadHash, string.byte(ThreadAddr, AddrIndex)) * 31 end end for AddrIndex = 1, #FuncAddr do FuncHash = bit32.bxor(FuncHash, string.byte(FuncAddr, AddrIndex)) * 37 end for AddrIndex = 1, #BufferAddr do BufferHash = bit32.bxor(BufferHash, string.byte(BufferAddr, AddrIndex)) * 41 end for AddrIndex = 1, #UserdataAddr do UserdataHash = bit32.bxor(UserdataHash, string.byte(UserdataAddr, AddrIndex)) * 43 end buffer.writeu32(AddressEntropy, Index * 16, TableHash) buffer.writeu32(AddressEntropy, Index * 16 + 4, ThreadHash) buffer.writeu32(AddressEntropy, Index * 16 + 8, FuncHash) buffer.writeu32(AddressEntropy, Index * 16 + 12, bit32.bxor(BufferHash, UserdataHash)) end WriteToBuffer(AddressEntropy) local function AddExtraEntropy(Entropy: buffer?, Warn: boolean, Provider: string?) if not Entropy then return end local BytesLeft = 1024 - Offset if BytesLeft > 0 then local Extra = buffer.len(Entropy) - BytesLeft local Truncated = math.min(BytesLeft, buffer.len(Entropy)) if Extra > 0 and Warn and Provider then warn(`CSPRNG: {Provider} returned {Extra} bytes more than available and was truncated to {Truncated} bytes`) end buffer.copy(EntropyBuffers, Offset, Entropy, 0, Truncated) end end for Index, Provider in CSPRNG.EntropyProviders do local BytesLeft = 1024 - Offset if BytesLeft > 0 then local Success: boolean, ExtraEntropy: buffer? = pcall(Provider, BytesLeft) if not Success then warn(`CSPRNG Provider errored with {ExtraEntropy}`) end AddExtraEntropy(ExtraEntropy, true, `Entropy Provider #{Index}`) end end if CustomEntropy then AddExtraEntropy(CustomEntropy, false) end local KeyMaterial = Blake3(EntropyBuffers, KEY_SIZE + NONCE_SIZE) CSPRNG.Key = buffer.create(KEY_SIZE) buffer.copy(CSPRNG.Key, 0, KeyMaterial, 0, KEY_SIZE) CSPRNG.Nonce = buffer.create(NONCE_SIZE) buffer.copy(CSPRNG.Nonce, 0, KeyMaterial, KEY_SIZE, NONCE_SIZE) return buffer.len(EntropyBuffers) - Offset end local function GenerateBlock() buffer.fill(INPUT_BUFFER, 0, 0, BLOCK_SIZE) local ChaChaOutput = ChaCha20(INPUT_BUFFER, CSPRNG.Key, CSPRNG.Nonce, CSPRNG.Counter, 20) CSPRNG.Buffer = if CSPRNG.BlockExpansion then Blake3(ChaChaOutput, SIZE_TARGET_CLAMPED) else ChaChaOutput CSPRNG.BufferPosition = 0 CSPRNG.BufferSize = buffer.len(CSPRNG.Buffer) CSPRNG.Counter += 1 if CSPRNG.Counter % REKEY_THRESHOLD == 0 then GatherEntropy() CSPRNG.Counter = 0 end end local function GetBytes(Count: number): buffer local Result = buffer.create(Count) local ResultPosition = 0 while ResultPosition < Count do if CSPRNG.BufferPosition >= CSPRNG.BufferSize then GenerateBlock() end local BytesNeeded = Count - ResultPosition local BytesAvailable = CSPRNG.BufferSize - CSPRNG.BufferPosition local BytesToCopy = math.min(BytesNeeded, BytesAvailable) buffer.copy(Result, ResultPosition, CSPRNG.Buffer, CSPRNG.BufferPosition, BytesToCopy) ResultPosition += BytesToCopy CSPRNG.BufferPosition += BytesToCopy end return Result end local function GetFloat(): number if CSPRNG.BufferPosition + 8 > CSPRNG.BufferSize then GenerateBlock() end local Value1 = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition) local Value2 = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition + 4) CSPRNG.BufferPosition += 8 local High = bit32.rshift(Value1, 5) local Low = bit32.rshift(Value2, 6) return (High * 67108864.0 + Low) / 9007199254740992.0 end local function GetIntRange(Min: number, Max: number): number local Range = Max - Min + 1 local MaxUInt32 = 0xFFFFFFFF local Limit = MaxUInt32 - (MaxUInt32 % Range) if CSPRNG.BufferPosition + 4 > CSPRNG.BufferSize then GenerateBlock() end local Value = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition) CSPRNG.BufferPosition += 4 if bit32.band(Range, Range - 1) == 0 then return Min + bit32.band(Value, Range - 1) else while Value > Limit do if CSPRNG.BufferPosition + 4 > CSPRNG.BufferSize then GenerateBlock() end Value = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition) CSPRNG.BufferPosition += 4 end return Min + (Value % Range) end end local function GetNumberRange(Min: number, Max: number): number if Min > Max then Min, Max = Max, Min end local Range = Max - Min if Range <= 0 then return Min end return Min + (GetFloat() * Range) end local function GetRandomString(Length: number, AsBuffer: boolean?): string | buffer local Characters = buffer.create(Length) for Index = 0, Length - 1 do buffer.writeu8(Characters, Index, GetIntRange(36, 122)) end return if AsBuffer then Characters else buffer.tostring(Characters) end local function GetEd25519RandomBytes(): buffer local Output = buffer.create(32) for Index = 0, 31 do buffer.writeu8(Output, Index, GetIntRange(0, 255)) end return Output end local function GetEd25519ClampedBytes(Input: buffer): buffer local Output = buffer.create(32) buffer.copy(Output, 0, Input, 0, 32) local FirstByte = buffer.readu8(Output, 0) FirstByte = bit32.band(FirstByte, 0xF8) buffer.writeu8(Output, 0, FirstByte) local LastByte = buffer.readu8(Output, 31) LastByte = bit32.band(LastByte, 0x7F) LastByte = bit32.bor(LastByte, 0x40) buffer.writeu8(Output, 31, LastByte) local HasVariation = false local FirstMiddleByte = buffer.readu8(Output, 1) for Index = 2, 30 do if buffer.readu8(Output, Index) ~= FirstMiddleByte then HasVariation = true break end end if not HasVariation then buffer.writeu8(Output, 15, bit32.bxor(FirstMiddleByte, 0x55)) end return Output end local function GetHexString(Length: number): string local BytesNeeded = Length / 2 local Bytes = GetBytes(BytesNeeded) local Hex = Conversions.ToHex(Bytes) return Hex end function CSPRNG.AddEntropyProvider(ProviderFunction: EntropyProvider) table.insert(CSPRNG.EntropyProviders, ProviderFunction) end function CSPRNG.RemoveEntropyProvider(ProviderFunction: EntropyProvider) for Index = #CSPRNG.EntropyProviders, 1, -1 do if CSPRNG.EntropyProviders[Index] == ProviderFunction then table.remove(CSPRNG.EntropyProviders, Index) break end end end function CSPRNG.Random(): number return GetFloat() end function CSPRNG.RandomInt(Min: number, Max: number?): number if Max and type(Max) ~= "number" then error(`Max must be a number or nil, got {typeof(Max)}`, 2) end if type(Min) ~= "number" then error(`Min must be a number, got {typeof(Min)}`, 2) end if Max and Max < Min then error(`Max ({Max}) can't be less than Min ({Min})`, 2) end if Max and Max == Min then error(`Max ({Max}) can't be equal to Min ({Min})`, 2) end local ActualMax: number local ActualMin: number if Max == nil then ActualMax = Min ActualMin = 1 else ActualMax = Max ActualMin = Min end return GetIntRange(ActualMin, ActualMax) end function CSPRNG.RandomNumber(Min: number, Max: number?): number if Max and type(Max) ~= "number" then error(`Max must be a number or nil, got {typeof(Max)}`, 2) end if type(Min) ~= "number" then error(`Min must be a number, got {typeof(Min)}`, 2) end if Max and Max < Min then error(`Max ({Max}) must be bigger than Min ({Min})`, 2) end if Max and Max == Min then error(`Max ({Max}) can't be equal to Min ({Min})`, 2) end local ActualMax: number local ActualMin: number if Max == nil then ActualMax = Min ActualMin = 0 else ActualMax = Max ActualMin = Min end return GetNumberRange(ActualMin, ActualMax) end function CSPRNG.RandomBytes(Count: number): buffer if type(Count) ~= "number" then error(`Count must be a number, got {typeof(Count)}`, 2) end if Count <= 0 then error(`Count must be bigger than 0, got {Count}`, 2) end if Count % 1 ~= 0 then error("Count must be an integer", 2) end return GetBytes(Count) end function CSPRNG.RandomString(Length: number, AsBuffer: boolean?): string | buffer if type(Length) ~= "number" then error(`Length must be a number, got {typeof(Length)}`, 2) end if Length <= 0 then error(`Length must be bigger than 0, got {Length}`, 2) end if Length % 1 ~= 0 then error("Length must be an integer", 2) end if AsBuffer ~= nil and type(AsBuffer) ~= "boolean" then error(`AsBuffer must be a boolean or nil, got {typeof(AsBuffer)}`, 2) end return GetRandomString(Length, AsBuffer) end function CSPRNG.RandomHex(Length: number): string if type(Length) ~= "number" then error(`Length must be a number, got {typeof(Length)}`, 2) end if Length <= 0 then error(`Length must be bigger than 0, got {Length}`, 2) end if Length % 1 ~= 0 then error("Length must be an integer", 2) end if Length % 2 ~= 0 then error(`Length must be even, got {Length}`, 2) end return GetHexString(Length) end function CSPRNG.Ed25519ClampedBytes(Input: buffer): buffer if type(Input) ~= "buffer" then error(`Input must be a buffer, got {typeof(Input)}`, 2) end return GetEd25519ClampedBytes(Input) end function CSPRNG.Ed25519Random(): buffer return GetEd25519ClampedBytes(GetEd25519RandomBytes()) end function CSPRNG.Reseed(CustomEntropy: buffer?) if CustomEntropy ~= nil and type(CustomEntropy) ~= "buffer" then error(`CustomEntropy must be a buffer or nil, got {typeof(CustomEntropy)}`, 2) end Reset() GatherEntropy(CustomEntropy) end CSPRNG.BytesLeft = GatherEntropy() GenerateBlock() return CSPRNG
5,064
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/Curve25519.luau
--[=[ Cryptography library: Curve25519 Montgomery Return type: varies by function Example usage: local Curve25519 = require("Curve25519") local FieldQuadratic = require("FieldQuadratic") --------Usage Case 1: Point multiplication-------- local BasePoint = Curve25519.G local SomeScalar = FieldQuadratic.Decode(ScalarBytes) local ScalarBits, BitCount = FieldQuadratic.Bits(SomeScalar) local Result = Curve25519.Ladder8(BasePoint, ScalarBits, BitCount) --------Usage Case 2: Encode/decode points-------- local EncodedPoint = Curve25519.Encode(Curve25519.Scale(Result)) local DecodedPoint = Curve25519.Decode(EncodedPoint) --]=] --!strict --!optimize 2 --!native local FieldPrime = require("./FieldPrime") local CSPRNG = require("./CSPRNG") local MONTGOMERY_POINT_SIZE = 208 local COORD_SIZE = 104 local function GetMontgomeryCoord(Point: buffer, Index: number): buffer local Coord = buffer.create(COORD_SIZE) buffer.copy(Coord, 0, Point, Index * COORD_SIZE, COORD_SIZE) return Coord end local function Double(PointToDouble: buffer): buffer local CoordX = GetMontgomeryCoord(PointToDouble, 0) local CoordZ = GetMontgomeryCoord(PointToDouble, 1) local SumXZ = FieldPrime.Add(CoordX, CoordZ) local SumSquared = FieldPrime.Square(SumXZ) local DiffXZ = FieldPrime.Sub(CoordX, CoordZ) local DiffSquared = FieldPrime.Square(DiffXZ) local Difference = FieldPrime.Sub(SumSquared, DiffSquared) local NewX = FieldPrime.Mul(SumSquared, DiffSquared) local NewZ = FieldPrime.Mul(Difference, FieldPrime.Add(DiffSquared, FieldPrime.KMul(Difference, 121666))) local Point = buffer.create(MONTGOMERY_POINT_SIZE) buffer.copy(Point, 0 * COORD_SIZE, NewX, 0, COORD_SIZE) buffer.copy(Point, 1 * COORD_SIZE, NewZ, 0, COORD_SIZE) return Point end local function LadderStep(DifferencePoint: buffer, Point1: buffer, Point2: buffer): (buffer, buffer) local DiffX = GetMontgomeryCoord(DifferencePoint, 0) local DiffZ = GetMontgomeryCoord(DifferencePoint, 1) local X1 = GetMontgomeryCoord(Point1, 0) local Z1 = GetMontgomeryCoord(Point1, 1) local X2 = GetMontgomeryCoord(Point2, 0) local Z2 = GetMontgomeryCoord(Point2, 1) local SumA = FieldPrime.Add(X1, Z1) local SumSquaredAA = FieldPrime.Square(SumA) local DiffB = FieldPrime.Sub(X1, Z1) local DiffSquaredBB = FieldPrime.Square(DiffB) local DifferenceE = FieldPrime.Sub(SumSquaredAA, DiffSquaredBB) local DiffD = FieldPrime.Sub(X2, Z2) local CrossDA = FieldPrime.Mul(DiffD, SumA) local SumC = FieldPrime.Add(X2, Z2) local CrossCB = FieldPrime.Mul(SumC, DiffB) local NewX4 = FieldPrime.Mul(DiffZ, FieldPrime.Square(FieldPrime.Add(CrossDA, CrossCB))) local NewZ4 = FieldPrime.Mul(DiffX, FieldPrime.Square(FieldPrime.Sub(CrossDA, CrossCB))) local NewX3 = FieldPrime.Mul(SumSquaredAA, DiffSquaredBB) local NewZ3 = FieldPrime.Mul(DifferenceE, FieldPrime.Add(DiffSquaredBB, FieldPrime.KMul(DifferenceE, 121666))) local Point = buffer.create(MONTGOMERY_POINT_SIZE) buffer.copy(Point, 0 * COORD_SIZE, NewX3, 0, COORD_SIZE) buffer.copy(Point, 1 * COORD_SIZE, NewZ3, 0, COORD_SIZE) local SecondPoint = buffer.create(MONTGOMERY_POINT_SIZE) buffer.copy(SecondPoint, 0 * COORD_SIZE, NewX4, 0, COORD_SIZE) buffer.copy(SecondPoint, 1 * COORD_SIZE, NewZ4, 0, COORD_SIZE) return Point, SecondPoint end local function Ladder(DifferencePoint: buffer, ScalarBits: buffer, ScalarBitCount: number): buffer local CurrentP = buffer.create(MONTGOMERY_POINT_SIZE) buffer.copy(CurrentP, 0 * COORD_SIZE, FieldPrime.Num(1), 0, COORD_SIZE) buffer.copy(CurrentP, 1 * COORD_SIZE, FieldPrime.Num(0), 0, COORD_SIZE) local CurrentQ = buffer.create(MONTGOMERY_POINT_SIZE) buffer.copy(CurrentQ, 0, DifferencePoint, 0, MONTGOMERY_POINT_SIZE) local LadderStep = LadderStep for BitIndex = ScalarBitCount, 1, -1 do local BitValue = buffer.readf64(ScalarBits, (BitIndex - 1) * 8) if BitValue == 0 then CurrentP, CurrentQ = LadderStep(DifferencePoint, CurrentP, CurrentQ) else CurrentQ, CurrentP = LadderStep(DifferencePoint, CurrentQ, CurrentP) end end return CurrentP end local Curve25519 = {} function Curve25519.DifferentialAdd(DifferencePoint: buffer, Point1: buffer, Point2: buffer): buffer local DiffX = GetMontgomeryCoord(DifferencePoint, 0) local DiffZ = GetMontgomeryCoord(DifferencePoint, 1) local X1 = GetMontgomeryCoord(Point1, 0) local Z1 = GetMontgomeryCoord(Point1, 1) local X2 = GetMontgomeryCoord(Point2, 0) local Z2 = GetMontgomeryCoord(Point2, 1) local SumA = FieldPrime.Add(X1, Z1) local DiffB = FieldPrime.Sub(X1, Z1) local SumC = FieldPrime.Add(X2, Z2) local DiffD = FieldPrime.Sub(X2, Z2) local CrossDA = FieldPrime.Mul(DiffD, SumA) local CrossCB = FieldPrime.Mul(SumC, DiffB) local NewX = FieldPrime.Mul(DiffZ, FieldPrime.Square(FieldPrime.Add(CrossDA, CrossCB))) local NewZ = FieldPrime.Mul(DiffX, FieldPrime.Square(FieldPrime.Sub(CrossDA, CrossCB))) local Point = buffer.create(MONTGOMERY_POINT_SIZE) buffer.copy(Point, 0 * COORD_SIZE, NewX, 0, COORD_SIZE) buffer.copy(Point, 1 * COORD_SIZE, NewZ, 0, COORD_SIZE) return Point end function Curve25519.Decode(EncodedBuffer: buffer): buffer local Point = buffer.create(MONTGOMERY_POINT_SIZE) buffer.copy(Point, 0 * COORD_SIZE, FieldPrime.Decode(EncodedBuffer), 0, COORD_SIZE) buffer.copy(Point, 1 * COORD_SIZE, FieldPrime.Num(1), 0, COORD_SIZE) return Point end function Curve25519.Prac(BasePoint: buffer, PracRuleset: {any}): (buffer?, buffer?, buffer?) local DifferentialAdd = Curve25519.DifferentialAdd local RandomBuffer = CSPRNG.Ed25519Random() local RandomFactor = FieldPrime.Decode(RandomBuffer) local BaseX = GetMontgomeryCoord(BasePoint, 0) local BaseZ = GetMontgomeryCoord(BasePoint, 1) local RandomizedA = buffer.create(MONTGOMERY_POINT_SIZE) buffer.copy(RandomizedA, 0 * COORD_SIZE, FieldPrime.Mul(BaseX, RandomFactor), 0, COORD_SIZE) buffer.copy(RandomizedA, 1 * COORD_SIZE, FieldPrime.Mul(BaseZ, RandomFactor), 0, COORD_SIZE) RandomizedA = Double(Double(Double(RandomizedA))) local AZ = GetMontgomeryCoord(RandomizedA, 1) if FieldPrime.Eqz(AZ) then return nil, nil, nil end RandomizedA = Ladder(RandomizedA, PracRuleset[1], PracRuleset[2]) local Rules: buffer = PracRuleset[3] local RuleCount: number = PracRuleset[4] if RuleCount == 0 then return RandomizedA, nil, nil end local CurrentB, CurrentC local FirstRule = buffer.readf64(Rules, (RuleCount - 1) * 8) if FirstRule == 2 then local DoubledA = Double(RandomizedA) RandomizedA, CurrentB, CurrentC = DifferentialAdd(RandomizedA, DoubledA, RandomizedA), RandomizedA, DoubledA elseif FirstRule == 3 or FirstRule == 5 then RandomizedA, CurrentB, CurrentC = Double(RandomizedA), RandomizedA, RandomizedA elseif FirstRule == 6 then local DoubledA = Double(RandomizedA) local TripledA = DifferentialAdd(RandomizedA, DoubledA, RandomizedA) RandomizedA, CurrentB, CurrentC = Double(TripledA), RandomizedA, DifferentialAdd(RandomizedA, TripledA, DoubledA) elseif FirstRule == 7 then local DoubledA = Double(RandomizedA) local TripledA = DifferentialAdd(RandomizedA, DoubledA, RandomizedA) local QuadrupleA = Double(DoubledA) RandomizedA, CurrentB, CurrentC = DifferentialAdd(TripledA, QuadrupleA, RandomizedA), RandomizedA, QuadrupleA elseif FirstRule == 8 then local DoubledA = Double(RandomizedA) local TripledA = DifferentialAdd(RandomizedA, DoubledA, RandomizedA) RandomizedA, CurrentB, CurrentC = Double(DoubledA), RandomizedA, TripledA else RandomizedA, CurrentB, CurrentC = RandomizedA, Double(RandomizedA), RandomizedA end if not CurrentC then return nil, nil, nil end for RuleIndex = RuleCount - 1, 1, -1 do local CurrentRule = buffer.readf64(Rules, (RuleIndex - 1) * 8) if CurrentRule == 0 then RandomizedA, CurrentB = CurrentB, RandomizedA elseif CurrentRule == 1 then local SumAB = DifferentialAdd(CurrentC, RandomizedA, CurrentB) RandomizedA, CurrentB = DifferentialAdd(CurrentB, SumAB, RandomizedA), DifferentialAdd(RandomizedA, SumAB, CurrentB) elseif CurrentRule == 2 then RandomizedA, CurrentC = DifferentialAdd(CurrentB, DifferentialAdd(CurrentC, RandomizedA, CurrentB), RandomizedA), Double(RandomizedA) elseif CurrentRule == 3 then RandomizedA, CurrentC = DifferentialAdd(CurrentC, RandomizedA, CurrentB), RandomizedA elseif CurrentRule == 5 then RandomizedA, CurrentC = Double(RandomizedA), DifferentialAdd(CurrentB, RandomizedA, CurrentC) elseif CurrentRule == 6 then local SumAB = DifferentialAdd(CurrentC, RandomizedA, CurrentB) local DoubledSumAABB = Double(SumAB) RandomizedA, CurrentC = DifferentialAdd(SumAB, DoubledSumAABB, SumAB), DifferentialAdd(DifferentialAdd(RandomizedA, SumAB, CurrentB), DoubledSumAABB, RandomizedA) elseif CurrentRule == 7 then local SumAB = DifferentialAdd(CurrentC, RandomizedA, CurrentB) local DoubleAAB = DifferentialAdd(CurrentB, SumAB, RandomizedA) RandomizedA, CurrentC = DifferentialAdd(RandomizedA, DoubleAAB, SumAB), DifferentialAdd(SumAB, DoubleAAB, RandomizedA) elseif CurrentRule == 8 then local DoubledA = Double(RandomizedA) RandomizedA, CurrentC = DifferentialAdd(CurrentC, DoubledA, DifferentialAdd(CurrentC, RandomizedA, CurrentB)), DifferentialAdd(RandomizedA, DoubledA, RandomizedA) else CurrentB, CurrentC = Double(CurrentB), DifferentialAdd(RandomizedA, CurrentC, CurrentB) end end return RandomizedA, CurrentB, CurrentC end local Point = buffer.create(MONTGOMERY_POINT_SIZE) buffer.copy(Point, 0 * COORD_SIZE, FieldPrime.Num(9), 0, COORD_SIZE) buffer.copy(Point, 1 * COORD_SIZE, FieldPrime.Num(1), 0, COORD_SIZE) Curve25519.G = Point return Curve25519
2,818
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/Edwards25519.luau
--[=[ Cryptography library: Edwards25519 Return type: varies by function Example usage: local Edwards = require("Edwards25519") local FieldQuadratic = require("FieldQuadratic") --------Usage Case 1: Point addition-------- local Point1 = Edwards.Decode(SomeEncodedBuffer) local Point2 = Edwards.Decode(AnotherEncodedBuffer) local NielsPoint2 = Edwards.Niels(Point2) local Sum = Edwards.Add(Point1, NielsPoint2) --------Usage Case 2: Scalar multiplication with buffer-based bits-------- local SomeScalar = FieldQuadratic.Decode(ScalarBytes) local ScalarBits, BitCount = FieldQuadratic.Bits(SomeScalar) local Result = Edwards.MulG(ScalarBits, BitCount) local EncodedResult = Edwards.Encode(Result) --]=] --!strict --!optimize 2 --!native local FieldPrime = require("./FieldPrime") local POINT_SIZE = 416 local COORD_SIZE = 104 local AFFINE_NIELS_SIZE = 312 local BASE_RADIX_WIDTH = 6 local BASE_POINT_ROW = 2 ^ BASE_RADIX_WIDTH / 2 local CURVE_D = FieldPrime.Mul(FieldPrime.Num(-121665), FieldPrime.Invert(FieldPrime.Num(121666))) local CURVE_K = FieldPrime.KMul(CURVE_D, 2) local IDENTITY_O = buffer.create(POINT_SIZE) do buffer.copy(IDENTITY_O, 0, FieldPrime.Num(0), 0, COORD_SIZE) buffer.copy(IDENTITY_O, COORD_SIZE, FieldPrime.Num(1), 0, COORD_SIZE) buffer.copy(IDENTITY_O, 2 * COORD_SIZE, FieldPrime.Num(1), 0, COORD_SIZE) buffer.copy(IDENTITY_O, 3 * COORD_SIZE, FieldPrime.Num(0), 0, COORD_SIZE) end local COORD_BUFFER_0 = buffer.create(COORD_SIZE) local COORD_BUFFER_1 = buffer.create(COORD_SIZE) local COORD_BUFFER_2 = buffer.create(COORD_SIZE) local COORD_BUFFER_3 = buffer.create(COORD_SIZE) local COORD_BUFFER_4 = buffer.create(COORD_SIZE) local COORD_BUFFER_5 = buffer.create(COORD_SIZE) local COORD_BUFFER_6 = buffer.create(COORD_SIZE) local COORD_BUFFER_7 = buffer.create(COORD_SIZE) local MUL_RESULT_POINT = buffer.create(POINT_SIZE) local MUL_NIELS_POINT = buffer.create(POINT_SIZE) local MUL_DOUBLE_X = buffer.create(COORD_SIZE) local MUL_DOUBLE_Y = buffer.create(COORD_SIZE) local MUL_DOUBLE_Z = buffer.create(COORD_SIZE) local MUL_DOUBLE_A = buffer.create(COORD_SIZE) local MUL_DOUBLE_B = buffer.create(COORD_SIZE) local MUL_DOUBLE_E = buffer.create(COORD_SIZE) local MUL_DOUBLE_G = buffer.create(COORD_SIZE) local MUL_P1X = buffer.create(COORD_SIZE) local MUL_P1Y = buffer.create(COORD_SIZE) local MUL_P1Z = buffer.create(COORD_SIZE) local MUL_P1T = buffer.create(COORD_SIZE) local MUL_N2P = buffer.create(COORD_SIZE) local MUL_N2M = buffer.create(COORD_SIZE) local MUL_N2Z = buffer.create(COORD_SIZE) local MUL_N2T = buffer.create(COORD_SIZE) local MUL_TMP = buffer.create(COORD_SIZE) local MULG_RESULT_POINT = buffer.create(POINT_SIZE) local MULG_AFFINE_NIELS = buffer.create(AFFINE_NIELS_SIZE) local MULG_DUMMY_POINT = buffer.create(POINT_SIZE) local MULG_P1X = buffer.create(COORD_SIZE) local MULG_P1Y = buffer.create(COORD_SIZE) local MULG_P1Z = buffer.create(COORD_SIZE) local MULG_P1T = buffer.create(COORD_SIZE) local MULG_N2P = buffer.create(COORD_SIZE) local MULG_N2M = buffer.create(COORD_SIZE) local MULG_N2T = buffer.create(COORD_SIZE) local MULG_TMP = buffer.create(COORD_SIZE) local NAF_TABLE_DOUBLED = buffer.create(POINT_SIZE) local NAF_TABLE_P1X = buffer.create(COORD_SIZE) local NAF_TABLE_P1Y = buffer.create(COORD_SIZE) local NAF_TABLE_P1Z = buffer.create(COORD_SIZE) local NAF_TABLE_P1T = buffer.create(COORD_SIZE) local NAF_TABLE_N2P = buffer.create(COORD_SIZE) local NAF_TABLE_N2M = buffer.create(COORD_SIZE) local NAF_TABLE_N2Z = buffer.create(COORD_SIZE) local NAF_TABLE_N2T = buffer.create(COORD_SIZE) local NAF_TABLE_TMP = buffer.create(COORD_SIZE) local NAF_TABLE_DBL_P = buffer.create(COORD_SIZE) local NAF_TABLE_DBL_M = buffer.create(COORD_SIZE) local NAF_TABLE_DBL_Z = buffer.create(COORD_SIZE) local NAF_TABLE_DBL_T = buffer.create(COORD_SIZE) local NAF_OUTPUT = buffer.create(512 * 8) local RADIX_OUTPUT = buffer.create(272 * 8) local BASEPONT_G: buffer? = nil local AFFINE_BASEPOINT_TABLE: buffer? = nil local function GetCoord(Point: buffer, Index: number, Storage: buffer?): buffer local Coord = Storage or buffer.create(COORD_SIZE) buffer.copy(Coord, 0, Point, Index * COORD_SIZE, COORD_SIZE) return Coord end local Edwards25519 = {} function Edwards25519.Double(Point1: buffer, Storage: buffer?): buffer local Point1X = GetCoord(Point1, 0, COORD_BUFFER_0) local Point1Y = GetCoord(Point1, 1, COORD_BUFFER_1) local Point1Z = GetCoord(Point1, 2, COORD_BUFFER_2) local SquaredA = FieldPrime.Square(Point1X) local SquaredB = FieldPrime.Square(Point1Y) FieldPrime.Square(Point1Z, Point1Z) FieldPrime.Add(Point1Z, Point1Z, Point1Z) local DoubledD = Point1Z local SumE = FieldPrime.Add(SquaredA, SquaredB) FieldPrime.Add(Point1X, Point1Y, Point1X) local SumF = Point1X local SquaredG = FieldPrime.Square(SumF) FieldPrime.Sub(SquaredG, SumE, SquaredG) FieldPrime.Carry(SquaredG, SquaredG) local DiffH = SquaredG FieldPrime.Sub(SquaredB, SquaredA, SquaredB) local DiffI = SquaredB FieldPrime.Sub(DoubledD, DiffI, DoubledD) FieldPrime.Carry(DoubledD, DoubledD) local DiffJ = DoubledD local NewX = FieldPrime.Mul(DiffH, DiffJ) local NewY = FieldPrime.Mul(DiffI, SumE) FieldPrime.Mul(DiffJ, DiffI, DiffJ) local NewZ = DiffJ FieldPrime.Mul(DiffH, SumE, DiffH) local NewT = DiffH local Result = Storage or buffer.create(POINT_SIZE) buffer.copy(Result, 0 * COORD_SIZE, NewX, 0, COORD_SIZE) buffer.copy(Result, 1 * COORD_SIZE, NewY, 0, COORD_SIZE) buffer.copy(Result, 2 * COORD_SIZE, NewZ, 0, COORD_SIZE) buffer.copy(Result, 3 * COORD_SIZE, NewT, 0, COORD_SIZE) return Result end function Edwards25519.Add(Point1: buffer, NielsPoint2: buffer, Storage: buffer?): buffer local Point1X = GetCoord(Point1, 0, COORD_BUFFER_0) local Point1Y = GetCoord(Point1, 1, COORD_BUFFER_1) local Point1Z = GetCoord(Point1, 2, COORD_BUFFER_2) local Point1T = GetCoord(Point1, 3, COORD_BUFFER_3) local Niels1Plus = GetCoord(NielsPoint2, 0, COORD_BUFFER_4) local Niels1Minus = GetCoord(NielsPoint2, 1, COORD_BUFFER_5) local Niels1Z = GetCoord(NielsPoint2, 2, COORD_BUFFER_6) local Niels1T = GetCoord(NielsPoint2, 3, COORD_BUFFER_7) local DiffA = FieldPrime.Sub(Point1Y, Point1X) FieldPrime.Mul(DiffA, Niels1Minus, DiffA) local ProductB = DiffA local SumC = FieldPrime.Add(Point1Y, Point1X) FieldPrime.Mul(SumC, Niels1Plus, SumC) local ProductD = SumC FieldPrime.Mul(Point1T, Niels1T, Point1T) local ProductE = Point1T FieldPrime.Mul(Point1Z, Niels1Z, Point1Z) local ProductF = Point1Z local DiffG = FieldPrime.Sub(ProductD, ProductB) local DiffH = FieldPrime.Sub(ProductF, ProductE) FieldPrime.Add(ProductF, ProductE, ProductF) local SumI = ProductF FieldPrime.Add(ProductD, ProductB, ProductD) local SumJ = ProductD local NewX = FieldPrime.Mul(DiffG, DiffH) local NewY = FieldPrime.Mul(SumI, SumJ) FieldPrime.Mul(DiffH, SumI, DiffH) local NewZ = DiffH FieldPrime.Mul(DiffG, SumJ, DiffG) local NewT = DiffG local Result = Storage or buffer.create(POINT_SIZE) buffer.copy(Result, 0 * COORD_SIZE, NewX, 0, COORD_SIZE) buffer.copy(Result, 1 * COORD_SIZE, NewY, 0, COORD_SIZE) buffer.copy(Result, 2 * COORD_SIZE, NewZ, 0, COORD_SIZE) buffer.copy(Result, 3 * COORD_SIZE, NewT, 0, COORD_SIZE) return Result end function Edwards25519.Sub(Point1: buffer, NielsPoint2: buffer, Storage: buffer?): buffer local Point1X = GetCoord(Point1, 0, COORD_BUFFER_0) local Point1Y = GetCoord(Point1, 1, COORD_BUFFER_1) local Point1Z = GetCoord(Point1, 2, COORD_BUFFER_2) local Point1T = GetCoord(Point1, 3, COORD_BUFFER_3) local Niels1Plus = GetCoord(NielsPoint2, 0, COORD_BUFFER_4) local Niels1Minus = GetCoord(NielsPoint2, 1, COORD_BUFFER_5) local Niels1Z = GetCoord(NielsPoint2, 2, COORD_BUFFER_6) local Niels1T = GetCoord(NielsPoint2, 3, COORD_BUFFER_7) local DiffA = FieldPrime.Sub(Point1Y, Point1X) FieldPrime.Mul(DiffA, Niels1Plus, DiffA) local ProductB = DiffA FieldPrime.Add(Point1Y, Point1X, Point1Y) local SumC = Point1Y FieldPrime.Mul(SumC, Niels1Minus, SumC) local ProductD = SumC FieldPrime.Mul(Point1T, Niels1T, Point1T) local ProductE = Point1T FieldPrime.Mul(Point1Z, Niels1Z, Point1Z) local ProductF = Point1Z local DiffG = FieldPrime.Sub(ProductD, ProductB) local SumH = FieldPrime.Add(ProductF, ProductE) local DiffI = FieldPrime.Sub(ProductF, ProductE) FieldPrime.Add(ProductD, ProductB, ProductD) local SumJ = ProductD local NewX = FieldPrime.Mul(DiffG, SumH) local NewY = FieldPrime.Mul(DiffI, SumJ) FieldPrime.Mul(SumH, DiffI, SumH) local NewZ = SumH FieldPrime.Mul(DiffG, SumJ, DiffG) local NewT = DiffG local Result = Storage or buffer.create(POINT_SIZE) buffer.copy(Result, 0 * COORD_SIZE, NewX, 0, COORD_SIZE) buffer.copy(Result, 1 * COORD_SIZE, NewY, 0, COORD_SIZE) buffer.copy(Result, 2 * COORD_SIZE, NewZ, 0, COORD_SIZE) buffer.copy(Result, 3 * COORD_SIZE, NewT, 0, COORD_SIZE) return Result end function Edwards25519.Niels(Point1: buffer, Storage: buffer?): buffer local Point1X = GetCoord(Point1, 0, COORD_BUFFER_0) local Point1Y = GetCoord(Point1, 1, COORD_BUFFER_1) local Point1Z = GetCoord(Point1, 2, COORD_BUFFER_2) local Point1T = GetCoord(Point1, 3, COORD_BUFFER_3) local PlusN3 = FieldPrime.Add(Point1Y, Point1X) local MinusN3 = FieldPrime.Sub(Point1Y, Point1X) FieldPrime.Add(Point1Z, Point1Z, Point1Z) local DoubledN3Z = Point1Z FieldPrime.Mul(Point1T, CURVE_K, Point1T) local ScaledN3T = Point1T local Result = Storage or buffer.create(POINT_SIZE) buffer.copy(Result, 0 * COORD_SIZE, PlusN3, 0, COORD_SIZE) buffer.copy(Result, 1 * COORD_SIZE, MinusN3, 0, COORD_SIZE) buffer.copy(Result, 2 * COORD_SIZE, DoubledN3Z, 0, COORD_SIZE) buffer.copy(Result, 3 * COORD_SIZE, ScaledN3T, 0, COORD_SIZE) return Result end function Edwards25519.AffineNiels(Point1: buffer, Storage: buffer?): buffer local Point1X = GetCoord(Point1, 0, COORD_BUFFER_0) local Point1Y = GetCoord(Point1, 1, COORD_BUFFER_1) local Point1T = GetCoord(Point1, 3, COORD_BUFFER_3) local YPlusX = FieldPrime.Add(Point1Y, Point1X) local YMinusX = FieldPrime.Sub(Point1Y, Point1X) FieldPrime.Mul(Point1T, CURVE_K, Point1T) local T2d = Point1T local Result = Storage or buffer.create(AFFINE_NIELS_SIZE) buffer.copy(Result, 0 * COORD_SIZE, YPlusX, 0, COORD_SIZE) buffer.copy(Result, 1 * COORD_SIZE, YMinusX, 0, COORD_SIZE) buffer.copy(Result, 2 * COORD_SIZE, T2d, 0, COORD_SIZE) return Result end function Edwards25519.AddAffine(Point1: buffer, AffineNiels2: buffer, Storage: buffer?): buffer local Point1X = GetCoord(Point1, 0, COORD_BUFFER_0) local Point1Y = GetCoord(Point1, 1, COORD_BUFFER_1) local Point1Z = GetCoord(Point1, 2, COORD_BUFFER_2) local Point1T = GetCoord(Point1, 3, COORD_BUFFER_3) local Niels2YPlusX = GetCoord(AffineNiels2, 0, COORD_BUFFER_4) local Niels2YMinusX = GetCoord(AffineNiels2, 1, COORD_BUFFER_5) local Niels2T2d = GetCoord(AffineNiels2, 2, COORD_BUFFER_6) local DiffA = FieldPrime.Sub(Point1Y, Point1X) FieldPrime.Mul(DiffA, Niels2YMinusX, DiffA) local ProductB = DiffA local SumC = FieldPrime.Add(Point1Y, Point1X) FieldPrime.Mul(SumC, Niels2YPlusX, SumC) local ProductD = SumC FieldPrime.Mul(Point1T, Niels2T2d, Point1T) local ProductE = Point1T FieldPrime.Add(Point1Z, Point1Z, Point1Z) local ProductF = Point1Z local DiffG = FieldPrime.Sub(ProductD, ProductB) local DiffH = FieldPrime.Sub(ProductF, ProductE) FieldPrime.Add(ProductF, ProductE, ProductF) local SumI = ProductF FieldPrime.Add(ProductD, ProductB, ProductD) local SumJ = ProductD local NewX = FieldPrime.Mul(DiffG, DiffH) local NewY = FieldPrime.Mul(SumI, SumJ) FieldPrime.Mul(DiffH, SumI, DiffH) local NewZ = DiffH FieldPrime.Mul(DiffG, SumJ, DiffG) local NewT = DiffG local Result = Storage or buffer.create(POINT_SIZE) buffer.copy(Result, 0 * COORD_SIZE, NewX, 0, COORD_SIZE) buffer.copy(Result, 1 * COORD_SIZE, NewY, 0, COORD_SIZE) buffer.copy(Result, 2 * COORD_SIZE, NewZ, 0, COORD_SIZE) buffer.copy(Result, 3 * COORD_SIZE, NewT, 0, COORD_SIZE) return Result end function Edwards25519.SubAffine(Point1: buffer, AffineNiels2: buffer, Storage: buffer?): buffer local Point1X = GetCoord(Point1, 0, COORD_BUFFER_0) local Point1Y = GetCoord(Point1, 1, COORD_BUFFER_1) local Point1Z = GetCoord(Point1, 2, COORD_BUFFER_2) local Point1T = GetCoord(Point1, 3, COORD_BUFFER_3) local Niels2YPlusX = GetCoord(AffineNiels2, 0, COORD_BUFFER_4) local Niels2YMinusX = GetCoord(AffineNiels2, 1, COORD_BUFFER_5) local Niels2T2d = GetCoord(AffineNiels2, 2, COORD_BUFFER_6) local DiffA = FieldPrime.Sub(Point1Y, Point1X) FieldPrime.Mul(DiffA, Niels2YPlusX, DiffA) local ProductB = DiffA FieldPrime.Add(Point1Y, Point1X, Point1Y) local SumC = Point1Y FieldPrime.Mul(SumC, Niels2YMinusX, SumC) local ProductD = SumC FieldPrime.Mul(Point1T, Niels2T2d, Point1T) local ProductE = Point1T FieldPrime.Add(Point1Z, Point1Z, Point1Z) local ProductF = Point1Z local DiffG = FieldPrime.Sub(ProductD, ProductB) local SumH = FieldPrime.Add(ProductF, ProductE) local DiffI = FieldPrime.Sub(ProductF, ProductE) FieldPrime.Add(ProductD, ProductB, ProductD) local SumJ = ProductD local NewX = FieldPrime.Mul(DiffG, SumH) local NewY = FieldPrime.Mul(DiffI, SumJ) FieldPrime.Mul(SumH, DiffI, SumH) local NewZ = SumH FieldPrime.Mul(DiffG, SumJ, DiffG) local NewT = DiffG local Result = Storage or buffer.create(POINT_SIZE) buffer.copy(Result, 0 * COORD_SIZE, NewX, 0, COORD_SIZE) buffer.copy(Result, 1 * COORD_SIZE, NewY, 0, COORD_SIZE) buffer.copy(Result, 2 * COORD_SIZE, NewZ, 0, COORD_SIZE) buffer.copy(Result, 3 * COORD_SIZE, NewT, 0, COORD_SIZE) return Result end function Edwards25519.Scale(Point1: buffer): buffer local Point1X = GetCoord(Point1, 0, COORD_BUFFER_0) local Point1Y = GetCoord(Point1, 1, COORD_BUFFER_1) local Point1Z = GetCoord(Point1, 2, COORD_BUFFER_2) FieldPrime.Invert(Point1Z, Point1Z) local ZInverse = Point1Z FieldPrime.Mul(Point1X, ZInverse, Point1X) local NewX = Point1X FieldPrime.Mul(Point1Y, ZInverse, Point1Y) local NewY = Point1Y local NewZ = FieldPrime.Num(1) local NewT = FieldPrime.Mul(NewX, NewY) local Result = buffer.create(POINT_SIZE) buffer.copy(Result, 0 * COORD_SIZE, NewX, 0, COORD_SIZE) buffer.copy(Result, 1 * COORD_SIZE, NewY, 0, COORD_SIZE) buffer.copy(Result, 2 * COORD_SIZE, NewZ, 0, COORD_SIZE) buffer.copy(Result, 3 * COORD_SIZE, NewT, 0, COORD_SIZE) return Result end function Edwards25519.Encode(Point1: buffer): buffer local ScaledPoint = Edwards25519.Scale(Point1) local Point1X = GetCoord(ScaledPoint, 0, COORD_BUFFER_0) local Point1Y = GetCoord(ScaledPoint, 1, COORD_BUFFER_1) local EncodedY = FieldPrime.Encode(Point1Y) local CanonicalX = FieldPrime.Canonicalize(Point1X) local XSignBit = buffer.readf64(CanonicalX, 0) % 2 local ResultBuffer = buffer.create(32) buffer.copy(ResultBuffer, 0, EncodedY, 0, 32) local LastByte = buffer.readu8(ResultBuffer, 31) buffer.writeu8(ResultBuffer, 31, LastByte + XSignBit * 128) return ResultBuffer end function Edwards25519.Decode(EncodedBuffer: buffer): buffer? local WorkingBuffer = buffer.create(32) buffer.copy(WorkingBuffer, 0, EncodedBuffer, 0, 32) local LastByte = buffer.readu8(WorkingBuffer, 31) local SignBit = bit32.extract(LastByte, 7) buffer.writeu8(WorkingBuffer, 31, bit32.band(LastByte, 0x7F)) local YCoord = FieldPrime.Decode(WorkingBuffer) local YSquared = FieldPrime.Square(YCoord) local Numerator = FieldPrime.Sub(YSquared, FieldPrime.Num(1)) local Denominator = FieldPrime.Mul(YSquared, CURVE_D) local DenomPlusOne = FieldPrime.Add(Denominator, FieldPrime.Num(1)) local XCoord = FieldPrime.SqrtDiv(Numerator, DenomPlusOne) if not XCoord then return nil end local CanonicalX = FieldPrime.Canonicalize(XCoord) local XSignBit = buffer.readf64(CanonicalX, 0) % 2 if XSignBit ~= SignBit then XCoord = FieldPrime.Carry(FieldPrime.Neg(XCoord)) end local ZCoord = FieldPrime.Num(1) local TCoord = FieldPrime.Mul(XCoord, YCoord) local Result = buffer.create(POINT_SIZE) buffer.copy(Result, 0 * COORD_SIZE, XCoord, 0, COORD_SIZE) buffer.copy(Result, 1 * COORD_SIZE, YCoord, 0, COORD_SIZE) buffer.copy(Result, 2 * COORD_SIZE, ZCoord, 0, COORD_SIZE) buffer.copy(Result, 3 * COORD_SIZE, TCoord, 0, COORD_SIZE) return Result end local BASEPOINT_BYTES = buffer.create(32) do local BasePointHex = { 0x58, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66 } for Index = 1, 32 do buffer.writeu8(BASEPOINT_BYTES, Index - 1, BasePointHex[Index]) end BASEPONT_G = Edwards25519.Decode(BASEPOINT_BYTES) end function Edwards25519.AffineRadixWTable(BasePoint: buffer, RadixWidth: number): buffer if RadixWidth <= 0 or RadixWidth > 8 then error("Invalid Radix width", 2) end if buffer.len(BasePoint) ~= POINT_SIZE then error("Invalid Basepoint", 2) end local MaxWindows = math.ceil(256 / RadixWidth) local MaxRowSize = 2 ^ RadixWidth / 2 local TableData = buffer.create(MaxWindows * MaxRowSize * AFFINE_NIELS_SIZE) local CurrentBasePoint = buffer.create(POINT_SIZE) buffer.copy(CurrentBasePoint, 0, BasePoint, 0, POINT_SIZE) local AffineNiels = Edwards25519.AffineNiels local Add = Edwards25519.Add local Double = Edwards25519.Double local Scale = Edwards25519.Scale local Niels = Edwards25519.Niels local NielsSize = AFFINE_NIELS_SIZE for WindowIndex = 1, MaxWindows do local BaseOffset = ((WindowIndex - 1) * MaxRowSize * NielsSize) local WorkingPoint = buffer.create(POINT_SIZE) buffer.copy(WorkingPoint, 0, CurrentBasePoint, 0, POINT_SIZE) local ScaledPoint = Scale(WorkingPoint) local FirstAffineNiels = AffineNiels(ScaledPoint) buffer.copy(TableData, BaseOffset, FirstAffineNiels, 0, NielsSize) local FirstNiels = Niels(ScaledPoint) for Multiple = 2, MaxRowSize do Add(WorkingPoint, FirstNiels, WorkingPoint) local Scaled = Scale(WorkingPoint) local AffineNielsBuffer = AffineNiels(Scaled) local Offset = BaseOffset + ((Multiple - 1) * NielsSize) buffer.copy(TableData, Offset, AffineNielsBuffer, 0, NielsSize) end for _ = 1, RadixWidth do CurrentBasePoint = Double(CurrentBasePoint) end end return TableData end do if BASEPONT_G then AFFINE_BASEPOINT_TABLE = Edwards25519.AffineRadixWTable(BASEPONT_G, BASE_RADIX_WIDTH) end end function Edwards25519.GetAffineBasePointTableEntry(WindowIndex: number, Multiple: number, Storage: buffer?): buffer if not AFFINE_BASEPOINT_TABLE then return buffer.create(0) end local BaseOffset = ((WindowIndex - 1) * BASE_POINT_ROW * AFFINE_NIELS_SIZE) local Offset = BaseOffset + ((Multiple - 1) * AFFINE_NIELS_SIZE) local AffineNielsPoint = Storage or buffer.create(AFFINE_NIELS_SIZE) buffer.copy(AffineNielsPoint, 0, AFFINE_BASEPOINT_TABLE, Offset, AFFINE_NIELS_SIZE) return AffineNielsPoint end function Edwards25519.SignedRadixW(ScalarBits: buffer, ScalarBitCount: number, RadixWidth: number): (buffer, number) if ScalarBitCount <= 0 or ScalarBitCount > 256 then error("Invalid scalar bit count", 2) end if RadixWidth <= 0 or RadixWidth > 8 then error("Invalid Radix width", 2) end local RadixValue = 2 ^ RadixWidth local HalfRadix = RadixValue / 2 local MaxOutputLength = 272 local OutputDigits = RADIX_OUTPUT local OutputLength, Accumulator = 0, 0 local Multiplier = 1 for BitIndex = 1, ScalarBitCount do if BitIndex > ScalarBitCount then break end local BitValue = buffer.readf64(ScalarBits, (BitIndex - 1) * 8) Accumulator += BitValue * Multiplier Multiplier *= 2 while BitIndex == ScalarBitCount and Accumulator > 0 or Multiplier > RadixValue do if OutputLength >= MaxOutputLength then error("Output overflow in SignedRadixW") end local Remainder = Accumulator % RadixValue if Remainder >= HalfRadix then Remainder -= RadixValue end Accumulator = (Accumulator - Remainder) / RadixValue Multiplier /= RadixValue buffer.writef64(OutputDigits, OutputLength * 8, Remainder) OutputLength += 1 end end return OutputDigits, OutputLength end function Edwards25519.WindowedNAF(ScalarBits: buffer, ScalarBitCount: number, WindowWidth: number): (buffer, number) local WindowValue = 2 ^ WindowWidth local HalfWindow = WindowValue / 2 local OutputNAF = NAF_OUTPUT local OutputLength = 0 local Accumulator = 0 local Multiplier = 1 for BitIndex = 1, ScalarBitCount do local BitValue = buffer.readf64(ScalarBits, (BitIndex - 1) * 8) Accumulator += BitValue * Multiplier Multiplier *= 2 while BitIndex == ScalarBitCount and Accumulator > 0 or Multiplier > WindowValue do if Accumulator % 2 == 0 then Accumulator /= 2 Multiplier /= 2 buffer.writef64(OutputNAF, OutputLength * 8, 0) OutputLength += 1 else local Remainder = Accumulator % WindowValue if Remainder >= HalfWindow then Remainder -= WindowValue end Accumulator -= Remainder buffer.writef64(OutputNAF, OutputLength * 8, Remainder) OutputLength += 1 end end end while OutputLength > 0 and buffer.readf64(OutputNAF, (OutputLength - 1) * 8) == 0 do OutputLength -= 1 end return OutputNAF, OutputLength end function Edwards25519.WindowedNAFTable(BasePoint: buffer, WindowWidth: number): buffer local PointSize = POINT_SIZE local CoordSize = COORD_SIZE local CurveK = CURVE_K local MaxOddMultiples = 2 ^ WindowWidth Edwards25519.Double(BasePoint, NAF_TABLE_DOUBLED) local TableData = buffer.create(MaxOddMultiples * PointSize) local FAdd = FieldPrime.Add local FSub = FieldPrime.Sub local FMul = FieldPrime.Mul local P1X = NAF_TABLE_P1X local P1Y = NAF_TABLE_P1Y local P1Z = NAF_TABLE_P1Z local P1T = NAF_TABLE_P1T local N2P = NAF_TABLE_N2P local N2M = NAF_TABLE_N2M local N2Z = NAF_TABLE_N2Z local N2T = NAF_TABLE_N2T local TMP = NAF_TABLE_TMP local DBLP = NAF_TABLE_DBL_P local DBLM = NAF_TABLE_DBL_M local DBLZ = NAF_TABLE_DBL_Z local DBLT = NAF_TABLE_DBL_T local Doubled = NAF_TABLE_DOUBLED buffer.copy(P1X, 0, Doubled, 0, CoordSize) buffer.copy(P1Y, 0, Doubled, CoordSize, CoordSize) buffer.copy(P1Z, 0, Doubled, 2 * CoordSize, CoordSize) buffer.copy(P1T, 0, Doubled, 3 * CoordSize, CoordSize) FAdd(P1Y, P1X, DBLP) FSub(P1Y, P1X, DBLM) FAdd(P1Z, P1Z, DBLZ) FMul(P1T, CurveK, DBLT) buffer.copy(P1X, 0, BasePoint, 0, CoordSize) buffer.copy(P1Y, 0, BasePoint, CoordSize, CoordSize) buffer.copy(P1Z, 0, BasePoint, 2 * CoordSize, CoordSize) buffer.copy(P1T, 0, BasePoint, 3 * CoordSize, CoordSize) FAdd(P1Y, P1X, N2P) FSub(P1Y, P1X, N2M) FAdd(P1Z, P1Z, N2Z) FMul(P1T, CurveK, N2T) buffer.copy(TableData, 0, N2P, 0, CoordSize) buffer.copy(TableData, CoordSize, N2M, 0, CoordSize) buffer.copy(TableData, 2 * CoordSize, N2Z, 0, CoordSize) buffer.copy(TableData, 3 * CoordSize, N2T, 0, CoordSize) buffer.copy(P1X, 0, BasePoint, 0, CoordSize) buffer.copy(P1Y, 0, BasePoint, CoordSize, CoordSize) buffer.copy(P1Z, 0, BasePoint, 2 * CoordSize, CoordSize) buffer.copy(P1T, 0, BasePoint, 3 * CoordSize, CoordSize) for OddMultiple = 3, MaxOddMultiples, 2 do local CurrentOffset = ((OddMultiple - 1) * PointSize) FSub(P1Y, P1X, TMP) FMul(TMP, DBLM, TMP) FAdd(P1Y, P1X, N2P) FMul(N2P, DBLP, N2P) FMul(P1T, DBLT, P1T) FMul(P1Z, DBLZ, P1Z) FSub(N2P, TMP, N2M) FSub(P1Z, P1T, N2Z) FAdd(P1Z, P1T, P1Z) FAdd(N2P, TMP, N2P) FMul(N2M, N2Z, P1X) FMul(P1Z, N2P, P1Y) FMul(N2Z, P1Z, P1Z) FMul(N2M, N2P, P1T) FAdd(P1Y, P1X, N2P) FSub(P1Y, P1X, N2M) FAdd(P1Z, P1Z, N2Z) FMul(P1T, CurveK, N2T) buffer.copy(TableData, CurrentOffset, N2P, 0, CoordSize) buffer.copy(TableData, CurrentOffset + CoordSize, N2M, 0, CoordSize) buffer.copy(TableData, CurrentOffset + 2 * CoordSize, N2Z, 0, CoordSize) buffer.copy(TableData, CurrentOffset + 3 * CoordSize, N2T, 0, CoordSize) end return TableData end function Edwards25519.MulG(ScalarBits: buffer, ScalarBitCount: number): buffer local PointSize = POINT_SIZE local CoordSize = COORD_SIZE local AffineNielsSize = AFFINE_NIELS_SIZE local IdentityO = IDENTITY_O local BaseRadixWidth = BASE_RADIX_WIDTH local BasePointRow = BASE_POINT_ROW local AffineTable = AFFINE_BASEPOINT_TABLE :: buffer local SignedWindows, WindowCount = Edwards25519.SignedRadixW(ScalarBits, ScalarBitCount, BaseRadixWidth) local ResultPoint = MULG_RESULT_POINT buffer.copy(ResultPoint, 0, IdentityO, 0, PointSize) local AffineNielsPoint = MULG_AFFINE_NIELS local DummyPoint = MULG_DUMMY_POINT buffer.copy(DummyPoint, 0, IdentityO, 0, PointSize) local FAdd = FieldPrime.Add local FSub = FieldPrime.Sub local FMul = FieldPrime.Mul local P1X = MULG_P1X local P1Y = MULG_P1Y local P1Z = MULG_P1Z local P1T = MULG_P1T local N2P = MULG_N2P local N2M = MULG_N2M local N2T = MULG_N2T local TMP = MULG_TMP for WindowIndex = 1, WindowCount do local WindowValue = buffer.readf64(SignedWindows, (WindowIndex - 1) * 8) if WindowValue > 0 then local BaseOffset = ((WindowIndex - 1) * BasePointRow * AffineNielsSize) local Offset = BaseOffset + ((WindowValue - 1) * AffineNielsSize) buffer.copy(AffineNielsPoint, 0, AffineTable, Offset, AffineNielsSize) buffer.copy(P1X, 0, ResultPoint, 0, CoordSize) buffer.copy(P1Y, 0, ResultPoint, CoordSize, CoordSize) buffer.copy(P1Z, 0, ResultPoint, 2 * CoordSize, CoordSize) buffer.copy(P1T, 0, ResultPoint, 3 * CoordSize, CoordSize) buffer.copy(N2P, 0, AffineNielsPoint, 0, CoordSize) buffer.copy(N2M, 0, AffineNielsPoint, CoordSize, CoordSize) buffer.copy(N2T, 0, AffineNielsPoint, 2 * CoordSize, CoordSize) FSub(P1Y, P1X, TMP) FMul(TMP, N2M, TMP) FAdd(P1Y, P1X, P1X) FMul(P1X, N2P, P1X) FMul(P1T, N2T, P1T) FAdd(P1Z, P1Z, P1Z) FSub(P1X, TMP, P1Y) FSub(P1Z, P1T, N2P) FAdd(P1Z, P1T, P1Z) FAdd(P1X, TMP, P1X) FMul(P1Y, N2P, TMP) FMul(P1Z, P1X, P1T) FMul(N2P, P1Z, P1Z) FMul(P1Y, P1X, P1X) buffer.copy(ResultPoint, 0, TMP, 0, CoordSize) buffer.copy(ResultPoint, CoordSize, P1T, 0, CoordSize) buffer.copy(ResultPoint, 2 * CoordSize, P1Z, 0, CoordSize) buffer.copy(ResultPoint, 3 * CoordSize, P1X, 0, CoordSize) elseif WindowValue < 0 then local BaseOffset = ((WindowIndex - 1) * BasePointRow * AffineNielsSize) local Offset = BaseOffset + (((-WindowValue) - 1) * AffineNielsSize) buffer.copy(AffineNielsPoint, 0, AffineTable, Offset, AffineNielsSize) buffer.copy(P1X, 0, ResultPoint, 0, CoordSize) buffer.copy(P1Y, 0, ResultPoint, CoordSize, CoordSize) buffer.copy(P1Z, 0, ResultPoint, 2 * CoordSize, CoordSize) buffer.copy(P1T, 0, ResultPoint, 3 * CoordSize, CoordSize) buffer.copy(N2P, 0, AffineNielsPoint, 0, CoordSize) buffer.copy(N2M, 0, AffineNielsPoint, CoordSize, CoordSize) buffer.copy(N2T, 0, AffineNielsPoint, 2 * CoordSize, CoordSize) FSub(P1Y, P1X, TMP) FMul(TMP, N2P, TMP) FAdd(P1Y, P1X, P1X) FMul(P1X, N2M, P1X) FMul(P1T, N2T, P1T) FAdd(P1Z, P1Z, P1Z) FSub(P1X, TMP, P1Y) FAdd(P1Z, P1T, N2P) FSub(P1Z, P1T, P1Z) FAdd(P1X, TMP, P1X) FMul(P1Y, N2P, TMP) FMul(P1Z, P1X, P1T) FMul(N2P, P1Z, P1Z) FMul(P1Y, P1X, P1X) buffer.copy(ResultPoint, 0, TMP, 0, CoordSize) buffer.copy(ResultPoint, CoordSize, P1T, 0, CoordSize) buffer.copy(ResultPoint, 2 * CoordSize, P1Z, 0, CoordSize) buffer.copy(ResultPoint, 3 * CoordSize, P1X, 0, CoordSize) else local BaseOffset = ((WindowIndex - 1) * BasePointRow * AffineNielsSize) buffer.copy(AffineNielsPoint, 0, AffineTable, BaseOffset, AffineNielsSize) buffer.copy(P1X, 0, DummyPoint, 0, CoordSize) buffer.copy(P1Y, 0, DummyPoint, CoordSize, CoordSize) buffer.copy(P1Z, 0, DummyPoint, 2 * CoordSize, CoordSize) buffer.copy(P1T, 0, DummyPoint, 3 * CoordSize, CoordSize) buffer.copy(N2P, 0, AffineNielsPoint, 0, CoordSize) buffer.copy(N2M, 0, AffineNielsPoint, CoordSize, CoordSize) buffer.copy(N2T, 0, AffineNielsPoint, 2 * CoordSize, CoordSize) FSub(P1Y, P1X, TMP) FMul(TMP, N2M, TMP) FAdd(P1Y, P1X, P1X) FMul(P1X, N2P, P1X) FMul(P1T, N2T, P1T) FAdd(P1Z, P1Z, P1Z) FSub(P1X, TMP, P1Y) FSub(P1Z, P1T, N2P) FAdd(P1Z, P1T, P1Z) FAdd(P1X, TMP, P1X) FMul(P1Y, N2P, TMP) FMul(P1Z, P1X, P1T) FMul(N2P, P1Z, P1Z) FMul(P1Y, P1X, P1X) buffer.copy(DummyPoint, 0, TMP, 0, CoordSize) buffer.copy(DummyPoint, CoordSize, P1T, 0, CoordSize) buffer.copy(DummyPoint, 2 * CoordSize, P1Z, 0, CoordSize) buffer.copy(DummyPoint, 3 * CoordSize, P1X, 0, CoordSize) end end local Output = buffer.create(PointSize) buffer.copy(Output, 0, ResultPoint, 0, PointSize) return Output end function Edwards25519.Mul(BasePoint: buffer, ScalarBits: buffer, ScalarBitCount: number): buffer local PointSize = POINT_SIZE local CoordSize = COORD_SIZE local IdentityO = IDENTITY_O local NAFForm, NAFLength = Edwards25519.WindowedNAF(ScalarBits, ScalarBitCount, 5) local MultipleTable = Edwards25519.WindowedNAFTable(BasePoint, 5) local ResultPoint = MUL_RESULT_POINT buffer.copy(ResultPoint, 0, IdentityO, 0, PointSize) local NielsPoint = MUL_NIELS_POINT local Square = FieldPrime.Square local FAdd = FieldPrime.Add local FSub = FieldPrime.Sub local FMul = FieldPrime.Mul local Carry = FieldPrime.Carry local DoubleX = MUL_DOUBLE_X local DoubleY = MUL_DOUBLE_Y local DoubleZ = MUL_DOUBLE_Z local DoubleA = MUL_DOUBLE_A local DoubleB = MUL_DOUBLE_B local DoubleE = MUL_DOUBLE_E local DoubleG = MUL_DOUBLE_G local P1X = MUL_P1X local P1Y = MUL_P1Y local P1Z = MUL_P1Z local P1T = MUL_P1T local N2P = MUL_N2P local N2M = MUL_N2M local N2Z = MUL_N2Z local N2T = MUL_N2T local TMP = MUL_TMP for NAFIndex = NAFLength, 1, -1 do local NAFDigit = buffer.readf64(NAFForm, (NAFIndex - 1) * 8) if NAFDigit == 0 then buffer.copy(DoubleX, 0, ResultPoint, 0, CoordSize) buffer.copy(DoubleY, 0, ResultPoint, CoordSize, CoordSize) buffer.copy(DoubleZ, 0, ResultPoint, 2 * CoordSize, CoordSize) Square(DoubleX, DoubleA) Square(DoubleY, DoubleB) Square(DoubleZ, DoubleZ) FAdd(DoubleZ, DoubleZ, DoubleZ) FAdd(DoubleA, DoubleB, DoubleE) FAdd(DoubleX, DoubleY, DoubleX) Square(DoubleX, DoubleG) FSub(DoubleG, DoubleE, DoubleG) Carry(DoubleG, DoubleG) FSub(DoubleB, DoubleA, DoubleB) FSub(DoubleZ, DoubleB, DoubleZ) Carry(DoubleZ, DoubleZ) FMul(DoubleG, DoubleZ, DoubleX) FMul(DoubleB, DoubleE, DoubleY) FMul(DoubleZ, DoubleB, DoubleZ) FMul(DoubleG, DoubleE, DoubleE) buffer.copy(ResultPoint, 0, DoubleX, 0, CoordSize) buffer.copy(ResultPoint, CoordSize, DoubleY, 0, CoordSize) buffer.copy(ResultPoint, 2 * CoordSize, DoubleZ, 0, CoordSize) buffer.copy(ResultPoint, 3 * CoordSize, DoubleE, 0, CoordSize) elseif NAFDigit > 0 then buffer.copy(NielsPoint, 0, MultipleTable, ((NAFDigit - 1) * PointSize), PointSize) buffer.copy(P1X, 0, ResultPoint, 0, CoordSize) buffer.copy(P1Y, 0, ResultPoint, CoordSize, CoordSize) buffer.copy(P1Z, 0, ResultPoint, 2 * CoordSize, CoordSize) buffer.copy(P1T, 0, ResultPoint, 3 * CoordSize, CoordSize) buffer.copy(N2P, 0, NielsPoint, 0, CoordSize) buffer.copy(N2M, 0, NielsPoint, CoordSize, CoordSize) buffer.copy(N2Z, 0, NielsPoint, 2 * CoordSize, CoordSize) buffer.copy(N2T, 0, NielsPoint, 3 * CoordSize, CoordSize) FSub(P1Y, P1X, TMP) FMul(TMP, N2M, TMP) FAdd(P1Y, P1X, P1X) FMul(P1X, N2P, P1X) FMul(P1T, N2T, P1T) FMul(P1Z, N2Z, P1Z) FSub(P1X, TMP, P1Y) FSub(P1Z, P1T, N2P) FAdd(P1Z, P1T, P1Z) FAdd(P1X, TMP, P1X) FMul(P1Y, N2P, TMP) FMul(P1Z, P1X, P1T) FMul(N2P, P1Z, P1Z) FMul(P1Y, P1X, P1X) buffer.copy(ResultPoint, 0, TMP, 0, CoordSize) buffer.copy(ResultPoint, CoordSize, P1T, 0, CoordSize) buffer.copy(ResultPoint, 2 * CoordSize, P1Z, 0, CoordSize) buffer.copy(ResultPoint, 3 * CoordSize, P1X, 0, CoordSize) else buffer.copy(NielsPoint, 0, MultipleTable, (((-NAFDigit) - 1) * PointSize), PointSize) buffer.copy(P1X, 0, ResultPoint, 0, CoordSize) buffer.copy(P1Y, 0, ResultPoint, CoordSize, CoordSize) buffer.copy(P1Z, 0, ResultPoint, 2 * CoordSize, CoordSize) buffer.copy(P1T, 0, ResultPoint, 3 * CoordSize, CoordSize) buffer.copy(N2P, 0, NielsPoint, 0, CoordSize) buffer.copy(N2M, 0, NielsPoint, CoordSize, CoordSize) buffer.copy(N2Z, 0, NielsPoint, 2 * CoordSize, CoordSize) buffer.copy(N2T, 0, NielsPoint, 3 * CoordSize, CoordSize) FSub(P1Y, P1X, TMP) FMul(TMP, N2P, TMP) FAdd(P1Y, P1X, P1X) FMul(P1X, N2M, P1X) FMul(P1T, N2T, P1T) FMul(P1Z, N2Z, P1Z) FSub(P1X, TMP, P1Y) FAdd(P1Z, P1T, N2P) FSub(P1Z, P1T, P1Z) FAdd(P1X, TMP, P1X) FMul(P1Y, N2P, TMP) FMul(P1Z, P1X, P1T) FMul(N2P, P1Z, P1Z) FMul(P1Y, P1X, P1X) buffer.copy(ResultPoint, 0, TMP, 0, CoordSize) buffer.copy(ResultPoint, CoordSize, P1T, 0, CoordSize) buffer.copy(ResultPoint, 2 * CoordSize, P1Z, 0, CoordSize) buffer.copy(ResultPoint, 3 * CoordSize, P1X, 0, CoordSize) end end local Output = buffer.create(PointSize) buffer.copy(Output, 0, ResultPoint, 0, PointSize) return Output end return Edwards25519
11,461
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/FieldPrime.luau
--[=[ Cryptography library: Field Prime (Curve25519 Base Field) Return type: varies by function Example usage: local FieldPrime = require("FieldPrime") --------Usage Case 1: Basic arithmetic-------- local ElementA = FieldPrime.Num(42) local ElementB = FieldPrime.Num(17) local Sum = FieldPrime.Add(ElementA, ElementB) local Product = FieldPrime.Mul(ElementA, ElementB) --------Usage Case 2: Encoding/decoding-------- local Encoded = FieldPrime.Encode(ElementA) local Decoded = FieldPrime.Decode(Encoded) --]=] --!strict --!optimize 2 --!native local SIZE = 104 local COMPOUND_V = (19 / 2 ^ 255) local SQUARES = buffer.create(SIZE) do local Tbl = { 0958640 * 2 ^ 0, 0826664 * 2 ^ 22, 1613251 * 2 ^ 43, 1041528 * 2 ^ 64, 0013673 * 2 ^ 85, 0387171 * 2 ^ 107, 1824679 * 2 ^ 128, 0313839 * 2 ^ 149, 0709440 * 2 ^ 170, 0122635 * 2 ^ 192, 0262782 * 2 ^ 213, 0712905 * 2 ^ 234, } for Index = 1, 12 do buffer.writef64(SQUARES, (Index - 1) * 8, Tbl[Index]) end end local FieldPrime = {} function FieldPrime.Num(Number: number): buffer local Buf = buffer.create(SIZE) buffer.writef64(Buf, 0, Number) return Buf end function FieldPrime.Neg(ElementA: buffer): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 = buffer.readf64(ElementA, 0), buffer.readf64(ElementA, 8), buffer.readf64(ElementA, 16), buffer.readf64(ElementA, 24), buffer.readf64(ElementA, 32), buffer.readf64(ElementA, 40), buffer.readf64(ElementA, 48), buffer.readf64(ElementA, 56), buffer.readf64(ElementA, 64), buffer.readf64(ElementA, 72), buffer.readf64(ElementA, 80), buffer.readf64(ElementA, 88) local Buf = buffer.create(SIZE) buffer.writef64(Buf, 0, -A00) buffer.writef64(Buf, 8, -A01) buffer.writef64(Buf, 16, -A02) buffer.writef64(Buf, 24, -A03) buffer.writef64(Buf, 32, -A04) buffer.writef64(Buf, 40, -A05) buffer.writef64(Buf, 48, -A06) buffer.writef64(Buf, 56, -A07) buffer.writef64(Buf, 64, -A08) buffer.writef64(Buf, 72, -A09) buffer.writef64(Buf, 80, -A10) buffer.writef64(Buf, 88, -A11) return Buf end function FieldPrime.Add(ElementA: buffer, ElementB: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 = buffer.readf64(ElementA, 0), buffer.readf64(ElementA, 8), buffer.readf64(ElementA, 16), buffer.readf64(ElementA, 24), buffer.readf64(ElementA, 32), buffer.readf64(ElementA, 40), buffer.readf64(ElementA, 48), buffer.readf64(ElementA, 56), buffer.readf64(ElementA, 64), buffer.readf64(ElementA, 72), buffer.readf64(ElementA, 80), buffer.readf64(ElementA, 88) local B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10, B11 = buffer.readf64(ElementB, 0), buffer.readf64(ElementB, 8), buffer.readf64(ElementB, 16), buffer.readf64(ElementB, 24), buffer.readf64(ElementB, 32), buffer.readf64(ElementB, 40), buffer.readf64(ElementB, 48), buffer.readf64(ElementB, 56), buffer.readf64(ElementB, 64), buffer.readf64(ElementB, 72), buffer.readf64(ElementB, 80), buffer.readf64(ElementB, 88) local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 + B00) buffer.writef64(Buf, 8, A01 + B01) buffer.writef64(Buf, 16, A02 + B02) buffer.writef64(Buf, 24, A03 + B03) buffer.writef64(Buf, 32, A04 + B04) buffer.writef64(Buf, 40, A05 + B05) buffer.writef64(Buf, 48, A06 + B06) buffer.writef64(Buf, 56, A07 + B07) buffer.writef64(Buf, 64, A08 + B08) buffer.writef64(Buf, 72, A09 + B09) buffer.writef64(Buf, 80, A10 + B10) buffer.writef64(Buf, 88, A11 + B11) return Buf end function FieldPrime.Sub(ElementA: buffer, ElementB: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 = buffer.readf64(ElementA, 0), buffer.readf64(ElementA, 8), buffer.readf64(ElementA, 16), buffer.readf64(ElementA, 24), buffer.readf64(ElementA, 32), buffer.readf64(ElementA, 40), buffer.readf64(ElementA, 48), buffer.readf64(ElementA, 56), buffer.readf64(ElementA, 64), buffer.readf64(ElementA, 72), buffer.readf64(ElementA, 80), buffer.readf64(ElementA, 88) local B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10, B11 = buffer.readf64(ElementB, 0), buffer.readf64(ElementB, 8), buffer.readf64(ElementB, 16), buffer.readf64(ElementB, 24), buffer.readf64(ElementB, 32), buffer.readf64(ElementB, 40), buffer.readf64(ElementB, 48), buffer.readf64(ElementB, 56), buffer.readf64(ElementB, 64), buffer.readf64(ElementB, 72), buffer.readf64(ElementB, 80), buffer.readf64(ElementB, 88) local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 - B00) buffer.writef64(Buf, 8, A01 - B01) buffer.writef64(Buf, 16, A02 - B02) buffer.writef64(Buf, 24, A03 - B03) buffer.writef64(Buf, 32, A04 - B04) buffer.writef64(Buf, 40, A05 - B05) buffer.writef64(Buf, 48, A06 - B06) buffer.writef64(Buf, 56, A07 - B07) buffer.writef64(Buf, 64, A08 - B08) buffer.writef64(Buf, 72, A09 - B09) buffer.writef64(Buf, 80, A10 - B10) buffer.writef64(Buf, 88, A11 - B11) return Buf end function FieldPrime.Carry(ElementA: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 = buffer.readf64(ElementA, 0), buffer.readf64(ElementA, 8), buffer.readf64(ElementA, 16), buffer.readf64(ElementA, 24), buffer.readf64(ElementA, 32), buffer.readf64(ElementA, 40), buffer.readf64(ElementA, 48), buffer.readf64(ElementA, 56), buffer.readf64(ElementA, 64), buffer.readf64(ElementA, 72), buffer.readf64(ElementA, 80), buffer.readf64(ElementA, 88) local C00, C01, C02, C03, C04, C05, C06, C07, C08, C09, C10, C11 C11 = A11 + 3 * 2 ^ 306 - 3 * 2 ^ 306 A00 += 19 / 2 ^ 255 * C11 C00 = A00 + 3 * 2 ^ 73 - 3 * 2 ^ 73 A01 += C00 C01 = A01 + 3 * 2 ^ 94 - 3 * 2 ^ 94 A02 += C01 C02 = A02 + 3 * 2 ^ 115 - 3 * 2 ^ 115 A03 += C02 C03 = A03 + 3 * 2 ^ 136 - 3 * 2 ^ 136 A04 += C03 C04 = A04 + 3 * 2 ^ 158 - 3 * 2 ^ 158 A05 += C04 C05 = A05 + 3 * 2 ^ 179 - 3 * 2 ^ 179 A06 += C05 C06 = A06 + 3 * 2 ^ 200 - 3 * 2 ^ 200 A07 += C06 C07 = A07 + 3 * 2 ^ 221 - 3 * 2 ^ 221 A08 += C07 C08 = A08 + 3 * 2 ^ 243 - 3 * 2 ^ 243 A09 += C08 C09 = A09 + 3 * 2 ^ 264 - 3 * 2 ^ 264 A10 += C09 C10 = A10 + 3 * 2 ^ 285 - 3 * 2 ^ 285 A11 = A11 - C11 + C10 C11 = A11 + 3 * 2 ^ 306 - 3 * 2 ^ 306 local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 - C00 + 19 / 2 ^ 255 * C11) buffer.writef64(Buf, 8, A01 - C01) buffer.writef64(Buf, 16, A02 - C02) buffer.writef64(Buf, 24, A03 - C03) buffer.writef64(Buf, 32, A04 - C04) buffer.writef64(Buf, 40, A05 - C05) buffer.writef64(Buf, 48, A06 - C06) buffer.writef64(Buf, 56, A07 - C07) buffer.writef64(Buf, 64, A08 - C08) buffer.writef64(Buf, 72, A09 - C09) buffer.writef64(Buf, 80, A10 - C10) buffer.writef64(Buf, 88, A11 - C11) return Buf end function FieldPrime.Canonicalize(ElementA: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 = buffer.readf64(ElementA, 0), buffer.readf64(ElementA, 8), buffer.readf64(ElementA, 16), buffer.readf64(ElementA, 24), buffer.readf64(ElementA, 32), buffer.readf64(ElementA, 40), buffer.readf64(ElementA, 48), buffer.readf64(ElementA, 56), buffer.readf64(ElementA, 64), buffer.readf64(ElementA, 72), buffer.readf64(ElementA, 80), buffer.readf64(ElementA, 88) local C00, C01, C02, C03, C04, C05, C06, C07, C08, C09, C10, C11 C00 = A00 % 2 ^ 22 A01 += A00 - C00 C01 = A01 % 2 ^ 43 A02 += A01 - C01 C02 = A02 % 2 ^ 64 A03 += A02 - C02 C03 = A03 % 2 ^ 85 A04 += A03 - C03 C04 = A04 % 2 ^ 107 A05 += A04 - C04 C05 = A05 % 2 ^ 128 A06 += A05 - C05 C06 = A06 % 2 ^ 149 A07 += A06 - C06 C07 = A07 % 2 ^ 170 A08 += A07 - C07 C08 = A08 % 2 ^ 192 A09 += A08 - C08 C09 = A09 % 2 ^ 213 A10 += A09 - C09 C10 = A10 % 2 ^ 234 A11 += A10 - C10 C11 = A11 % 2 ^ 255 C00 += 19 / 2 ^ 255 * (A11 - C11) local Buf = Storage or buffer.create(SIZE) if C11 / 2 ^ 234 == 2 ^ 21 - 1 and C10 / 2 ^ 213 == 2 ^ 21 - 1 and C09 / 2 ^ 192 == 2 ^ 21 - 1 and C08 / 2 ^ 170 == 2 ^ 22 - 1 and C07 / 2 ^ 149 == 2 ^ 21 - 1 and C06 / 2 ^ 128 == 2 ^ 21 - 1 and C05 / 2 ^ 107 == 2 ^ 21 - 1 and C04 / 2 ^ 85 == 2 ^ 22 - 1 and C03 / 2 ^ 64 == 2 ^ 21 - 1 and C02 / 2 ^ 43 == 2 ^ 21 - 1 and C01 / 2 ^ 22 == 2 ^ 21 - 1 and C00 >= 2 ^ 22 - 19 then buffer.writef64(Buf, 0, 19 - 2 ^ 22 + C00) for Index = 8, 88, 8 do buffer.writef64(Buf, Index, 0) end else buffer.writef64(Buf, 0, C00) buffer.writef64(Buf, 8, C01) buffer.writef64(Buf, 16, C02) buffer.writef64(Buf, 24, C03) buffer.writef64(Buf, 32, C04) buffer.writef64(Buf, 40, C05) buffer.writef64(Buf, 48, C06) buffer.writef64(Buf, 56, C07) buffer.writef64(Buf, 64, C08) buffer.writef64(Buf, 72, C09) buffer.writef64(Buf, 80, C10) buffer.writef64(Buf, 88, C11) end return Buf end function FieldPrime.Eq(ElementA: buffer, ElementB: buffer): boolean local Difference = FieldPrime.Canonicalize(FieldPrime.Sub(ElementA, ElementB)) local DifferenceAccumulator = 0 for LimbIndex = 0, 88, 8 do local LimbLow = buffer.readu32(Difference, LimbIndex) local LimbHigh = buffer.readu32(Difference, LimbIndex + 4) DifferenceAccumulator = bit32.bor(DifferenceAccumulator, LimbLow, LimbHigh) end return DifferenceAccumulator == 0 end local A00: number, A01: number, A02: number, A03: number, A04: number, A05: number, A06: number, A07: number, A08: number, A09: number, A10: number, A11: number local B00: number, B01: number, B02: number, B03: number, B04: number, B05: number, B06: number, B07: number, B08: number, B09: number, B10: number, B11: number function FieldPrime.Mul(ElementA: buffer, ElementB: buffer, Storage: buffer?): buffer local CompoundV = COMPOUND_V A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 = buffer.readf64(ElementA, 0), buffer.readf64(ElementA, 8), buffer.readf64(ElementA, 16), buffer.readf64(ElementA, 24), buffer.readf64(ElementA, 32), buffer.readf64(ElementA, 40), buffer.readf64(ElementA, 48), buffer.readf64(ElementA, 56), buffer.readf64(ElementA, 64), buffer.readf64(ElementA, 72), buffer.readf64(ElementA, 80), buffer.readf64(ElementA, 88) B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10, B11 = buffer.readf64(ElementB, 0), buffer.readf64(ElementB, 8), buffer.readf64(ElementB, 16), buffer.readf64(ElementB, 24), buffer.readf64(ElementB, 32), buffer.readf64(ElementB, 40), buffer.readf64(ElementB, 48), buffer.readf64(ElementB, 56), buffer.readf64(ElementB, 64), buffer.readf64(ElementB, 72), buffer.readf64(ElementB, 80), buffer.readf64(ElementB, 88) local T00: number, T01: number, T02: number, T03: number, T04: number, T05: number, T06: number, T07: number, T08: number, T09: number, T10: number, T11: number = A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 local U00: number, U01: number, U02: number, U03: number, U04: number, U05: number, U06: number, U07: number, U08: number, U09: number, U10: number, U11: number = B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10, B11 local C00 = T11 * U01 + T10 * U02 + T09 * U03 + T08 * U04 + T07 * U05 + T06 * U06 + T05 * U07 + T04 * U08 + T03 * U09 + T02 * U10 + T01 * U11 local C01 = T11 * U02 + T10 * U03 + T09 * U04 + T08 * U05 + T07 * U06 + T06 * U07 + T05 * U08 + T04 * U09 + T03 * U10 + T02 * U11 local C02 = T11 * U03 + T10 * U04 + T09 * U05 + T08 * U06 + T07 * U07 + T06 * U08 + T05 * U09 + T04 * U10 + T03 * U11 local C03 = T11 * U04 + T10 * U05 + T09 * U06 + T08 * U07 + T07 * U08 + T06 * U09 + T05 * U10 + T04 * U11 local C04 = T11 * U05 + T10 * U06 + T09 * U07 + T08 * U08 + T07 * U09 + T06 * U10 + T05 * U11 local C05 = T11 * U06 + T10 * U07 + T09 * U08 + T08 * U09 + T07 * U10 + T06 * U11 local C06 = T11 * U07 + T10 * U08 + T09 * U09 + T08 * U10 + T07 * U11 local C07 = T11 * U08 + T10 * U09 + T09 * U10 + T08 * U11 local C08 = T11 * U09 + T10 * U10 + T09 * U11 local C09 = T11 * U10 + T10 * U11 local C10 = T11 * U11 C00 *= CompoundV C00 += T00 * U00 C01 *= CompoundV C01 += T01 * U00 + T00 * U01 C02 *= CompoundV C02 += T02 * U00 + T01 * U01 + T00 * U02 C03 *= CompoundV C03 += T03 * U00 + T02 * U01 + T01 * U02 + T00 * U03 C04 *= CompoundV C04 += T04 * U00 + T03 * U01 + T02 * U02 + T01 * U03 + T00 * U04 C05 *= CompoundV C05 += T05 * U00 + T04 * U01 + T03 * U02 + T02 * U03 + T01 * U04 + T00 * U05 C06 *= CompoundV C06 += T06 * U00 + T05 * U01 + T04 * U02 + T03 * U03 + T02 * U04 + T01 * U05 + T00 * U06 C07 *= CompoundV C07 += T07 * U00 + T06 * U01 + T05 * U02 + T04 * U03 + T03 * U04 + T02 * U05 + T01 * U06 + T00 * U07 C08 *= CompoundV C08 += T08 * U00 + T07 * U01 + T06 * U02 + T05 * U03 + T04 * U04 + T03 * U05 + T02 * U06 + T01 * U07 + T00 * U08 C09 *= CompoundV C09 += T09 * U00 + T08 * U01 + T07 * U02 + T06 * U03 + T05 * U04 + T04 * U05 + T03 * U06 + T02 * U07 + T01 * U08 + T00 * U09 C10 *= CompoundV C10 += T10 * U00 + T09 * U01 + T08 * U02 + T07 * U03 + T06 * U04 + T05 * U05 + T04 * U06 + T03 * U07 + T02 * U08 + T01 * U09 + T00 * U10 local C11 = T11 * U00 + T10 * U01 + T09 * U02 + T08 * U03 + T07 * U04 + T06 * U05 + T05 * U06 + T04 * U07 + T03 * U08 + T02 * U09 + T01 * U10 + T00 * U11 T10 = C10 + 3 * 2 ^ 285 - 3 * 2 ^ 285 C11 += T10 T11 = C11 + 3 * 2 ^ 306 - 3 * 2 ^ 306 C00 += CompoundV * T11 T00 = C00 + 3 * 2 ^ 73 - 3 * 2 ^ 73 C01 += T00 T01 = C01 + 3 * 2 ^ 94 - 3 * 2 ^ 94 C02 += T01 T02 = C02 + 3 * 2 ^ 115 - 3 * 2 ^ 115 C03 += T02 T03 = C03 + 3 * 2 ^ 136 - 3 * 2 ^ 136 C04 += T03 T04 = C04 + 3 * 2 ^ 158 - 3 * 2 ^ 158 C05 += T04 T05 = C05 + 3 * 2 ^ 179 - 3 * 2 ^ 179 C06 += T05 T06 = C06 + 3 * 2 ^ 200 - 3 * 2 ^ 200 C07 += T06 T07 = C07 + 3 * 2 ^ 221 - 3 * 2 ^ 221 C08 += T07 T08 = C08 + 3 * 2 ^ 243 - 3 * 2 ^ 243 C09 += T08 T09 = C09 + 3 * 2 ^ 264 - 3 * 2 ^ 264 C10 = C10 - T10 + T09 T10 = C10 + 3 * 2 ^ 285 - 3 * 2 ^ 285 C11 = C11 - T11 + T10 T11 = C11 + 3 * 2 ^ 306 - 3 * 2 ^ 306 local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, C00 - T00 + CompoundV * T11) buffer.writef64(Buf, 8, C01 - T01) buffer.writef64(Buf, 16, C02 - T02) buffer.writef64(Buf, 24, C03 - T03) buffer.writef64(Buf, 32, C04 - T04) buffer.writef64(Buf, 40, C05 - T05) buffer.writef64(Buf, 48, C06 - T06) buffer.writef64(Buf, 56, C07 - T07) buffer.writef64(Buf, 64, C08 - T08) buffer.writef64(Buf, 72, C09 - T09) buffer.writef64(Buf, 80, C10 - T10) buffer.writef64(Buf, 88, C11 - T11) return Buf end function FieldPrime.Square(ElementA: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 = buffer.readf64(ElementA, 0), buffer.readf64(ElementA, 8), buffer.readf64(ElementA, 16), buffer.readf64(ElementA, 24), buffer.readf64(ElementA, 32), buffer.readf64(ElementA, 40), buffer.readf64(ElementA, 48), buffer.readf64(ElementA, 56), buffer.readf64(ElementA, 64), buffer.readf64(ElementA, 72), buffer.readf64(ElementA, 80), buffer.readf64(ElementA, 88) local D00 = A00 * 2 local D01 = A01 * 2 local D02 = A02 * 2 local D03 = A03 * 2 local D04 = A04 * 2 local D05 = A05 * 2 local D06 = A06 * 2 local D07 = A07 * 2 local D08 = A08 * 2 local D09 = A09 * 2 local D10 = A10 * 2 local ReductionFactor = 19 / 2 ^ 255 local H00 = A11 * D01 + A10 * D02 + A09 * D03 + A08 * D04 + A07 * D05 + A06 * A06 local H01 = A11 * D02 + A10 * D03 + A09 * D04 + A08 * D05 + A07 * D06 local H02 = A11 * D03 + A10 * D04 + A09 * D05 + A08 * D06 + A07 * A07 local H03 = A11 * D04 + A10 * D05 + A09 * D06 + A08 * D07 local H04 = A11 * D05 + A10 * D06 + A09 * D07 + A08 * A08 local H05 = A11 * D06 + A10 * D07 + A09 * D08 local H06 = A11 * D07 + A10 * D08 + A09 * A09 local H07 = A11 * D08 + A10 * D09 local H08 = A11 * D09 + A10 * A10 local H09 = A11 * D10 local H10 = A11 * A11 local L00 = A00 * A00 local L01 = A01 * D00 local L02 = A02 * D00 + A01 * A01 local L03 = A03 * D00 + A02 * D01 local L04 = A04 * D00 + A03 * D01 + A02 * A02 local L05 = A05 * D00 + A04 * D01 + A03 * D02 local L06 = A06 * D00 + A05 * D01 + A04 * D02 + A03 * A03 local L07 = A07 * D00 + A06 * D01 + A05 * D02 + A04 * D03 local L08 = A08 * D00 + A07 * D01 + A06 * D02 + A05 * D03 + A04 * A04 local L09 = A09 * D00 + A08 * D01 + A07 * D02 + A06 * D03 + A05 * D04 local L10 = A10 * D00 + A09 * D01 + A08 * D02 + A07 * D03 + A06 * D04 + A05 * A05 local L11 = A11 * D00 + A10 * D01 + A09 * D02 + A08 * D03 + A07 * D04 + A06 * D05 local Result = Storage or buffer.create(SIZE) buffer.writef64(Result, 0, H00 * ReductionFactor + L00) buffer.writef64(Result, 8, H01 * ReductionFactor + L01) buffer.writef64(Result, 16, H02 * ReductionFactor + L02) buffer.writef64(Result, 24, H03 * ReductionFactor + L03) buffer.writef64(Result, 32, H04 * ReductionFactor + L04) buffer.writef64(Result, 40, H05 * ReductionFactor + L05) buffer.writef64(Result, 48, H06 * ReductionFactor + L06) buffer.writef64(Result, 56, H07 * ReductionFactor + L07) buffer.writef64(Result, 64, H08 * ReductionFactor + L08) buffer.writef64(Result, 72, H09 * ReductionFactor + L09) buffer.writef64(Result, 80, H10 * ReductionFactor + L10) buffer.writef64(Result, 88, L11) return FieldPrime.Carry(Result, Result) end function FieldPrime.KMul(ElementA: buffer, SmallK: number, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 = buffer.readf64(ElementA, 0), buffer.readf64(ElementA, 8), buffer.readf64(ElementA, 16), buffer.readf64(ElementA, 24), buffer.readf64(ElementA, 32), buffer.readf64(ElementA, 40), buffer.readf64(ElementA, 48), buffer.readf64(ElementA, 56), buffer.readf64(ElementA, 64), buffer.readf64(ElementA, 72), buffer.readf64(ElementA, 80), buffer.readf64(ElementA, 88) local C00, C01, C02, C03, C04, C05, C06, C07, C08, C09, C10, C11 A00 *= SmallK A01 *= SmallK A02 *= SmallK A03 *= SmallK A04 *= SmallK A05 *= SmallK A06 *= SmallK A07 *= SmallK A08 *= SmallK A09 *= SmallK A10 *= SmallK A11 *= SmallK C11 = A11 + 3 * 2 ^ 306 - 3 * 2 ^ 306 A00 += 19 / 2 ^ 255 * C11 C00 = A00 + 3 * 2 ^ 73 - 3 * 2 ^ 73 A01 += C00 C01 = A01 + 3 * 2 ^ 94 - 3 * 2 ^ 94 A02 += C01 C02 = A02 + 3 * 2 ^ 115 - 3 * 2 ^ 115 A03 += C02 C03 = A03 + 3 * 2 ^ 136 - 3 * 2 ^ 136 A04 += C03 C04 = A04 + 3 * 2 ^ 158 - 3 * 2 ^ 158 A05 += C04 C05 = A05 + 3 * 2 ^ 179 - 3 * 2 ^ 179 A06 += C05 C06 = A06 + 3 * 2 ^ 200 - 3 * 2 ^ 200 A07 += C06 C07 = A07 + 3 * 2 ^ 221 - 3 * 2 ^ 221 A08 += C07 C08 = A08 + 3 * 2 ^ 243 - 3 * 2 ^ 243 A09 += C08 C09 = A09 + 3 * 2 ^ 264 - 3 * 2 ^ 264 A10 += C09 C10 = A10 + 3 * 2 ^ 285 - 3 * 2 ^ 285 A11 = A11 - C11 + C10 C11 = A11 + 3 * 2 ^ 306 - 3 * 2 ^ 306 local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 - C00 + 19 / 2 ^ 255 * C11) buffer.writef64(Buf, 8, A01 - C01) buffer.writef64(Buf, 16, A02 - C02) buffer.writef64(Buf, 24, A03 - C03) buffer.writef64(Buf, 32, A04 - C04) buffer.writef64(Buf, 40, A05 - C05) buffer.writef64(Buf, 48, A06 - C06) buffer.writef64(Buf, 56, A07 - C07) buffer.writef64(Buf, 64, A08 - C08) buffer.writef64(Buf, 72, A09 - C09) buffer.writef64(Buf, 80, A10 - C10) buffer.writef64(Buf, 88, A11 - C11) return Buf end function FieldPrime.NSquare(ElementA: buffer, SquareCount: number, StoreInBuffer: boolean?): buffer local Square = FieldPrime.Square if StoreInBuffer then for _ = 1, SquareCount do Square(ElementA, ElementA) end return ElementA else for _ = 1, SquareCount do ElementA = Square(ElementA) end return ElementA end end function FieldPrime.Invert(ElementA: buffer, Storage: buffer?): buffer local Mul = FieldPrime.Mul local A2 = FieldPrime.Square(ElementA) local A9 = Mul(ElementA, FieldPrime.NSquare(A2, 2)) local A11 = Mul(A9, A2) local X5 = Mul(FieldPrime.Square(A11), A9) local X10 = Mul(FieldPrime.NSquare(X5, 5), X5) local X20 = Mul(FieldPrime.NSquare(X10, 10), X10) local X40 = Mul(FieldPrime.NSquare(X20, 20), X20) local X50 = Mul(FieldPrime.NSquare(X40, 10), X10) local X100 = Mul(FieldPrime.NSquare(X50, 50), X50) local X200 = Mul(FieldPrime.NSquare(X100, 100), X100) local X250 = Mul(FieldPrime.NSquare(X200, 50), X50) return Mul(FieldPrime.NSquare(X250, 5), A11, Storage) end function FieldPrime.SqrtDiv(ElementU: buffer, ElementV: buffer): buffer? local Mul = FieldPrime.Mul local Square = FieldPrime.Square local Carry = FieldPrime.Carry Carry(ElementU, ElementU) local V2 = Square(ElementV) local V3 = Mul(ElementV, V2) local UV3 = Mul(ElementU, V3) local V4 = Square(V2) local UV7 = Mul(UV3, V4) local X2 = Mul(Square(UV7), UV7) local X4 = Mul(FieldPrime.NSquare(X2, 2), X2) local X8 = Mul(FieldPrime.NSquare(X4, 4), X4) local X16 = Mul(FieldPrime.NSquare(X8, 8), X8) local X18 = Mul(FieldPrime.NSquare(X16, 2), X2) local X32 = Mul(FieldPrime.NSquare(X16, 16), X16) local X50 = Mul(FieldPrime.NSquare(X32, 18), X18) local X100 = Mul(FieldPrime.NSquare(X50, 50), X50) local X200 = Mul(FieldPrime.NSquare(X100, 100), X100) local X250 = Mul(FieldPrime.NSquare(X200, 50), X50) local PowerResult = Mul(FieldPrime.NSquare(X250, 2), UV7) local CandidateB = Mul(UV3, PowerResult) local B2 = Square(CandidateB) local VB2 = Mul(ElementV, B2) if not FieldPrime.Eq(VB2, ElementU) then CandidateB = Mul(CandidateB, SQUARES) B2 = Square(CandidateB) VB2 = Mul(ElementV, B2) end if FieldPrime.Eq(VB2, ElementU) then return CandidateB else return nil end end function FieldPrime.Encode(ElementA: buffer): buffer ElementA = FieldPrime.Canonicalize(ElementA) local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10, A11 = buffer.readf64(ElementA, 0), buffer.readf64(ElementA, 8), buffer.readf64(ElementA, 16), buffer.readf64(ElementA, 24), buffer.readf64(ElementA, 32), buffer.readf64(ElementA, 40), buffer.readf64(ElementA, 48), buffer.readf64(ElementA, 56), buffer.readf64(ElementA, 64), buffer.readf64(ElementA, 72), buffer.readf64(ElementA, 80), buffer.readf64(ElementA, 88) local Buf = buffer.create(32) local ByteIndex = 0 local Accumulator = A00 local Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 local Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Accumulator += A01 / 2 ^ 16 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 local Byte2 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte2) Accumulator = (Accumulator - Byte2) / 256 ByteIndex += 1 Accumulator += A02 / 2 ^ 40 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Byte2 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte2) Accumulator = (Accumulator - Byte2) / 256 ByteIndex += 1 Accumulator += A03 / 2 ^ 64 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Accumulator += A04 / 2 ^ 80 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Byte2 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte2) Accumulator = (Accumulator - Byte2) / 256 ByteIndex += 1 Accumulator += A05 / 2 ^ 104 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Byte2 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte2) Accumulator = (Accumulator - Byte2) / 256 ByteIndex += 1 Accumulator += A06 / 2 ^ 128 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Accumulator += A07 / 2 ^ 144 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Byte2 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte2) Accumulator = (Accumulator - Byte2) / 256 ByteIndex += 1 Accumulator += A08 / 2 ^ 168 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Byte2 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte2) Accumulator = (Accumulator - Byte2) / 256 ByteIndex += 1 Accumulator += A09 / 2 ^ 192 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Accumulator += A10 / 2 ^ 208 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Byte2 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte2) Accumulator = (Accumulator - Byte2) / 256 ByteIndex += 1 Accumulator += A11 / 2 ^ 232 Byte0 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte0) Accumulator = (Accumulator - Byte0) / 256 ByteIndex += 1 Byte1 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte1) Accumulator = (Accumulator - Byte1) / 256 ByteIndex += 1 Byte2 = Accumulator % 256 buffer.writeu8(Buf, ByteIndex, Byte2) return Buf end function FieldPrime.Decode(EncodedBytes: buffer): buffer local B0, B1, B2 = buffer.readu8(EncodedBytes, 0), buffer.readu8(EncodedBytes, 1), buffer.readu8(EncodedBytes, 2) local W00 = B0 + B1 * 256 + B2 * 65536 B0, B1, B2 = buffer.readu8(EncodedBytes, 3), buffer.readu8(EncodedBytes, 4), buffer.readu8(EncodedBytes, 5) local W01 = B0 + B1 * 256 + B2 * 65536 local W02 = buffer.readu16(EncodedBytes, 6) B0, B1, B2 = buffer.readu8(EncodedBytes, 8), buffer.readu8(EncodedBytes, 9), buffer.readu8(EncodedBytes, 10) local W03 = B0 + B1 * 256 + B2 * 65536 B0, B1, B2 = buffer.readu8(EncodedBytes, 11), buffer.readu8(EncodedBytes, 12), buffer.readu8(EncodedBytes, 13) local W04 = B0 + B1 * 256 + B2 * 65536 local W05 = buffer.readu16(EncodedBytes, 14) B0, B1, B2 = buffer.readu8(EncodedBytes, 16), buffer.readu8(EncodedBytes, 17), buffer.readu8(EncodedBytes, 18) local W06 = B0 + B1 * 256 + B2 * 65536 B0, B1, B2 = buffer.readu8(EncodedBytes, 19), buffer.readu8(EncodedBytes, 20), buffer.readu8(EncodedBytes, 21) local W07 = B0 + B1 * 256 + B2 * 65536 local W08 = buffer.readu16(EncodedBytes, 22) B0, B1, B2 = buffer.readu8(EncodedBytes, 24), buffer.readu8(EncodedBytes, 25), buffer.readu8(EncodedBytes, 26) local W09 = B0 + B1 * 256 + B2 * 65536 B0, B1, B2 = buffer.readu8(EncodedBytes, 27), buffer.readu8(EncodedBytes, 28), buffer.readu8(EncodedBytes, 29) local W10 = B0 + B1 * 256 + B2 * 65536 local W11 = buffer.readu16(EncodedBytes, 30) % 32768 local Buf = buffer.create(SIZE) buffer.writef64(Buf, 0, W00) buffer.writef64(Buf, 8, W01 * 2 ^ 24) buffer.writef64(Buf, 16, W02 * 2 ^ 48) buffer.writef64(Buf, 24, W03 * 2 ^ 64) buffer.writef64(Buf, 32, W04 * 2 ^ 88) buffer.writef64(Buf, 40, W05 * 2 ^ 112) buffer.writef64(Buf, 48, W06 * 2 ^ 128) buffer.writef64(Buf, 56, W07 * 2 ^ 152) buffer.writef64(Buf, 64, W08 * 2 ^ 176) buffer.writef64(Buf, 72, W09 * 2 ^ 192) buffer.writef64(Buf, 80, W10 * 2 ^ 216) buffer.writef64(Buf, 88, W11 * 2 ^ 240) return FieldPrime.Carry(Buf, Buf) end function FieldPrime.Eqz(ElementA: buffer): boolean local Canonical = FieldPrime.Canonicalize(ElementA) local C00, C01, C02, C03, C04, C05, C06, C07, C08, C09, C10, C11 = buffer.readf64(Canonical, 0), buffer.readf64(Canonical, 8), buffer.readf64(Canonical, 16), buffer.readf64(Canonical, 24), buffer.readf64(Canonical, 32), buffer.readf64(Canonical, 40), buffer.readf64(Canonical, 48), buffer.readf64(Canonical, 56), buffer.readf64(Canonical, 64), buffer.readf64(Canonical, 72), buffer.readf64(Canonical, 80), buffer.readf64(Canonical, 88) return C00 + C01 + C02 + C03 + C04 + C05 + C06 + C07 + C08 + C09 + C10 + C11 == 0 end return FieldPrime
12,113
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/FieldQuadratic.luau
--[=[ Cryptography library: Field Quadratic (Curve25519 Scalar Field) Return type: varies by function Example usage: local FieldQuadratic = require("FieldQuadratic") --------Usage Case 1: Basic scalar arithmetic-------- local ScalarA = FieldQuadratic.Decode(SomeBytes) local ScalarB = FieldQuadratic.Decode(OtherBytes) local Sum = FieldQuadratic.Add(ScalarA, ScalarB) local Product = FieldQuadratic.Mul(ScalarA, ScalarB) --------Usage Case 2: Convert to bits for scalar multiplication-------- local ScalarBits = FieldQuadratic.Bits(ScalarA) local EncodedResult = FieldQuadratic.Encode(Product) --]=] --!strict --!optimize 2 --!native local MultiPrecision = require("./MultiPrecision") local CONSTANT_ZERO = MultiPrecision.Num(0) local OUTPUT_BUFFER = buffer.create(8192) local RULE_BUFFER = buffer.create(8192) local DECODE_WIDE_LOW = buffer.create(96) local DECODE_WIDE_HIGH = buffer.create(96) local DECODE_BUFFER = buffer.create(96) local CLAMPED_BUFFER = buffer.create(32) local FIELD_ORDER_BYTES = buffer.create(32) do local Bytes = { 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 } for Index = 1, 32 do buffer.writeu8(FIELD_ORDER_BYTES, Index - 1, Bytes[Index]) end end local FIELD_ORDER = buffer.create(96) do local ByteIndex = 0 for LimbIndex = 0, 9 do local Value = buffer.readu8(FIELD_ORDER_BYTES, ByteIndex) + buffer.readu8(FIELD_ORDER_BYTES, ByteIndex + 1) * 256 + buffer.readu8(FIELD_ORDER_BYTES, ByteIndex + 2) * 65536 buffer.writef64(FIELD_ORDER, LimbIndex * 8, Value) ByteIndex += 3 end local LastValue = buffer.readu8(FIELD_ORDER_BYTES, 30) + buffer.readu8(FIELD_ORDER_BYTES, 31) * 256 buffer.writef64(FIELD_ORDER, 10 * 8, LastValue) end local MONTGOMERY_T0 = buffer.create(96) do local Values = { 05537307, 01942290, 16765621, 16628356, 10618610, 07072433, 03735459, 01369940, 15276086, 13038191, 13409718 } for Index = 1, 11 do buffer.writef64(MONTGOMERY_T0, (Index - 1) * 8, Values[Index]) end end local MONTGOMERY_T1 = buffer.create(96) do local Values = { 11711996, 01747860, 08326961, 03814718, 01859974, 13327461, 16105061, 07590423, 04050668, 08138906, 00000283 } for Index = 1, 11 do buffer.writef64(MONTGOMERY_T1, (Index - 1) * 8, Values[Index]) end end local DIVIDE_8 = buffer.create(96) do local Values = { 5110253, 3039345, 2503500, 11779568, 15416472, 16766550, 16777215, 16777215, 16777215, 16777215, 4095 } for Index = 1, 11 do buffer.writef64(DIVIDE_8, (Index - 1) * 8, Values[Index]) end end local function Reduce(LargeNumber: buffer): buffer local Difference = MultiPrecision.Sub(LargeNumber, FIELD_ORDER) if MultiPrecision.Approx(Difference) < 0 then return MultiPrecision.Carry(LargeNumber) end return MultiPrecision.Carry(Difference) end local function Demontgomery(MontgomeryScalar: buffer): buffer local ReductionLow, ReductionHigh = MultiPrecision.Mul(MultiPrecision.LMul(MontgomeryScalar, MONTGOMERY_T0), FIELD_ORDER) local _, ResultHigh = MultiPrecision.DWAdd(MontgomeryScalar, CONSTANT_ZERO, ReductionLow, ReductionHigh) return Reduce(ResultHigh) end local function RebaseLE(InputBuffer: buffer, InputLength: number, FromBase: number, ToBase: number): (buffer, number) local OutputLength = 0 local Accumulator = 0 local Multiplier = 1 for Index = 0, InputLength - 1 do Accumulator += buffer.readf64(InputBuffer, Index * 8) * Multiplier Multiplier *= FromBase while Multiplier >= ToBase do local Remainder = Accumulator % ToBase Accumulator = (Accumulator - Remainder) / ToBase Multiplier /= ToBase buffer.writef64(OUTPUT_BUFFER, OutputLength * 8, Remainder) OutputLength += 1 end end if Multiplier > 0 then buffer.writef64(OUTPUT_BUFFER, OutputLength * 8, Accumulator) OutputLength += 1 end return OUTPUT_BUFFER, OutputLength end local FieldQuadratic = {} function FieldQuadratic.IsValidScalar(ScalarBytes: buffer): boolean local FieldOrder = FIELD_ORDER_BYTES local Borrow = 0 for Index = 0, 31 do local ScalarByte = buffer.readu8(ScalarBytes, Index) local OrderByte = buffer.readu8(FieldOrder, Index) local Diff = ScalarByte - OrderByte - Borrow Borrow = 1 - bit32.rshift(Diff + 256, 8) end return Borrow == 1 end function FieldQuadratic.Montgomery(RegularScalar: buffer): buffer return FieldQuadratic.Mul(RegularScalar, MONTGOMERY_T1) end function FieldQuadratic.Add(ScalarA: buffer, ScalarB: buffer): buffer return Reduce(MultiPrecision.Add(ScalarA, ScalarB)) end function FieldQuadratic.Neg(ScalarA: buffer): buffer return Reduce(MultiPrecision.Sub(FIELD_ORDER, ScalarA)) end function FieldQuadratic.Sub(ScalarA: buffer, ScalarB: buffer): buffer return FieldQuadratic.Add(ScalarA, FieldQuadratic.Neg(ScalarB)) end function FieldQuadratic.Mul(ScalarA: buffer, ScalarB: buffer): buffer local ProductLow, ProductHigh = MultiPrecision.Mul(ScalarA, ScalarB) local ReductionLow, ReductionHigh = MultiPrecision.Mul(MultiPrecision.LMul(ProductLow, MONTGOMERY_T0), FIELD_ORDER) local _, ResultHigh = MultiPrecision.DWAdd(ProductLow, ProductHigh, ReductionLow, ReductionHigh) return Reduce(ResultHigh) end function FieldQuadratic.Encode(MontgomeryScalar: buffer): buffer local DemontResult = Demontgomery(MontgomeryScalar) local EncodedBuffer = buffer.create(32) local ByteIndex = 0 for LimbIndex = 0, 9 do local Value = buffer.readf64(DemontResult, LimbIndex * 8) buffer.writeu8(EncodedBuffer, ByteIndex, Value % 256) Value = Value // 256 buffer.writeu8(EncodedBuffer, ByteIndex + 1, Value % 256) Value = Value // 256 buffer.writeu8(EncodedBuffer, ByteIndex + 2, Value % 256) ByteIndex += 3 end local LastValue = buffer.readf64(DemontResult, 10 * 8) buffer.writeu8(EncodedBuffer, 30, LastValue % 256) LastValue = LastValue // 256 buffer.writeu8(EncodedBuffer, 31, LastValue % 256) return EncodedBuffer end function FieldQuadratic.Decode(EncodedBuffer: buffer): buffer local DecodedBuffer = DECODE_BUFFER local ByteIndex = 0 for LimbIndex = 0, 9 do local Value = buffer.readu8(EncodedBuffer, ByteIndex) + buffer.readu8(EncodedBuffer, ByteIndex + 1) * 256 + buffer.readu8(EncodedBuffer, ByteIndex + 2) * 65536 buffer.writef64(DecodedBuffer, LimbIndex * 8, Value) ByteIndex += 3 end local LastValue = buffer.readu8(EncodedBuffer, 30) + buffer.readu8(EncodedBuffer, 31) * 256 buffer.writef64(DecodedBuffer, 10 * 8, LastValue) return FieldQuadratic.Montgomery(DecodedBuffer) end function FieldQuadratic.DecodeWide(WideBuffer: buffer): buffer local LowPart = DECODE_WIDE_LOW local HighPart = DECODE_WIDE_HIGH for LimbIndex = 0, 10 do local ByteIndex = LimbIndex * 3 local Value = buffer.readu8(WideBuffer, ByteIndex) + buffer.readu8(WideBuffer, ByteIndex + 1) * 256 + buffer.readu8(WideBuffer, ByteIndex + 2) * 65536 buffer.writef64(LowPart, LimbIndex * 8, Value) end for LimbIndex = 0, 9 do local ByteIndex = 33 + LimbIndex * 3 local Value = buffer.readu8(WideBuffer, ByteIndex) + buffer.readu8(WideBuffer, ByteIndex + 1) * 256 + buffer.readu8(WideBuffer, ByteIndex + 2) * 65536 buffer.writef64(HighPart, LimbIndex * 8, Value) end buffer.writef64(HighPart, 10 * 8, buffer.readu8(WideBuffer, 63)) local MontLow = FieldQuadratic.Montgomery(LowPart) local MontHigh = FieldQuadratic.Montgomery(HighPart) local MontMontHigh = FieldQuadratic.Montgomery(MontHigh) return FieldQuadratic.Add(MontLow, MontMontHigh) end function FieldQuadratic.DecodeClamped(ClampedBuffer: buffer): buffer local ClampedCopy = CLAMPED_BUFFER buffer.copy(ClampedCopy, 0, ClampedBuffer, 0, 32) local FirstByte = buffer.readu8(ClampedCopy, 0) buffer.writeu8(ClampedCopy, 0, bit32.band(FirstByte, 0xF8)) local LastByte = buffer.readu8(ClampedCopy, 31) buffer.writeu8(ClampedCopy, 31, bit32.bor(bit32.band(LastByte, 0x7F), 0x40)) return FieldQuadratic.Decode(ClampedCopy) end function FieldQuadratic.Eighth(MontgomeryScalar: buffer): buffer return FieldQuadratic.Mul(MontgomeryScalar, DIVIDE_8) end function FieldQuadratic.Bits(MontgomeryScalar: buffer): (buffer, number) local DemontResult = Demontgomery(MontgomeryScalar) local BitOutput, BitCount = RebaseLE(DemontResult, 11, 2 ^ 24, 2) if BitCount > 253 then BitCount = 253 end return BitOutput, BitCount end function FieldQuadratic.MakeRuleset(ScalarA: buffer, ScalarB: buffer): (buffer, number, buffer, number) local DTable = Demontgomery(ScalarA) local ETable = Demontgomery(ScalarB) local FTable = MultiPrecision.Sub(DTable, ETable) local DMod2 = MultiPrecision.Mod2(DTable) local EMod2 = MultiPrecision.Mod2(ETable) local DMod3 = MultiPrecision.Mod3(DTable) local EMod3 = MultiPrecision.Mod3(ETable) local EFloat = MultiPrecision.Approx(ETable) local FFloat = MultiPrecision.Approx(FTable) local Mod3Lut = {[0] = 0, 2, 1} local RuleBuffer = RULE_BUFFER local RuleCount = 0 while FFloat ~= 0 do local Rule = -1 if FFloat < 0 then Rule = 0 DTable, ETable = ETable, DTable DMod2, EMod2 = EMod2, DMod2 DMod3, EMod3 = EMod3, DMod3 EFloat = MultiPrecision.Approx(ETable) FTable = MultiPrecision.Sub(DTable, ETable) FFloat = -FFloat elseif 4 * FFloat < EFloat and DMod3 == Mod3Lut[EMod3] then Rule = 1 DTable, ETable = MultiPrecision.Third(MultiPrecision.Add(DTable, FTable)), MultiPrecision.Third(MultiPrecision.Sub(ETable, FTable)) :: buffer DMod2, EMod2 = EMod2, DMod2 DMod3, EMod3 = MultiPrecision.Mod3(DTable), MultiPrecision.Mod3(ETable) EFloat = MultiPrecision.Approx(ETable) elseif 4 * FFloat < EFloat and DMod2 == EMod2 and DMod3 == EMod3 then Rule = 2 DTable = MultiPrecision.Half(FTable) DMod2 = MultiPrecision.Mod2(DTable) DMod3 = Mod3Lut[(DMod3 - EMod3) % 3] FTable = MultiPrecision.Sub(DTable, ETable) FFloat = MultiPrecision.Approx(FTable) elseif FFloat < 3 * EFloat then Rule = 3 DTable = MultiPrecision.CarryWeak(FTable) DMod2 = (DMod2 - EMod2) % 2 DMod3 = (DMod3 - EMod3) % 3 FTable = MultiPrecision.Sub(DTable, ETable) FFloat = MultiPrecision.Approx(FTable) elseif DMod2 == EMod2 then Rule = 2 DTable = MultiPrecision.Half(FTable) DMod2 = MultiPrecision.Mod2(DTable) DMod3 = Mod3Lut[(DMod3 - EMod3) % 3] FTable = MultiPrecision.Sub(DTable, ETable) FFloat = MultiPrecision.Approx(FTable) elseif DMod2 == 0 then Rule = 5 DTable = MultiPrecision.Half(DTable) DMod2 = MultiPrecision.Mod2(DTable) DMod3 = Mod3Lut[DMod3] FTable = MultiPrecision.Sub(DTable, ETable) FFloat = MultiPrecision.Approx(FTable) elseif DMod3 == 0 then Rule = 6 DTable = MultiPrecision.CarryWeak(MultiPrecision.Sub(MultiPrecision.Third(DTable), ETable)) DMod2 = (DMod2 - EMod2) % 2 DMod3 = MultiPrecision.Mod3(DTable) FTable = MultiPrecision.Sub(DTable, ETable) FFloat = MultiPrecision.Approx(FTable) elseif DMod3 == Mod3Lut[EMod3] then Rule = 7 DTable = MultiPrecision.Third(MultiPrecision.Sub(FTable, ETable)) DMod3 = MultiPrecision.Mod3(DTable) FTable = MultiPrecision.Sub(DTable, ETable) FFloat = MultiPrecision.Approx(FTable) elseif DMod3 == EMod3 then Rule = 8 DTable = MultiPrecision.Third(FTable) DMod2 = (DMod2 - EMod2) % 2 DMod3 = MultiPrecision.Mod3(DTable) FTable = MultiPrecision.Sub(DTable, ETable) FFloat = MultiPrecision.Approx(FTable) else Rule = 9 ETable = MultiPrecision.Half(ETable) EMod2 = MultiPrecision.Mod2(ETable) EMod3 = Mod3Lut[EMod3] EFloat = MultiPrecision.Approx(ETable) FTable = MultiPrecision.Sub(DTable, ETable) FFloat = MultiPrecision.Approx(FTable) end buffer.writef64(RuleBuffer, RuleCount * 8, Rule) RuleCount += 1 end local FinalBits, FinalBitCount = RebaseLE(DTable, 11, 2 ^ 24, 2) while FinalBitCount > 0 and buffer.readf64(FinalBits, (FinalBitCount - 1) * 8) == 0 do FinalBitCount -= 1 end return FinalBits, FinalBitCount, RuleBuffer, RuleCount end return FieldQuadratic
3,927
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/MultiPrecision.luau
--[=[ Cryptography library: Multi-Precision Arithmetic (264-bit integers) Return type: varies by function Example usage: local MultiPrecision = require("MultiPrecision") --------Usage Case 1: Basic arithmetic-------- local NumberA = MultiPrecision.Num(42) local NumberB = MultiPrecision.Num(17) local Sum = MultiPrecision.Add(NumberA, NumberB) local Product = MultiPrecision.Mul(NumberA, NumberB) --------Usage Case 2: Carry operations-------- local LargeSum = MultiPrecision.Add(Sum, Product) local Normalized = MultiPrecision.Carry(LargeSum) --]=] --!strict --!optimize 2 --!native local CARRY = 88 local SIZE = 96 local MultiPrecision = {} function MultiPrecision.CarryWeak(LargeNumber: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10 = buffer.readf64(LargeNumber, 0), buffer.readf64(LargeNumber, 8), buffer.readf64(LargeNumber, 16), buffer.readf64(LargeNumber, 24), buffer.readf64(LargeNumber, 32), buffer.readf64(LargeNumber, 40), buffer.readf64(LargeNumber, 48), buffer.readf64(LargeNumber, 56), buffer.readf64(LargeNumber, 64), buffer.readf64(LargeNumber, 72), buffer.readf64(LargeNumber, 80) local Carry00 = A00 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A01 += Carry00 * 2 ^ -24 local Carry01 = A01 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A02 += Carry01 * 2 ^ -24 local Carry02 = A02 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A03 += Carry02 * 2 ^ -24 local Carry03 = A03 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A04 += Carry03 * 2 ^ -24 local Carry04 = A04 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A05 += Carry04 * 2 ^ -24 local Carry05 = A05 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A06 += Carry05 * 2 ^ -24 local Carry06 = A06 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A07 += Carry06 * 2 ^ -24 local Carry07 = A07 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A08 += Carry07 * 2 ^ -24 local Carry08 = A08 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A09 += Carry08 * 2 ^ -24 local Carry09 = A09 + 3 * 2 ^ 75 - 3 * 2 ^ 75; A10 += Carry09 * 2 ^ -24 local Carry10 = A10 + 3 * 2 ^ 75 - 3 * 2 ^ 75 local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 - Carry00) buffer.writef64(Buf, 8, A01 - Carry01) buffer.writef64(Buf, 16, A02 - Carry02) buffer.writef64(Buf, 24, A03 - Carry03) buffer.writef64(Buf, 32, A04 - Carry04) buffer.writef64(Buf, 40, A05 - Carry05) buffer.writef64(Buf, 48, A06 - Carry06) buffer.writef64(Buf, 56, A07 - Carry07) buffer.writef64(Buf, 64, A08 - Carry08) buffer.writef64(Buf, 72, A09 - Carry09) buffer.writef64(Buf, 80, A10 - Carry10) buffer.writef64(Buf, 88, Carry10 * 2 ^ -24) return Buf end function MultiPrecision.Carry(LargeNumber: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10 = buffer.readf64(LargeNumber, 0), buffer.readf64(LargeNumber, 8), buffer.readf64(LargeNumber, 16), buffer.readf64(LargeNumber, 24), buffer.readf64(LargeNumber, 32), buffer.readf64(LargeNumber, 40), buffer.readf64(LargeNumber, 48), buffer.readf64(LargeNumber, 56), buffer.readf64(LargeNumber, 64), buffer.readf64(LargeNumber, 72), buffer.readf64(LargeNumber, 80) local Low00 = A00 % 2 ^ 24; A01 += (A00 - Low00) * 2 ^ -24 local Low01 = A01 % 2 ^ 24; A02 += (A01 - Low01) * 2 ^ -24 local Low02 = A02 % 2 ^ 24; A03 += (A02 - Low02) * 2 ^ -24 local Low03 = A03 % 2 ^ 24; A04 += (A03 - Low03) * 2 ^ -24 local Low04 = A04 % 2 ^ 24; A05 += (A04 - Low04) * 2 ^ -24 local Low05 = A05 % 2 ^ 24; A06 += (A05 - Low05) * 2 ^ -24 local Low06 = A06 % 2 ^ 24; A07 += (A06 - Low06) * 2 ^ -24 local Low07 = A07 % 2 ^ 24; A08 += (A07 - Low07) * 2 ^ -24 local Low08 = A08 % 2 ^ 24; A09 += (A08 - Low08) * 2 ^ -24 local Low09 = A09 % 2 ^ 24; A10 += (A09 - Low09) * 2 ^ -24 local Low10 = A10 % 2 ^ 24 local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, Low00) buffer.writef64(Buf, 8, Low01) buffer.writef64(Buf, 16, Low02) buffer.writef64(Buf, 24, Low03) buffer.writef64(Buf, 32, Low04) buffer.writef64(Buf, 40, Low05) buffer.writef64(Buf, 48, Low06) buffer.writef64(Buf, 56, Low07) buffer.writef64(Buf, 64, Low08) buffer.writef64(Buf, 72, Low09) buffer.writef64(Buf, 80, Low10) buffer.writef64(Buf, 88, (A10 - Low10) * 2 ^ -24) return Buf end function MultiPrecision.Add(NumberA: buffer, NumberB: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10 = buffer.readf64(NumberA, 0), buffer.readf64(NumberA, 8), buffer.readf64(NumberA, 16), buffer.readf64(NumberA, 24), buffer.readf64(NumberA, 32), buffer.readf64(NumberA, 40), buffer.readf64(NumberA, 48), buffer.readf64(NumberA, 56), buffer.readf64(NumberA, 64), buffer.readf64(NumberA, 72), buffer.readf64(NumberA, 80) local B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10 = buffer.readf64(NumberB, 0), buffer.readf64(NumberB, 8), buffer.readf64(NumberB, 16), buffer.readf64(NumberB, 24), buffer.readf64(NumberB, 32), buffer.readf64(NumberB, 40), buffer.readf64(NumberB, 48), buffer.readf64(NumberB, 56), buffer.readf64(NumberB, 64), buffer.readf64(NumberB, 72), buffer.readf64(NumberB, 80) local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 + B00) buffer.writef64(Buf, 8, A01 + B01) buffer.writef64(Buf, 16, A02 + B02) buffer.writef64(Buf, 24, A03 + B03) buffer.writef64(Buf, 32, A04 + B04) buffer.writef64(Buf, 40, A05 + B05) buffer.writef64(Buf, 48, A06 + B06) buffer.writef64(Buf, 56, A07 + B07) buffer.writef64(Buf, 64, A08 + B08) buffer.writef64(Buf, 72, A09 + B09) buffer.writef64(Buf, 80, A10 + B10) return Buf end function MultiPrecision.Sub(NumberA: buffer, NumberB: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10 = buffer.readf64(NumberA, 0), buffer.readf64(NumberA, 8), buffer.readf64(NumberA, 16), buffer.readf64(NumberA, 24), buffer.readf64(NumberA, 32), buffer.readf64(NumberA, 40), buffer.readf64(NumberA, 48), buffer.readf64(NumberA, 56), buffer.readf64(NumberA, 64), buffer.readf64(NumberA, 72), buffer.readf64(NumberA, 80) local B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10 = buffer.readf64(NumberB, 0), buffer.readf64(NumberB, 8), buffer.readf64(NumberB, 16), buffer.readf64(NumberB, 24), buffer.readf64(NumberB, 32), buffer.readf64(NumberB, 40), buffer.readf64(NumberB, 48), buffer.readf64(NumberB, 56), buffer.readf64(NumberB, 64), buffer.readf64(NumberB, 72), buffer.readf64(NumberB, 80) local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 - B00) buffer.writef64(Buf, 8, A01 - B01) buffer.writef64(Buf, 16, A02 - B02) buffer.writef64(Buf, 24, A03 - B03) buffer.writef64(Buf, 32, A04 - B04) buffer.writef64(Buf, 40, A05 - B05) buffer.writef64(Buf, 48, A06 - B06) buffer.writef64(Buf, 56, A07 - B07) buffer.writef64(Buf, 64, A08 - B08) buffer.writef64(Buf, 72, A09 - B09) buffer.writef64(Buf, 80, A10 - B10) return Buf end function MultiPrecision.LMul(NumberA: buffer, NumberB: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10 = buffer.readf64(NumberA, 0), buffer.readf64(NumberA, 8), buffer.readf64(NumberA, 16), buffer.readf64(NumberA, 24), buffer.readf64(NumberA, 32), buffer.readf64(NumberA, 40), buffer.readf64(NumberA, 48), buffer.readf64(NumberA, 56), buffer.readf64(NumberA, 64), buffer.readf64(NumberA, 72), buffer.readf64(NumberA, 80) local B00, B01, B02, B03, B04, B05, B06, B07, B08, B09, B10 = buffer.readf64(NumberB, 0), buffer.readf64(NumberB, 8), buffer.readf64(NumberB, 16), buffer.readf64(NumberB, 24), buffer.readf64(NumberB, 32), buffer.readf64(NumberB, 40), buffer.readf64(NumberB, 48), buffer.readf64(NumberB, 56), buffer.readf64(NumberB, 64), buffer.readf64(NumberB, 72), buffer.readf64(NumberB, 80) local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 * B00) buffer.writef64(Buf, 8, A01 * B00 + A00 * B01) buffer.writef64(Buf, 16, A02 * B00 + A01 * B01 + A00 * B02) buffer.writef64(Buf, 24, A03 * B00 + A02 * B01 + A01 * B02 + A00 * B03) buffer.writef64(Buf, 32, A04 * B00 + A03 * B01 + A02 * B02 + A01 * B03 + A00 * B04) buffer.writef64(Buf, 40, A05 * B00 + A04 * B01 + A03 * B02 + A02 * B03 + A01 * B04 + A00 * B05) buffer.writef64(Buf, 48, A06 * B00 + A05 * B01 + A04 * B02 + A03 * B03 + A02 * B04 + A01 * B05 + A00 * B06) buffer.writef64(Buf, 56, A07 * B00 + A06 * B01 + A05 * B02 + A04 * B03 + A03 * B04 + A02 * B05 + A01 * B06 + A00 * B07) buffer.writef64(Buf, 64, A08 * B00 + A07 * B01 + A06 * B02 + A05 * B03 + A04 * B04 + A03 * B05 + A02 * B06 + A01 * B07 + A00 * B08) buffer.writef64(Buf, 72, A09 * B00 + A08 * B01 + A07 * B02 + A06 * B03 + A05 * B04 + A04 * B05 + A03 * B06 + A02 * B07 + A01 * B08 + A00 * B09) buffer.writef64(Buf, 80, A10 * B00 + A09 * B01 + A08 * B02 + A07 * B03 + A06 * B04 + A05 * B05 + A04 * B06 + A03 * B07 + A02 * B08 + A01 * B09 + A00 * B10) return MultiPrecision.Carry(Buf, Buf) end function MultiPrecision.Mul(NumberA: buffer, NumberB: buffer, LowStorage: buffer?, HighStorage: buffer?): (buffer, buffer) local LowResult = MultiPrecision.LMul(NumberA, NumberB, LowStorage) local Overflow = buffer.readf64(LowResult, CARRY) local A01, A02, A03, A04, A05, A06, A07, A08, A09, A10 = buffer.readf64(NumberA, 8), buffer.readf64(NumberA, 16), buffer.readf64(NumberA, 24), buffer.readf64(NumberA, 32), buffer.readf64(NumberA, 40), buffer.readf64(NumberA, 48), buffer.readf64(NumberA, 56), buffer.readf64(NumberA, 64), buffer.readf64(NumberA, 72), buffer.readf64(NumberA, 80) local B01, B02, B03, B04, B05, B06, B07, B08, B09, B10 = buffer.readf64(NumberB, 8), buffer.readf64(NumberB, 16), buffer.readf64(NumberB, 24), buffer.readf64(NumberB, 32), buffer.readf64(NumberB, 40), buffer.readf64(NumberB, 48), buffer.readf64(NumberB, 56), buffer.readf64(NumberB, 64), buffer.readf64(NumberB, 72), buffer.readf64(NumberB, 80) local Buf = HighStorage or buffer.create(SIZE) buffer.writef64(Buf, 0, Overflow + A10 * B01 + A09 * B02 + A08 * B03 + A07 * B04 + A06 * B05 + A05 * B06 + A04 * B07 + A03 * B08 + A02 * B09 + A01 * B10) buffer.writef64(Buf, 8, A10 * B02 + A09 * B03 + A08 * B04 + A07 * B05 + A06 * B06 + A05 * B07 + A04 * B08 + A03 * B09 + A02 * B10) buffer.writef64(Buf, 16, A10 * B03 + A09 * B04 + A08 * B05 + A07 * B06 + A06 * B07 + A05 * B08 + A04 * B09 + A03 * B10) buffer.writef64(Buf, 24, A10 * B04 + A09 * B05 + A08 * B06 + A07 * B07 + A06 * B08 + A05 * B09 + A04 * B10) buffer.writef64(Buf, 32, A10 * B05 + A09 * B06 + A08 * B07 + A07 * B08 + A06 * B09 + A05 * B10) buffer.writef64(Buf, 40, A10 * B06 + A09 * B07 + A08 * B08 + A07 * B09 + A06 * B10) buffer.writef64(Buf, 48, A10 * B07 + A09 * B08 + A08 * B09 + A07 * B10) buffer.writef64(Buf, 56, A10 * B08 + A09 * B09 + A08 * B10) buffer.writef64(Buf, 64, A10 * B09 + A09 * B10) buffer.writef64(Buf, 72, A10 * B10) buffer.writef64(Buf, 80, 0) return LowResult, MultiPrecision.Carry(Buf, Buf) end function MultiPrecision.DWAdd(NumberA0: buffer, NumberA1: buffer, NumberB0: buffer, NumberB1: buffer, LowStorage: buffer?, HighStorage: buffer?): (buffer, buffer, number) local LowSum = MultiPrecision.Carry(MultiPrecision.Add(NumberA0, NumberB0, LowStorage), LowStorage) local CarryOut = buffer.readf64(LowSum, CARRY) local HighSum = MultiPrecision.Add(NumberA1, NumberB1, HighStorage) buffer.writef64(HighSum, 0, buffer.readf64(HighSum, 0) + CarryOut) local Carried = MultiPrecision.Carry(HighSum, HighSum) return LowSum, Carried, buffer.readf64(Carried, CARRY) end function MultiPrecision.Half(NumberA: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10 = buffer.readf64(NumberA, 0), buffer.readf64(NumberA, 8), buffer.readf64(NumberA, 16), buffer.readf64(NumberA, 24), buffer.readf64(NumberA, 32), buffer.readf64(NumberA, 40), buffer.readf64(NumberA, 48), buffer.readf64(NumberA, 56), buffer.readf64(NumberA, 64), buffer.readf64(NumberA, 72), buffer.readf64(NumberA, 80) local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 * 0.5 + A01 * 2 ^ 23) buffer.writef64(Buf, 8, A02 * 2 ^ 23) buffer.writef64(Buf, 16, A03 * 2 ^ 23) buffer.writef64(Buf, 24, A04 * 2 ^ 23) buffer.writef64(Buf, 32, A05 * 2 ^ 23) buffer.writef64(Buf, 40, A06 * 2 ^ 23) buffer.writef64(Buf, 48, A07 * 2 ^ 23) buffer.writef64(Buf, 56, A08 * 2 ^ 23) buffer.writef64(Buf, 64, A09 * 2 ^ 23) buffer.writef64(Buf, 72, A10 * 2 ^ 23) buffer.writef64(Buf, 80, 0) return MultiPrecision.CarryWeak(Buf, Buf) end function MultiPrecision.Third(NumberA: buffer, Storage: buffer?): buffer local A00, A01, A02, A03, A04, A05, A06, A07, A08, A09, A10 = buffer.readf64(NumberA, 0), buffer.readf64(NumberA, 8), buffer.readf64(NumberA, 16), buffer.readf64(NumberA, 24), buffer.readf64(NumberA, 32), buffer.readf64(NumberA, 40), buffer.readf64(NumberA, 48), buffer.readf64(NumberA, 56), buffer.readf64(NumberA, 64), buffer.readf64(NumberA, 72), buffer.readf64(NumberA, 80) local Division00 = A00 * 0xaaaaaa local Division01 = A01 * 0xaaaaaa + Division00 local Division02 = A02 * 0xaaaaaa + Division01 local Division03 = A03 * 0xaaaaaa + Division02 local Division04 = A04 * 0xaaaaaa + Division03 local Division05 = A05 * 0xaaaaaa + Division04 local Division06 = A06 * 0xaaaaaa + Division05 local Division07 = A07 * 0xaaaaaa + Division06 local Division08 = A08 * 0xaaaaaa + Division07 local Division09 = A09 * 0xaaaaaa + Division08 local Division10 = A10 * 0xaaaaaa + Division09 local Buf = Storage or buffer.create(SIZE) buffer.writef64(Buf, 0, A00 + Division00) buffer.writef64(Buf, 8, A01 + Division01) buffer.writef64(Buf, 16, A02 + Division02) buffer.writef64(Buf, 24, A03 + Division03) buffer.writef64(Buf, 32, A04 + Division04) buffer.writef64(Buf, 40, A05 + Division05) buffer.writef64(Buf, 48, A06 + Division06) buffer.writef64(Buf, 56, A07 + Division07) buffer.writef64(Buf, 64, A08 + Division08) buffer.writef64(Buf, 72, A09 + Division09) buffer.writef64(Buf, 80, A10 + Division10) return MultiPrecision.CarryWeak(Buf, Buf) end function MultiPrecision.Mod2(NumberA: buffer): number return buffer.readf64(NumberA, 0) % 2 end function MultiPrecision.Mod3(NumberA: buffer): number return ( buffer.readf64(NumberA, 0) + buffer.readf64(NumberA, 8) + buffer.readf64(NumberA, 16) + buffer.readf64(NumberA, 24) + buffer.readf64(NumberA, 32) + buffer.readf64(NumberA, 40) + buffer.readf64(NumberA, 48) + buffer.readf64(NumberA, 56) + buffer.readf64(NumberA, 64) + buffer.readf64(NumberA, 72) + buffer.readf64(NumberA, 80) ) % 3 end function MultiPrecision.Approx(NumberA: buffer): number return buffer.readf64(NumberA, 0) + buffer.readf64(NumberA, 8) * 2 ^ 24 + buffer.readf64(NumberA, 16) * 2 ^ 48 + buffer.readf64(NumberA, 24) * 2 ^ 72 + buffer.readf64(NumberA, 32) * 2 ^ 96 + buffer.readf64(NumberA, 40) * 2 ^ 120 + buffer.readf64(NumberA, 48) * 2 ^ 144 + buffer.readf64(NumberA, 56) * 2 ^ 168 + buffer.readf64(NumberA, 64) * 2 ^ 192 + buffer.readf64(NumberA, 72) * 2 ^ 216 + buffer.readf64(NumberA, 80) * 2 ^ 240 end function MultiPrecision.Cmp(NumberA: buffer, NumberB: buffer): number return MultiPrecision.Approx(MultiPrecision.Sub(NumberA, NumberB)) end function MultiPrecision.Num(RegularNumber: number): buffer local Buf = buffer.create(SIZE) buffer.writef64(Buf, 0, RegularNumber) return Buf end return MultiPrecision
5,898
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/SHA512.luau
--!strict --!optimize 2 --!native local K_HI = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, 0xca273ece, 0xd186b8c7, 0xeada7dd6, 0xf57d4f7f, 0x06f067aa, 0x0a637dc5, 0x113f9804, 0x1b710b35, 0x28db77f5, 0x32caab7b, 0x3c9ebe0a, 0x431d67c4, 0x4cc5d4be, 0x597f299c, 0x5fcb6fab, 0x6c44198c, } local K_LO = { 0xd728ae22, 0x23ef65cd, 0xec4d3b2f, 0x8189dbbc, 0xf348b538, 0xb605d019, 0xaf194f9b, 0xda6d8118, 0xa3030242, 0x45706fbe, 0x4ee4b28c, 0xd5ffb4e2, 0xf27b896f, 0x3b1696b1, 0x25c71235, 0xcf692694, 0x9ef14ad2, 0x384f25e3, 0x8b8cd5b5, 0x77ac9c65, 0x592b0275, 0x6ea6e483, 0xbd41fbd4, 0x831153b5, 0xee66dfab, 0x2db43210, 0x98fb213f, 0xbeef0ee4, 0x3da88fc2, 0x930aa725, 0xe003826f, 0x0a0e6e70, 0x46d22ffc, 0x5c26c926, 0x5ac42aed, 0x9d95b3df, 0x8baf63de, 0x3c77b2a8, 0x47edaee6, 0x1482353b, 0x4cf10364, 0xbc423001, 0xd0f89791, 0x0654be30, 0xd6ef5218, 0x5565a910, 0x5771202a, 0x32bbd1b8, 0xb8d2d0c8, 0x5141ab53, 0xdf8eeb99, 0xe19b48a8, 0xc5c95a63, 0xe3418acb, 0x7763e373, 0xd6b2b8a3, 0x5defb2fc, 0x43172f60, 0xa1f0ab72, 0x1a6439ec, 0x23631e28, 0xde82bde9, 0xb2c67915, 0xe372532b, 0xea26619c, 0x21c0c207, 0xcde0eb1e, 0xee6ed178, 0x72176fba, 0xa2c898a6, 0xbef90dae, 0x131c471b, 0x23047d84, 0x40c72493, 0x15c9bebc, 0x9c100d4c, 0xcb3e42b6, 0xfc657e2a, 0x3ad6faec, 0x4a475817, } local W_HI = table.create(80) :: {number} local W_LO = table.create(80) :: {number} local RESULT_BUFFER = buffer.create(64) local function PreProcess(Contents: buffer): (buffer, number) local ContentLength = buffer.len(Contents) local Padding = (128 - ((ContentLength + 17) % 128)) % 128 local NewLength = ContentLength + 1 + Padding + 16 local Result = buffer.create(NewLength) buffer.copy(Result, 0, Contents) buffer.writeu8(Result, ContentLength, 0x80) buffer.fill(Result, ContentLength + 1, 0, Padding + 8) local BitLength = ContentLength * 8 local LengthOffset = ContentLength + 1 + Padding + 8 for Index = 7, 0, -1 do buffer.writeu8(Result, LengthOffset + Index, BitLength % 256) BitLength = BitLength // 256 end return Result, NewLength end local function SHA512(Message: buffer): buffer local Blocks, Length = PreProcess(Message) local Hi, Lo = W_HI, W_LO local KHi, KLo = K_HI, K_LO local H1Hi, H2Hi, H3Hi, H4Hi = 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a local H5Hi, H6Hi, H7Hi, H8Hi = 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 local H1Lo, H2Lo, H3Lo, H4Lo = 0xf3bcc908, 0x84caa73b, 0xfe94f82b, 0x5f1d36f1 local H5Lo, H6Lo, H7Lo, H8Lo = 0xade682d1, 0x2b3e6c1f, 0xfb41bd6b, 0x137e2179 for Offset = 0, Length - 1, 128 do for T = 1, 16 do local ByteOffset = Offset + (T - 1) * 8 Hi[T] = bit32.byteswap(buffer.readu32(Blocks, ByteOffset)) Lo[T] = bit32.byteswap(buffer.readu32(Blocks, ByteOffset + 4)) end for T = 17, 80 do local P15Hi, P15Lo = Hi[T - 15], Lo[T - 15] local P2Hi, P2Lo = Hi[T - 2], Lo[T - 2] local S0Lo = bit32.bxor(bit32.rshift(P15Lo, 1) + bit32.lshift(P15Hi, 31), bit32.rshift(P15Lo, 8) + bit32.lshift(P15Hi, 24), bit32.rshift(P15Lo, 7) + bit32.lshift(P15Hi, 25)) local S1Lo = bit32.bxor(bit32.rshift(P2Lo, 19) + bit32.lshift(P2Hi, 13), bit32.lshift(P2Lo, 3) + bit32.rshift(P2Hi, 29), bit32.rshift(P2Lo, 6) + bit32.lshift(P2Hi, 26)) local TmpLo = Lo[T - 16] + S0Lo + Lo[T - 7] + S1Lo Lo[T] = bit32.bor(TmpLo, 0) Hi[T] = bit32.bxor(bit32.rshift(P15Hi, 1) + bit32.lshift(P15Lo, 31), bit32.rshift(P15Hi, 8) + bit32.lshift(P15Lo, 24), bit32.rshift(P15Hi, 7)) + bit32.bxor(bit32.rshift(P2Hi, 19) + bit32.lshift(P2Lo, 13), bit32.lshift(P2Hi, 3) + bit32.rshift(P2Lo, 29), bit32.rshift(P2Hi, 6)) + Hi[T - 16] + Hi[T - 7] + TmpLo // 0x100000000 end local AHi, ALo = H1Hi, H1Lo local BHi, BLo = H2Hi, H2Lo local CHi, CLo = H3Hi, H3Lo local DHi, DLo = H4Hi, H4Lo local EHi, ELo = H5Hi, H5Lo local FHi, FLo = H6Hi, H6Lo local GHi, GLo = H7Hi, H7Lo local HHi, HLo = H8Hi, H8Lo for T = 1, 79, 2 do local Sigma1Lo = bit32.bxor(bit32.rshift(ELo, 14) + bit32.lshift(EHi, 18), bit32.rshift(ELo, 18) + bit32.lshift(EHi, 14), bit32.lshift(ELo, 23) + bit32.rshift(EHi, 9)) local Sigma1Hi = bit32.bxor(bit32.rshift(EHi, 14) + bit32.lshift(ELo, 18), bit32.rshift(EHi, 18) + bit32.lshift(ELo, 14), bit32.lshift(EHi, 23) + bit32.rshift(ELo, 9)) local Sigma0Lo = bit32.bxor(bit32.rshift(ALo, 28) + bit32.lshift(AHi, 4), bit32.lshift(ALo, 30) + bit32.rshift(AHi, 2), bit32.lshift(ALo, 25) + bit32.rshift(AHi, 7)) local Sigma0Hi = bit32.bxor(bit32.rshift(AHi, 28) + bit32.lshift(ALo, 4), bit32.lshift(AHi, 30) + bit32.rshift(ALo, 2), bit32.lshift(AHi, 25) + bit32.rshift(ALo, 7)) local ChLo = bit32.band(ELo, FLo) + bit32.band(-1 - ELo, GLo) local ChHi = bit32.band(EHi, FHi) + bit32.band(-1 - EHi, GHi) local MajLo = bit32.band(CLo, BLo) + bit32.band(ALo, bit32.bxor(CLo, BLo)) local MajHi = bit32.band(CHi, BHi) + bit32.band(AHi, bit32.bxor(CHi, BHi)) local T1Lo = HLo + Sigma1Lo + ChLo + KLo[T] + Lo[T] local T1Hi = HHi + Sigma1Hi + ChHi + KHi[T] + Hi[T] + T1Lo // 0x100000000 T1Lo = bit32.bor(T1Lo, 0) HHi, HLo = GHi, GLo GHi, GLo = FHi, FLo FHi, FLo = EHi, ELo local ELoNew = DLo + T1Lo EHi = DHi + T1Hi + ELoNew // 0x100000000 ELo = bit32.bor(ELoNew, 0) DHi, DLo = CHi, CLo CHi, CLo = BHi, BLo BHi, BLo = AHi, ALo local ALoNew = T1Lo + Sigma0Lo + MajLo AHi = T1Hi + Sigma0Hi + MajHi + ALoNew // 0x100000000 ALo = bit32.bor(ALoNew, 0) local T2 = T + 1 Sigma1Lo = bit32.bxor(bit32.rshift(ELo, 14) + bit32.lshift(EHi, 18), bit32.rshift(ELo, 18) + bit32.lshift(EHi, 14), bit32.lshift(ELo, 23) + bit32.rshift(EHi, 9)) Sigma1Hi = bit32.bxor(bit32.rshift(EHi, 14) + bit32.lshift(ELo, 18), bit32.rshift(EHi, 18) + bit32.lshift(ELo, 14), bit32.lshift(EHi, 23) + bit32.rshift(ELo, 9)) Sigma0Lo = bit32.bxor(bit32.rshift(ALo, 28) + bit32.lshift(AHi, 4), bit32.lshift(ALo, 30) + bit32.rshift(AHi, 2), bit32.lshift(ALo, 25) + bit32.rshift(AHi, 7)) Sigma0Hi = bit32.bxor(bit32.rshift(AHi, 28) + bit32.lshift(ALo, 4), bit32.lshift(AHi, 30) + bit32.rshift(ALo, 2), bit32.lshift(AHi, 25) + bit32.rshift(ALo, 7)) ChLo = bit32.band(ELo, FLo) + bit32.band(-1 - ELo, GLo) ChHi = bit32.band(EHi, FHi) + bit32.band(-1 - EHi, GHi) MajLo = bit32.band(CLo, BLo) + bit32.band(ALo, bit32.bxor(CLo, BLo)) MajHi = bit32.band(CHi, BHi) + bit32.band(AHi, bit32.bxor(CHi, BHi)) T1Lo = HLo + Sigma1Lo + ChLo + KLo[T2] + Lo[T2] T1Hi = HHi + Sigma1Hi + ChHi + KHi[T2] + Hi[T2] + T1Lo // 0x100000000 T1Lo = bit32.bor(T1Lo, 0) HHi, HLo = GHi, GLo GHi, GLo = FHi, FLo FHi, FLo = EHi, ELo ELoNew = DLo + T1Lo EHi = DHi + T1Hi + ELoNew // 0x100000000 ELo = bit32.bor(ELoNew, 0) DHi, DLo = CHi, CLo CHi, CLo = BHi, BLo BHi, BLo = AHi, ALo ALoNew = T1Lo + Sigma0Lo + MajLo AHi = T1Hi + Sigma0Hi + MajHi + ALoNew // 0x100000000 ALo = bit32.bor(ALoNew, 0) end H1Lo = H1Lo + ALo H1Hi = bit32.bor(H1Hi + AHi + H1Lo // 0x100000000, 0) H1Lo = bit32.bor(H1Lo, 0) H2Lo = H2Lo + BLo H2Hi = bit32.bor(H2Hi + BHi + H2Lo // 0x100000000, 0) H2Lo = bit32.bor(H2Lo, 0) H3Lo = H3Lo + CLo H3Hi = bit32.bor(H3Hi + CHi + H3Lo // 0x100000000, 0) H3Lo = bit32.bor(H3Lo, 0) H4Lo = H4Lo + DLo H4Hi = bit32.bor(H4Hi + DHi + H4Lo // 0x100000000, 0) H4Lo = bit32.bor(H4Lo, 0) H5Lo = H5Lo + ELo H5Hi = bit32.bor(H5Hi + EHi + H5Lo // 0x100000000, 0) H5Lo = bit32.bor(H5Lo, 0) H6Lo = H6Lo + FLo H6Hi = bit32.bor(H6Hi + FHi + H6Lo // 0x100000000, 0) H6Lo = bit32.bor(H6Lo, 0) H7Lo = H7Lo + GLo H7Hi = bit32.bor(H7Hi + GHi + H7Lo // 0x100000000, 0) H7Lo = bit32.bor(H7Lo, 0) H8Lo = H8Lo + HLo H8Hi = bit32.bor(H8Hi + HHi + H8Lo // 0x100000000, 0) H8Lo = bit32.bor(H8Lo, 0) end buffer.writeu32(RESULT_BUFFER, 0, bit32.byteswap(H1Hi)) buffer.writeu32(RESULT_BUFFER, 4, bit32.byteswap(H1Lo)) buffer.writeu32(RESULT_BUFFER, 8, bit32.byteswap(H2Hi)) buffer.writeu32(RESULT_BUFFER, 12, bit32.byteswap(H2Lo)) buffer.writeu32(RESULT_BUFFER, 16, bit32.byteswap(H3Hi)) buffer.writeu32(RESULT_BUFFER, 20, bit32.byteswap(H3Lo)) buffer.writeu32(RESULT_BUFFER, 24, bit32.byteswap(H4Hi)) buffer.writeu32(RESULT_BUFFER, 28, bit32.byteswap(H4Lo)) buffer.writeu32(RESULT_BUFFER, 32, bit32.byteswap(H5Hi)) buffer.writeu32(RESULT_BUFFER, 36, bit32.byteswap(H5Lo)) buffer.writeu32(RESULT_BUFFER, 40, bit32.byteswap(H6Hi)) buffer.writeu32(RESULT_BUFFER, 44, bit32.byteswap(H6Lo)) buffer.writeu32(RESULT_BUFFER, 48, bit32.byteswap(H7Hi)) buffer.writeu32(RESULT_BUFFER, 52, bit32.byteswap(H7Lo)) buffer.writeu32(RESULT_BUFFER, 56, bit32.byteswap(H8Hi)) buffer.writeu32(RESULT_BUFFER, 60, bit32.byteswap(H8Lo)) return RESULT_BUFFER end return SHA512
4,655
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/EdDSA/X25519.luau
--[=[ Cryptography library: X25519 with cofactor clearing Return type: varies by function Example usage: local AlicePrivate = CSPRNG.Ed25519Random() local BobPrivate = CSPRNG.Ed25519Random() local AliceMasked = X25519.Mask(AlicePrivate) local BobMasked = X25519.Mask(BobPrivate) local AlicePublic = X25519.PublicKey(AliceMasked) local BobPublic = X25519.PublicKey(BobMasked) local AliceSharedPrimary, AliceEphemeralSecret = X25519.Exchange(AliceMasked, BobPublic) local BobSharedPrimary, BobEphemeralSecret = X25519.Exchange(BobMasked, AlicePublic) Expect(ToHex(AliceSharedPrimary)).ToBe(ToHex(BobSharedPrimary)) Expect(ToHex(AliceEphemeralSecret)).Never.ToBe(ToHex(BobEphemeralSecret)) --]=] --!strict --!optimize 2 --!native local FieldQuadratic = require("./FieldQuadratic") local FieldPrime = require("./FieldPrime") local Curve25519 = require("./Curve25519") local SHA512 = require("./SHA512") local CSPRNG = require("./CSPRNG") local COORD_SIZE = 104 local X25519_SECRET_KEY_SIZE = 32 local X25519_PUBLIC_KEY_SIZE = 32 local X25519_MASKED_KEY_SIZE = 64 local X25519_SIGNATURE_SECRET_KEY_SIZE = 32 local Mask = {} function Mask.Mask(SecretKey: buffer): buffer if SecretKey == nil then error("SecretKey cannot be nil", 2) end if typeof(SecretKey) ~= "buffer" then error(`SecretKey must be a buffer, got {typeof(SecretKey)}`, 2) end local SecretKeyLength = buffer.len(SecretKey) if SecretKeyLength ~= X25519_SECRET_KEY_SIZE then error(`SecretKey must be exactly {X25519_SECRET_KEY_SIZE} bytes long, got {SecretKeyLength} bytes`, 2) end local RandomMask = CSPRNG.Ed25519Random() local ScalarX = FieldQuadratic.DecodeClamped(SecretKey) local ScalarR = FieldQuadratic.DecodeClamped(RandomMask) local MaskedScalar = FieldQuadratic.Sub(ScalarX, ScalarR) local EncodedMaskedScalar = FieldQuadratic.Encode(MaskedScalar) local MaskedKey = buffer.create(64) buffer.copy(MaskedKey, 0, EncodedMaskedScalar, 0, 32) buffer.copy(MaskedKey, 32, RandomMask, 0, 32) return MaskedKey end function Mask.MaskSignature(SignatureSecretKey: buffer): buffer if SignatureSecretKey == nil then error("SignatureSecretKey cannot be nil", 2) end if typeof(SignatureSecretKey) ~= "buffer" then error(`SignatureSecretKey must be a buffer, got {typeof(SignatureSecretKey)}`, 2) end local SignatureKeyLength = buffer.len(SignatureSecretKey) if SignatureKeyLength ~= X25519_SIGNATURE_SECRET_KEY_SIZE then error(`SignatureSecretKey must be exactly {X25519_SIGNATURE_SECRET_KEY_SIZE} bytes long, got {SignatureKeyLength} bytes`, 2) end local HashResult = SHA512(SignatureSecretKey) local FirstHalf = buffer.create(32) buffer.copy(FirstHalf, 0, HashResult, 0, 32) return Mask.Mask(FirstHalf) end function Mask.Remask(MaskedKey: buffer): buffer if MaskedKey == nil then error("MaskedKey cannot be nil", 2) end if typeof(MaskedKey) ~= "buffer" then error(`MaskedKey must be a buffer, got {typeof(MaskedKey)}`, 2) end local MaskedKeyLength = buffer.len(MaskedKey) if MaskedKeyLength ~= X25519_MASKED_KEY_SIZE then error(`MaskedKey must be exactly {X25519_MASKED_KEY_SIZE} bytes long, got {MaskedKeyLength} bytes`, 2) end local NewRandomMask = CSPRNG.Ed25519Random() local MaskedScalarBytes = buffer.create(32) buffer.copy(MaskedScalarBytes, 0, MaskedKey, 0, 32) local MaskedScalar = FieldQuadratic.Decode(MaskedScalarBytes) local OldMaskBytes = buffer.create(32) buffer.copy(OldMaskBytes, 0, MaskedKey, 32, 32) local OldMask = FieldQuadratic.DecodeClamped(OldMaskBytes) local NewMask = FieldQuadratic.DecodeClamped(NewRandomMask) local RemaskedScalar = FieldQuadratic.Add(MaskedScalar, FieldQuadratic.Sub(OldMask, NewMask)) local EncodedRemaskedScalar = FieldQuadratic.Encode(RemaskedScalar) local RemaskedKey = buffer.create(64) buffer.copy(RemaskedKey, 0, EncodedRemaskedScalar, 0, 32) buffer.copy(RemaskedKey, 32, NewRandomMask, 0, 32) return RemaskedKey end function Mask.MaskComponent(MaskedKey: buffer): buffer if MaskedKey == nil then error("MaskedKey cannot be nil", 2) end if typeof(MaskedKey) ~= "buffer" then error(`MaskedKey must be a buffer, got {typeof(MaskedKey)}`, 2) end local MaskedKeyLength = buffer.len(MaskedKey) if MaskedKeyLength ~= X25519_MASKED_KEY_SIZE then error(`MaskedKey must be exactly {X25519_MASKED_KEY_SIZE} bytes long, got {MaskedKeyLength} bytes`, 2) end local MaskKey = buffer.create(32) buffer.copy(MaskKey, 0, MaskedKey, 32, 32) return MaskKey end local function ExchangeOnPoint(MaskedSecretKey: buffer, CurvePoint: buffer): (buffer, buffer) local MaskedScalarBytes = buffer.create(32) buffer.copy(MaskedScalarBytes, 0, MaskedSecretKey, 0, 32) local MaskedScalar = FieldQuadratic.Decode(MaskedScalarBytes) local MaskBytes = buffer.create(32) buffer.copy(MaskBytes, 0, MaskedSecretKey, 32, 32) local MaskScalar = FieldQuadratic.DecodeClamped(MaskBytes) local MaskPoint, MaskedPoint, DifferencePoint = Curve25519.Prac(CurvePoint, {FieldQuadratic.MakeRuleset(FieldQuadratic.Eighth(MaskScalar), FieldQuadratic.Eighth(MaskedScalar))}) if not MaskPoint then error("Invalid public key", 2) end if not DifferencePoint or not MaskedPoint then error("Invalid public key", 2) end local FullScalarPoint = Curve25519.DifferentialAdd(DifferencePoint, MaskPoint, MaskedPoint) local PointX = buffer.create(COORD_SIZE) buffer.copy(PointX, 0, CurvePoint, 0 * COORD_SIZE, COORD_SIZE) local PointZ = buffer.create(COORD_SIZE) buffer.copy(PointZ, 0, CurvePoint, 1 * COORD_SIZE, COORD_SIZE) local FullPointX = buffer.create(COORD_SIZE) buffer.copy(FullPointX, 0, FullScalarPoint, 0 * COORD_SIZE, COORD_SIZE) local FullPointZ = buffer.create(COORD_SIZE) buffer.copy(FullPointZ, 0, FullScalarPoint, 1 * COORD_SIZE, COORD_SIZE) local MaskPointX = buffer.create(COORD_SIZE) buffer.copy(MaskPointX, 0, MaskPoint, 0 * COORD_SIZE, COORD_SIZE) local MaskPointZ = buffer.create(COORD_SIZE) buffer.copy(MaskPointZ, 0, MaskPoint, 1 * COORD_SIZE, COORD_SIZE) PointX, PointZ = FieldPrime.Mul(PointX, PointZ), FieldPrime.Square(PointZ) :: buffer FullPointX, FullPointZ = FieldPrime.Mul(FullPointX, FullPointZ), FieldPrime.Square(FullPointZ) :: buffer MaskPointX, MaskPointZ = FieldPrime.Mul(MaskPointX, MaskPointZ), FieldPrime.Square(MaskPointZ) :: buffer local PointXSquared = FieldPrime.Square(PointX) local PointZSquared = FieldPrime.Square(PointZ) local PointXZ = FieldPrime.Mul(PointX, PointZ) local CurveConstantTerm = FieldPrime.KMul(PointXZ, 486662) local RightHandSide = FieldPrime.Mul(PointX, FieldPrime.Add(PointXSquared, FieldPrime.Carry(FieldPrime.Add(CurveConstantTerm, PointZSquared)))) local SquareRoot = FieldPrime.SqrtDiv(FieldPrime.Num(1), FieldPrime.Mul(FieldPrime.Mul(FullPointZ, MaskPointZ), RightHandSide)) if not SquareRoot then error("Invalid public key", 2) end local CombinedInverse = FieldPrime.Mul(FieldPrime.Square(SquareRoot), RightHandSide) local FullPointZInverse = FieldPrime.Mul(CombinedInverse, MaskPointZ) local MaskPointZInverse = FieldPrime.Mul(CombinedInverse, FullPointZ) return FieldPrime.Encode(FieldPrime.Mul(FullPointX, FullPointZInverse)), FieldPrime.Encode(FieldPrime.Mul(MaskPointX, MaskPointZInverse)) end function Mask.PublicKey(MaskedKey: buffer): buffer if MaskedKey == nil then error("MaskedKey cannot be nil", 2) end if typeof(MaskedKey) ~= "buffer" then error(`MaskedKey must be a buffer, got {typeof(MaskedKey)}`, 2) end local MaskedKeyLength = buffer.len(MaskedKey) if MaskedKeyLength ~= X25519_MASKED_KEY_SIZE then error(`MaskedKey must be exactly {X25519_MASKED_KEY_SIZE} bytes long, got {MaskedKeyLength} bytes`, 2) end return (ExchangeOnPoint(MaskedKey, Curve25519.G)) end function Mask.Exchange(MaskedSecretKey: buffer, TheirPublicKey: buffer): (buffer, buffer) if MaskedSecretKey == nil then error("MaskedSecretKey cannot be nil", 2) end if typeof(MaskedSecretKey) ~= "buffer" then error(`MaskedSecretKey must be a buffer, got {typeof(MaskedSecretKey)}`, 2) end local MaskedSecretKeyLength = buffer.len(MaskedSecretKey) if MaskedSecretKeyLength ~= X25519_MASKED_KEY_SIZE then error(`MaskedSecretKey must be exactly {X25519_MASKED_KEY_SIZE} bytes long, got {MaskedSecretKeyLength} bytes`, 2) end if TheirPublicKey == nil then error("TheirPublicKey cannot be nil", 2) end if typeof(TheirPublicKey) ~= "buffer" then error(`TheirPublicKey must be a buffer, got {typeof(TheirPublicKey)}`, 2) end local TheirPublicKeyLength = buffer.len(TheirPublicKey) if TheirPublicKeyLength ~= X25519_PUBLIC_KEY_SIZE then error(`TheirPublicKey must be exactly {X25519_PUBLIC_KEY_SIZE} bytes long, got {TheirPublicKeyLength} bytes`, 2) end return ExchangeOnPoint(MaskedSecretKey, Curve25519.Decode(TheirPublicKey)) end return Mask
2,513
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/CSPRNG/init.luau
--[=[ Cryptography library: Cryptographically Secure RNG Usage: local RandomFloat = CSPRNG.Random() local RandomInt = CSPRNG.RandomInt(1, 100) local RandomNumber = CSPRNG.RandomNumber(0.5, 10.5) local RandomBytes = CSPRNG.RandomBytes(32) local RandomHex = CSPRNG.RandomHex(16) local FastString = CSPRNG.RandomString(16, false) local FastBuffer = CSPRNG.RandomString(32, true) local Ed25519Clamped = CSPRNG.Ed25519ClampedBytes(SomeBuffer) local Ed25519Random = CSPRNG.Ed25519Random() CSPRNG.AddEntropyProvider(function) CSPRNG.RemoveEntropyProvider(function) CSPRNG.Reseed() CSPRNG.BytesLeft --]=] --!strict --!optimize 2 --!native local Conversions = require("@self/Conversions") local ChaCha20 = require("@self/ChaCha20") local Blake3 = require("@self/Blake3") export type EntropyProvider = (BytesLeft: number) -> buffer? type CSPRNGModule = { BlockExpansion: boolean, SizeTarget: number, RekeyAfter: number, Key: buffer, Nonce: buffer, Buffer: buffer, Counter: number, BufferPosition: number, BufferSize: number, BytesLeft: number, EntropyProviders: { EntropyProvider }, Reseed: (CustomEntropy: buffer?) -> (), AddEntropyProvider: (ProviderFunction: EntropyProvider) -> (), RemoveEntropyProvider: (ProviderFunction: EntropyProvider) -> (), Random: () -> number, RandomInt: (Min: number, Max: number?) -> number, RandomNumber: (Min: number, Max: number?) -> number, RandomBytes: (Count: number) -> buffer, RandomString: (Length: number, AsBuffer: boolean?) -> string | buffer, RandomHex: (Length: number) -> string, Ed25519ClampedBytes: (Input: buffer) -> buffer, Ed25519Random: () -> buffer, } local BLOCK_SIZE = 64 local KEY_SIZE = 32 local NONCE_SIZE = 12 local CSPRNG: CSPRNGModule = { BlockExpansion = true, SizeTarget = 2048, RekeyAfter = 1024, Key = buffer.create(0), Nonce = buffer.create(0), Buffer = buffer.create(0), Counter = 0, BufferPosition = 0, BufferSize = 0, BytesLeft = 0, EntropyProviders = {} } :: CSPRNGModule local INPUT_BUFFER = buffer.create(BLOCK_SIZE) local REKEY_THRESHOLD = math.max(math.floor(CSPRNG.RekeyAfter), 2) local SIZE_TARGET_CLAMPED = math.clamp(math.floor(CSPRNG.SizeTarget), 64, 4294967295) local function Reset() CSPRNG.Key = buffer.create(0) CSPRNG.Nonce = buffer.create(0) CSPRNG.Buffer = buffer.create(0) CSPRNG.Counter = 0 CSPRNG.BufferPosition = 0 CSPRNG.BufferSize = 0 end local function GatherEntropy(CustomEntropy: buffer?): number local EntropyBuffers = buffer.create(1024) local Offset = 0 local function WriteToBuffer(Source: buffer) local Size = buffer.len(Source) buffer.copy(EntropyBuffers, Offset, Source, 0, Size) Offset += Size end local CurrentTime = 1.234 if tick then CurrentTime = tick() local TimeBuffer = buffer.create(8) buffer.writef64(TimeBuffer, 0, CurrentTime) WriteToBuffer(TimeBuffer) end local ClockTime = os.clock() local ClockBuffer = buffer.create(8) buffer.writef64(ClockBuffer, 0, ClockTime) WriteToBuffer(ClockBuffer) local UnixTime = os.time() local UnixBuffer = buffer.create(8) buffer.writeu32(UnixBuffer, 0, UnixTime % 0x100000000) buffer.writeu32(UnixBuffer, 4, math.floor(UnixTime / 0x100000000)) WriteToBuffer(UnixBuffer) local DateTimeMillis = 5.678 if DateTime then DateTimeMillis = DateTime.now().UnixTimestampMillis local DateTimeBuffer = buffer.create(8) buffer.writef64(DateTimeBuffer, 0, DateTimeMillis) WriteToBuffer(DateTimeBuffer) local DateTimePrecisionBuffer = buffer.create(16) buffer.writef32(DateTimePrecisionBuffer, 0, DateTimeMillis / 1000) buffer.writef32(DateTimePrecisionBuffer, 4, (DateTimeMillis % 1000) / 100) buffer.writef32(DateTimePrecisionBuffer, 8, DateTimeMillis / 86400000) buffer.writef32(DateTimePrecisionBuffer, 12, (DateTimeMillis * 0.001) % 1) WriteToBuffer(DateTimePrecisionBuffer) else WriteToBuffer(buffer.create(24)) end local FracTimeBuffer = buffer.create(16) buffer.writef32(FracTimeBuffer, 0, ClockTime / 100) buffer.writef32(FracTimeBuffer, 4, CurrentTime / 1000) buffer.writef32(FracTimeBuffer, 8, (ClockTime * 12345.6789) % 1) buffer.writef32(FracTimeBuffer, 12, (CurrentTime * 98765.4321) % 1) WriteToBuffer(FracTimeBuffer) local NoiseBuffer = buffer.create(32) for Index = 0, 7 do local Noise1 = math.noise(ClockTime + Index, UnixTime + Index, ClockTime + UnixTime + Index) local Noise2 = math.noise(CurrentTime + Index * 0.1, DateTimeMillis * 0.0001 + Index, ClockTime * 1.5 + Index) local Noise3 = math.noise(UnixTime * 0.01 + Index, ClockTime + DateTimeMillis * 0.001, CurrentTime + Index * 2) local Noise4 = math.noise(DateTimeMillis * 0.00001 + Index, UnixTime + ClockTime + Index, CurrentTime * 0.1 + Index) buffer.writef32(NoiseBuffer, Index * 4, Noise1 + Noise2 + Noise3 + Noise4) end WriteToBuffer(NoiseBuffer) local BenchmarkTimings = buffer.create(32) for Index = 0, 7 do local StartTime = os.clock() local Sum = 0 local Iterations = 50 + (Index * 25) for Iteration = 1, Iterations do Sum += Iteration * Iteration + math.sin(Iteration / 10) * math.cos(Iteration / 7) end local EndTime = os.clock() local TimingDelta = EndTime - StartTime buffer.writef32(BenchmarkTimings, Index * 4, TimingDelta * 1000000) end WriteToBuffer(BenchmarkTimings) local AllocTimings = buffer.create(24) for Index = 0, 5 do local AllocStart = os.clock() for AllocIndex = 1, 20 do local _TempBuf = buffer.create(64 + AllocIndex) end local AllocEnd = os.clock() buffer.writef32(AllocTimings, Index * 4, (AllocEnd - AllocStart) * 10000000) end WriteToBuffer(AllocTimings) local MicroTime = math.floor(CurrentTime * 1000000) local MicroTimeBuffer = buffer.create(8) buffer.writeu32(MicroTimeBuffer, 0, MicroTime % 0x100000000) buffer.writeu32(MicroTimeBuffer, 4, math.floor(MicroTime / 0x100000000)) WriteToBuffer(MicroTimeBuffer) if game then if game.JobId and #game.JobId > 0 then local JobIdBuffer = buffer.fromstring(game.JobId) WriteToBuffer(JobIdBuffer) end if game.PlaceId then local PlaceIdBuffer = buffer.create(8) buffer.writeu32(PlaceIdBuffer, 0, game.PlaceId % 0x100000000) buffer.writeu32(PlaceIdBuffer, 4, math.floor(game.PlaceId / 0x100000000)) WriteToBuffer(PlaceIdBuffer) end if workspace and workspace.DistributedGameTime then local DistTimeBuffer = buffer.create(8) buffer.writef64(DistTimeBuffer, 0, workspace.DistributedGameTime) WriteToBuffer(DistTimeBuffer) local DistMicroTime = math.floor(workspace.DistributedGameTime * 1000000) local DistMicroBuffer = buffer.create(8) buffer.writeu32(DistMicroBuffer, 0, DistMicroTime % 0x100000000) buffer.writeu32(DistMicroBuffer, 4, math.floor(DistMicroTime / 0x100000000)) WriteToBuffer(DistMicroBuffer) end end local AddressEntropy = buffer.create(128) for Index = 0, 7 do local TempTable = {} local TempFunc = function() end local TempBuffer = buffer.create(0) local TempUserdata = newproxy() local TableAddr = string.gsub(tostring(TempTable), "table: ", "") local FuncAddr = string.gsub(tostring(TempFunc), "function: ", "") local BufferAddr = string.gsub(tostring(TempBuffer), "buffer: ", "") local UserdataAddr = string.gsub(tostring(TempUserdata), "userdata: ", "") local TableHash = 0 local ThreadHash = 0 local FuncHash = 0 local BufferHash = 0 local UserdataHash = 0 for AddrIndex = 1, #TableAddr do TableHash = bit32.bxor(TableHash, string.byte(TableAddr, AddrIndex)) * 31 end if coroutine then local ThreadAddr = string.gsub(tostring(coroutine.create(function() end)), "thread: ", "") for AddrIndex = 1, #ThreadAddr do ThreadHash = bit32.bxor(ThreadHash, string.byte(ThreadAddr, AddrIndex)) * 31 end end for AddrIndex = 1, #FuncAddr do FuncHash = bit32.bxor(FuncHash, string.byte(FuncAddr, AddrIndex)) * 37 end for AddrIndex = 1, #BufferAddr do BufferHash = bit32.bxor(BufferHash, string.byte(BufferAddr, AddrIndex)) * 41 end for AddrIndex = 1, #UserdataAddr do UserdataHash = bit32.bxor(UserdataHash, string.byte(UserdataAddr, AddrIndex)) * 43 end buffer.writeu32(AddressEntropy, Index * 16, TableHash) buffer.writeu32(AddressEntropy, Index * 16 + 4, ThreadHash) buffer.writeu32(AddressEntropy, Index * 16 + 8, FuncHash) buffer.writeu32(AddressEntropy, Index * 16 + 12, bit32.bxor(BufferHash, UserdataHash)) end WriteToBuffer(AddressEntropy) local function AddExtraEntropy(Entropy: buffer?, Warn: boolean, Provider: string?) if not Entropy then return end local BytesLeft = 1024 - Offset if BytesLeft > 0 then local Extra = buffer.len(Entropy) - BytesLeft local Truncated = math.min(BytesLeft, buffer.len(Entropy)) if Extra > 0 and Warn and Provider then warn(`CSPRNG: {Provider} returned {Extra} bytes more than available and was truncated to {Truncated} bytes`) end buffer.copy(EntropyBuffers, Offset, Entropy, 0, Truncated) end end for Index, Provider in CSPRNG.EntropyProviders do local BytesLeft = 1024 - Offset if BytesLeft > 0 then local Success: boolean, ExtraEntropy: buffer? = pcall(Provider, BytesLeft) if not Success then warn(`CSPRNG Provider errored with {ExtraEntropy}`) end AddExtraEntropy(ExtraEntropy, true, `Entropy Provider #{Index}`) end end if CustomEntropy then AddExtraEntropy(CustomEntropy, false) end local KeyMaterial = Blake3(EntropyBuffers, KEY_SIZE + NONCE_SIZE) CSPRNG.Key = buffer.create(KEY_SIZE) buffer.copy(CSPRNG.Key, 0, KeyMaterial, 0, KEY_SIZE) CSPRNG.Nonce = buffer.create(NONCE_SIZE) buffer.copy(CSPRNG.Nonce, 0, KeyMaterial, KEY_SIZE, NONCE_SIZE) return buffer.len(EntropyBuffers) - Offset end local function GenerateBlock() buffer.fill(INPUT_BUFFER, 0, 0, BLOCK_SIZE) local ChaChaOutput = ChaCha20(INPUT_BUFFER, CSPRNG.Key, CSPRNG.Nonce, CSPRNG.Counter, 20) CSPRNG.Buffer = if CSPRNG.BlockExpansion then Blake3(ChaChaOutput, SIZE_TARGET_CLAMPED) else ChaChaOutput CSPRNG.BufferPosition = 0 CSPRNG.BufferSize = buffer.len(CSPRNG.Buffer) CSPRNG.Counter += 1 if CSPRNG.Counter % REKEY_THRESHOLD == 0 then GatherEntropy() CSPRNG.Counter = 0 end end local function GetBytes(Count: number): buffer local Result = buffer.create(Count) local ResultPosition = 0 while ResultPosition < Count do if CSPRNG.BufferPosition >= CSPRNG.BufferSize then GenerateBlock() end local BytesNeeded = Count - ResultPosition local BytesAvailable = CSPRNG.BufferSize - CSPRNG.BufferPosition local BytesToCopy = math.min(BytesNeeded, BytesAvailable) buffer.copy(Result, ResultPosition, CSPRNG.Buffer, CSPRNG.BufferPosition, BytesToCopy) ResultPosition += BytesToCopy CSPRNG.BufferPosition += BytesToCopy end return Result end local function GetFloat(): number if CSPRNG.BufferPosition + 8 > CSPRNG.BufferSize then GenerateBlock() end local Value1 = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition) local Value2 = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition + 4) CSPRNG.BufferPosition += 8 local High = bit32.rshift(Value1, 5) local Low = bit32.rshift(Value2, 6) return (High * 67108864.0 + Low) / 9007199254740992.0 end local function GetIntRange(Min: number, Max: number): number local Range = Max - Min + 1 local MaxUInt32 = 0xFFFFFFFF local Limit = MaxUInt32 - (MaxUInt32 % Range) if CSPRNG.BufferPosition + 4 > CSPRNG.BufferSize then GenerateBlock() end local Value = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition) CSPRNG.BufferPosition += 4 if bit32.band(Range, Range - 1) == 0 then return Min + bit32.band(Value, Range - 1) else while Value > Limit do if CSPRNG.BufferPosition + 4 > CSPRNG.BufferSize then GenerateBlock() end Value = buffer.readu32(CSPRNG.Buffer, CSPRNG.BufferPosition) CSPRNG.BufferPosition += 4 end return Min + (Value % Range) end end local function GetNumberRange(Min: number, Max: number): number if Min > Max then Min, Max = Max, Min end local Range = Max - Min if Range <= 0 then return Min end return Min + (GetFloat() * Range) end local function GetRandomString(Length: number, AsBuffer: boolean?): string | buffer local Characters = buffer.create(Length) for Index = 0, Length - 1 do buffer.writeu8(Characters, Index, GetIntRange(36, 122)) end return if AsBuffer then Characters else buffer.tostring(Characters) end local function GetEd25519RandomBytes(): buffer local Output = buffer.create(32) for Index = 0, 31 do buffer.writeu8(Output, Index, GetIntRange(0, 255)) end return Output end local function GetEd25519ClampedBytes(Input: buffer): buffer local Output = buffer.create(32) buffer.copy(Output, 0, Input, 0, 32) local FirstByte = buffer.readu8(Output, 0) FirstByte = bit32.band(FirstByte, 0xF8) buffer.writeu8(Output, 0, FirstByte) local LastByte = buffer.readu8(Output, 31) LastByte = bit32.band(LastByte, 0x7F) LastByte = bit32.bor(LastByte, 0x40) buffer.writeu8(Output, 31, LastByte) local HasVariation = false local FirstMiddleByte = buffer.readu8(Output, 1) for Index = 2, 30 do if buffer.readu8(Output, Index) ~= FirstMiddleByte then HasVariation = true break end end if not HasVariation then buffer.writeu8(Output, 15, bit32.bxor(FirstMiddleByte, 0x55)) end return Output end local function GetHexString(Length: number): string local BytesNeeded = Length / 2 local Bytes = GetBytes(BytesNeeded) local Hex = Conversions.ToHex(Bytes) return Hex end function CSPRNG.AddEntropyProvider(ProviderFunction: EntropyProvider) table.insert(CSPRNG.EntropyProviders, ProviderFunction) end function CSPRNG.RemoveEntropyProvider(ProviderFunction: EntropyProvider) for Index = #CSPRNG.EntropyProviders, 1, -1 do if CSPRNG.EntropyProviders[Index] == ProviderFunction then table.remove(CSPRNG.EntropyProviders, Index) break end end end function CSPRNG.Random(): number return GetFloat() end function CSPRNG.RandomInt(Min: number, Max: number?): number if Max and type(Max) ~= "number" then error(`Max must be a number or nil, got {typeof(Max)}`, 2) end if type(Min) ~= "number" then error(`Min must be a number, got {typeof(Min)}`, 2) end if Max and Max < Min then error(`Max ({Max}) can't be less than Min ({Min})`, 2) end if Max and Max == Min then error(`Max ({Max}) can't be equal to Min ({Min})`, 2) end local ActualMax: number local ActualMin: number if Max == nil then ActualMax = Min ActualMin = 1 else ActualMax = Max ActualMin = Min end return GetIntRange(ActualMin, ActualMax) end function CSPRNG.RandomNumber(Min: number, Max: number?): number if Max and type(Max) ~= "number" then error(`Max must be a number or nil, got {typeof(Max)}`, 2) end if type(Min) ~= "number" then error(`Min must be a number, got {typeof(Min)}`, 2) end if Max and Max < Min then error(`Max ({Max}) must be bigger than Min ({Min})`, 2) end if Max and Max == Min then error(`Max ({Max}) can't be equal to Min ({Min})`, 2) end local ActualMax: number local ActualMin: number if Max == nil then ActualMax = Min ActualMin = 0 else ActualMax = Max ActualMin = Min end return GetNumberRange(ActualMin, ActualMax) end function CSPRNG.RandomBytes(Count: number): buffer if type(Count) ~= "number" then error(`Count must be a number, got {typeof(Count)}`, 2) end if Count <= 0 then error(`Count must be bigger than 0, got {Count}`, 2) end if Count % 1 ~= 0 then error("Count must be an integer", 2) end return GetBytes(Count) end function CSPRNG.RandomString(Length: number, AsBuffer: boolean?): string | buffer if type(Length) ~= "number" then error(`Length must be a number, got {typeof(Length)}`, 2) end if Length <= 0 then error(`Length must be bigger than 0, got {Length}`, 2) end if Length % 1 ~= 0 then error("Length must be an integer", 2) end if AsBuffer ~= nil and type(AsBuffer) ~= "boolean" then error(`AsBuffer must be a boolean or nil, got {typeof(AsBuffer)}`, 2) end return GetRandomString(Length, AsBuffer) end function CSPRNG.RandomHex(Length: number): string if type(Length) ~= "number" then error(`Length must be a number, got {typeof(Length)}`, 2) end if Length <= 0 then error(`Length must be bigger than 0, got {Length}`, 2) end if Length % 1 ~= 0 then error("Length must be an integer", 2) end if Length % 2 ~= 0 then error(`Length must be even, got {Length}`, 2) end return GetHexString(Length) end function CSPRNG.Ed25519ClampedBytes(Input: buffer): buffer if type(Input) ~= "buffer" then error(`Input must be a buffer, got {typeof(Input)}`, 2) end return GetEd25519ClampedBytes(Input) end function CSPRNG.Ed25519Random(): buffer return GetEd25519ClampedBytes(GetEd25519RandomBytes()) end function CSPRNG.Reseed(CustomEntropy: buffer?) if CustomEntropy ~= nil and type(CustomEntropy) ~= "buffer" then error(`CustomEntropy must be a buffer or nil, got {typeof(CustomEntropy)}`, 2) end Reset() GatherEntropy(CustomEntropy) end CSPRNG.BytesLeft = GatherEntropy() GenerateBlock() return CSPRNG
5,064
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/Field.luau
--[=[ Finite field arithmetic modulo Q = 8380417 Arithmetic operations over the prime field Z_q where q = 2^23 - 2^13 + 1. All operations maintain elements in canonical form [0, Q). Example usage: local Field = require(script) local A = 12345 local B = 67890 local Sum = Field.Add(A, B) local Product = Field.Multiply(A, B) local Inverse = Field.Inverse(A) --]=] --!strict --!optimize 2 --!native local Q = 8380417 local Field = {} function Field.Add(A: number, B: number): number local Sum = A + B return if Sum >= Q then Sum - Q else Sum end function Field.Negate(A: number): number return if A == 0 then 0 else Q - A end function Field.Subtract(A: number, B: number): number local Diff = A - B return if Diff < 0 then Diff + Q else Diff end function Field.Multiply(A: number, B: number): number return (A * B) % Q end function Field.Power(Base: number, Exponent: number): number if Exponent == 0 then return 1 end if Exponent == 1 then return Base % Q end local Result = 1 local CurrentBase = Base % Q local Exp = Exponent while Exp > 0 do if bit32.band(Exp, 1) == 1 then Result = Field.Multiply(Result, CurrentBase) end CurrentBase = Field.Multiply(CurrentBase, CurrentBase) Exp = bit32.rshift(Exp, 1) end return Result end function Field.Inverse(A: number): number return Field.Power(A, Q - 2) end function Field.Divide(A: number, B: number): number return Field.Multiply(A, Field.Inverse(B)) end return Field
451
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/NTT.luau
--[=[ Number Theoretic Transform for degree-255 polynomials Forward and inverse NTT over Z_q for polynomial multiplication. Uses Cooley-Tukey and Gentleman-Sande algorithms with precomputed roots. Example usage: local NTT = require(script) local Poly = buffer.create(256 * 4) -- 256 coefficients, 4 bytes each NTT.ForwardNTT(Poly) -- Perform operations in NTT domain NTT.InverseNTT(Poly) --]=] --!strict --!optimize 2 --!native local Field = require("./Field") local LOG2N = 8 local ZETA = 1753 local Q = 8380417 local N = bit32.lshift(1, LOG2N) local INV_N = Field.Inverse(N) local ZETA_EXP, ZETA_NEG_EXP = buffer.create(N * 4), buffer.create(N * 4) do for I = 0, N - 1 do local Reversed = 0 local Value = I for J = 0, LOG2N - 1 do local Bit = bit32.band(bit32.rshift(Value, J), 1) Reversed = bit32.bxor(Reversed, bit32.lshift(Bit, LOG2N - 1 - J)) end local ZetaExp = Field.Power(ZETA, Reversed) local ZetaNegExp = Field.Negate(ZetaExp) buffer.writeu32(ZETA_EXP, I * 4, ZetaExp) buffer.writeu32(ZETA_NEG_EXP, I * 4, ZetaNegExp) end end local Ntt = {} function Ntt.ForwardNTT(Poly: buffer) local Zeta = ZETA_EXP local Modulus = Q for L = LOG2N - 1, 0, -1 do local Len = bit32.lshift(1, L) local LenX2 = bit32.lshift(Len, 1) local KBeg = bit32.rshift(N, L + 1) for Start = 0, N - 1, LenX2 do local KNow = KBeg + bit32.rshift(Start, L + 1) local ZetaExpValue = buffer.readu32(Zeta, KNow * 4) for I = Start, Start + Len - 1 do local IOffset = I * 4 local ILenOffset = (I + Len) * 4 local PolyI = buffer.readu32(Poly, IOffset) local PolyILen = buffer.readu32(Poly, ILenOffset) local Tmp = (ZetaExpValue * PolyILen) % Modulus local Sub = if PolyI >= Tmp then PolyI - Tmp else PolyI - Tmp + Modulus local Add = PolyI + Tmp Add = if Add >= Modulus then Add - Modulus else Add buffer.writeu32(Poly, ILenOffset, Sub) buffer.writeu32(Poly, IOffset, Add) end end end end function Ntt.ForwardNTTWithOffset(Poly: buffer, BaseOffset: number) local Zeta = ZETA_EXP local Modulus = Q for L = LOG2N - 1, 0, -1 do local Len = bit32.lshift(1, L) local LenX2 = bit32.lshift(Len, 1) local KBeg = bit32.rshift(N, L + 1) for Start = 0, N - 1, LenX2 do local KNow = KBeg + bit32.rshift(Start, L + 1) local ZetaExpValue = buffer.readu32(Zeta, KNow * 4) for I = Start, Start + Len - 1 do local IOffset = BaseOffset + I * 4 local ILenOffset = BaseOffset + (I + Len) * 4 local PolyI = buffer.readu32(Poly, IOffset) local PolyILen = buffer.readu32(Poly, ILenOffset) local Tmp = (ZetaExpValue * PolyILen) % Modulus local Sub = if PolyI >= Tmp then PolyI - Tmp else PolyI - Tmp + Modulus local Add = PolyI + Tmp Add = if Add >= Modulus then Add - Modulus else Add buffer.writeu32(Poly, ILenOffset, Sub) buffer.writeu32(Poly, IOffset, Add) end end end end function Ntt.InverseNTT(Poly: buffer) local Zeta = ZETA_NEG_EXP local Inv_n = INV_N local Modulus = Q for L = 0, LOG2N - 1 do local Len = bit32.lshift(1, L) local LenX2 = bit32.lshift(Len, 1) local KBeg = bit32.rshift(N, L) - 1 for Start = 0, N - 1, LenX2 do local KNow = KBeg - bit32.rshift(Start, L + 1) local NegZetaExpValue = buffer.readu32(Zeta, KNow * 4) for I = Start, Start + Len - 1 do local IOffset = I * 4 local ILenOffset = (I + Len) * 4 local PolyI = buffer.readu32(Poly, IOffset) local PolyILen = buffer.readu32(Poly, ILenOffset) local Sum = PolyI + PolyILen Sum = if Sum >= Modulus then Sum - Modulus else Sum local Diff = if PolyI >= PolyILen then PolyI - PolyILen else PolyI - PolyILen + Modulus local Product = (Diff * NegZetaExpValue) % Modulus buffer.writeu32(Poly, IOffset, Sum) buffer.writeu32(Poly, ILenOffset, Product) end end end for I = 0, N - 1 do local Offset = I * 4 local PolyValue = buffer.readu32(Poly, Offset) local Result = (PolyValue * Inv_n) % Modulus buffer.writeu32(Poly, Offset, Result) end end Ntt.ZETA_NEG_EXP = ZETA_NEG_EXP Ntt.INV_N = INV_N return Ntt
1,459
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/Pack.luau
--[=[ Bit packing and unpacking utilities Serializes polynomials to byte arrays with various bit widths. Supports encoding/decoding of polynomial coefficients and hint bits. Example usage: local BitPacking = require(script) local Poly = buffer.create(256 * 4) local Encoded = buffer.create(96) -- For 3-bit encoding BitPacking.Encode(Poly, Encoded, 3) BitPacking.Decode(Encoded, Poly, 3) --]=] --!strict --!optimize 2 --!native local N = 256 local POLY_BYTES = N * 4 local BitPacking = {} function BitPacking.Encode(Poly: buffer, Arr: buffer, Sbw: number) local ArrLen = buffer.len(Arr) buffer.fill(Arr, 0, 0, ArrLen) if Sbw == 3 then for I = 0, 31 do local PBase = I * 32 local BBase = I * 3 local P0 = bit32.band(buffer.readu32(Poly, PBase), 0x7) local P1 = bit32.band(buffer.readu32(Poly, PBase + 4), 0x7) local P2 = bit32.band(buffer.readu32(Poly, PBase + 8), 0x7) local P3 = bit32.band(buffer.readu32(Poly, PBase + 12), 0x7) local P4 = bit32.band(buffer.readu32(Poly, PBase + 16), 0x7) local P5 = bit32.band(buffer.readu32(Poly, PBase + 20), 0x7) local P6 = bit32.band(buffer.readu32(Poly, PBase + 24), 0x7) local P7 = bit32.band(buffer.readu32(Poly, PBase + 28), 0x7) local Byte0 = bit32.bor(P0, bit32.lshift(P1, 3), bit32.lshift(P2, 6)) local Byte1 = bit32.bor(bit32.rshift(P2, 2), bit32.lshift(P3, 1), bit32.lshift(P4, 4), bit32.lshift(P5, 7)) local Byte2 = bit32.bor(bit32.rshift(P5, 1), bit32.lshift(P6, 2), bit32.lshift(P7, 5)) buffer.writeu8(Arr, BBase, Byte0) buffer.writeu8(Arr, BBase + 1, Byte1) buffer.writeu8(Arr, BBase + 2, Byte2) end elseif Sbw == 4 then for I = 0, 31 do local PBase = I * 32 local BBase = I * 4 local Word = buffer.readu32(Poly, PBase) local P0 = bit32.band(Word, 0xF) Word = buffer.readu32(Poly, PBase + 4) local P1 = bit32.band(Word, 0xF) Word = buffer.readu32(Poly, PBase + 8) local P2 = bit32.band(Word, 0xF) Word = buffer.readu32(Poly, PBase + 12) local P3 = bit32.band(Word, 0xF) Word = buffer.readu32(Poly, PBase + 16) local P4 = bit32.band(Word, 0xF) Word = buffer.readu32(Poly, PBase + 20) local P5 = bit32.band(Word, 0xF) Word = buffer.readu32(Poly, PBase + 24) local P6 = bit32.band(Word, 0xF) Word = buffer.readu32(Poly, PBase + 28) local P7 = bit32.band(Word, 0xF) buffer.writeu32(Arr, BBase, bit32.bor( P0, bit32.lshift(P1, 4), bit32.lshift(P2, 8), bit32.lshift(P3, 12), bit32.lshift(P4, 16), bit32.lshift(P5, 20), bit32.lshift(P6, 24), bit32.lshift(P7, 28) )) end elseif Sbw == 6 then for I = 0, 63 do local PBase = I * 16 local BBase = I * 3 local P0 = bit32.band(buffer.readu32(Poly, PBase), 0x3F) local P1 = bit32.band(buffer.readu32(Poly, PBase + 4), 0x3F) local P2 = bit32.band(buffer.readu32(Poly, PBase + 8), 0x3F) local P3 = bit32.band(buffer.readu32(Poly, PBase + 12), 0x3F) local Packed = bit32.bor(P0, bit32.lshift(P1, 6), bit32.lshift(P2, 12), bit32.lshift(P3, 18)) buffer.writeu8(Arr, BBase, bit32.band(Packed, 0xFF)) buffer.writeu8(Arr, BBase + 1, bit32.band(bit32.rshift(Packed, 8), 0xFF)) buffer.writeu8(Arr, BBase + 2, bit32.rshift(Packed, 16)) end elseif Sbw == 10 then for I = 0, 63 do local PBase = I * 16 local BBase = I * 5 local P0 = bit32.band(buffer.readu32(Poly, PBase), 0x3FF) local P1 = bit32.band(buffer.readu32(Poly, PBase + 4), 0x3FF) local P2 = bit32.band(buffer.readu32(Poly, PBase + 8), 0x3FF) local P3 = bit32.band(buffer.readu32(Poly, PBase + 12), 0x3FF) local Lo = bit32.bor(P0, bit32.lshift(P1, 10), bit32.lshift(P2, 20)) local Hi = bit32.bor(bit32.rshift(P2, 12), bit32.lshift(P3, 8)) buffer.writeu32(Arr, BBase, Lo) buffer.writeu8(Arr, BBase + 4, bit32.band(Hi, 0xFF)) end elseif Sbw == 13 then for I = 0, 31 do local PBase = I * 32 local BBase = I * 13 local P0 = bit32.band(buffer.readu32(Poly, PBase), 0x1FFF) local P1 = bit32.band(buffer.readu32(Poly, PBase + 4), 0x1FFF) local P2 = bit32.band(buffer.readu32(Poly, PBase + 8), 0x1FFF) local P3 = bit32.band(buffer.readu32(Poly, PBase + 12), 0x1FFF) local P4 = bit32.band(buffer.readu32(Poly, PBase + 16), 0x1FFF) local P5 = bit32.band(buffer.readu32(Poly, PBase + 20), 0x1FFF) local P6 = bit32.band(buffer.readu32(Poly, PBase + 24), 0x1FFF) local P7 = bit32.band(buffer.readu32(Poly, PBase + 28), 0x1FFF) local W0 = bit32.bor(P0, bit32.lshift(P1, 13), bit32.lshift(P2, 26)) local W1 = bit32.bor(bit32.rshift(P2, 6), bit32.lshift(P3, 7), bit32.lshift(P4, 20)) local W2 = bit32.bor(bit32.rshift(P4, 12), bit32.lshift(P5, 1), bit32.lshift(P6, 14), bit32.lshift(P7, 27)) local W3 = bit32.rshift(P7, 5) buffer.writeu32(Arr, BBase, W0) buffer.writeu32(Arr, BBase + 4, W1) buffer.writeu32(Arr, BBase + 8, W2) buffer.writeu8(Arr, BBase + 12, W3) end elseif Sbw == 18 then for I = 0, 63 do local PBase = I * 16 local BBase = I * 9 local P0 = bit32.band(buffer.readu32(Poly, PBase), 0x3FFFF) local P1 = bit32.band(buffer.readu32(Poly, PBase + 4), 0x3FFFF) local P2 = bit32.band(buffer.readu32(Poly, PBase + 8), 0x3FFFF) local P3 = bit32.band(buffer.readu32(Poly, PBase + 12), 0x3FFFF) local W0 = bit32.bor(P0, bit32.lshift(P1, 18)) local W1 = bit32.bor(bit32.rshift(P1, 14), bit32.lshift(P2, 4), bit32.lshift(P3, 22)) local W2 = bit32.rshift(P3, 10) buffer.writeu32(Arr, BBase, W0) buffer.writeu32(Arr, BBase + 4, W1) buffer.writeu8(Arr, BBase + 8, W2) end elseif Sbw == 20 then for I = 0, 63 do local PBase = I * 16 local BBase = I * 10 local P0 = bit32.band(buffer.readu32(Poly, PBase), 0xFFFFF) local P1 = bit32.band(buffer.readu32(Poly, PBase + 4), 0xFFFFF) local P2 = bit32.band(buffer.readu32(Poly, PBase + 8), 0xFFFFF) local P3 = bit32.band(buffer.readu32(Poly, PBase + 12), 0xFFFFF) local W0 = bit32.bor(P0, bit32.lshift(P1, 20)) local W1 = bit32.bor(bit32.rshift(P1, 12), bit32.lshift(P2, 8), bit32.lshift(P3, 28)) local W2 = bit32.rshift(P3, 4) buffer.writeu32(Arr, BBase, W0) buffer.writeu32(Arr, BBase + 4, W1) buffer.writeu16(Arr, BBase + 8, W2) end else local Mask = bit32.lshift(1, Sbw) - 1 local BitPos = 0 for I = 0, N - 1 do local Value = bit32.band(buffer.readu32(Poly, I * 4), Mask) local BitsRemaining = Sbw while BitsRemaining > 0 do local ByteIdx = bit32.rshift(BitPos, 3) local BitOffset = bit32.band(BitPos, 7) local BitsInByte = math.min(BitsRemaining, 8 - BitOffset) local BitMask = bit32.lshift(1, BitsInByte) - 1 local Bits = bit32.band(Value, BitMask) local Current = buffer.readu8(Arr, ByteIdx) buffer.writeu8(Arr, ByteIdx, bit32.bor(Current, bit32.lshift(Bits, BitOffset))) Value = bit32.rshift(Value, BitsInByte) BitPos += BitsInByte BitsRemaining -= BitsInByte end end end end function BitPacking.Decode(Arr: buffer, Poly: buffer, Sbw: number) buffer.fill(Poly, 0, 0, POLY_BYTES) if Sbw == 3 then for I = 0, 31 do local BBase = I * 3 local PBase = I * 32 local B0 = buffer.readu8(Arr, BBase) local B1 = buffer.readu8(Arr, BBase + 1) local B2 = buffer.readu8(Arr, BBase + 2) buffer.writeu32(Poly, PBase, bit32.band(B0, 0x7)) buffer.writeu32(Poly, PBase + 4, bit32.band(bit32.rshift(B0, 3), 0x7)) buffer.writeu32(Poly, PBase + 8, bit32.bor(bit32.rshift(B0, 6), bit32.lshift(bit32.band(B1, 0x1), 2))) buffer.writeu32(Poly, PBase + 12, bit32.band(bit32.rshift(B1, 1), 0x7)) buffer.writeu32(Poly, PBase + 16, bit32.band(bit32.rshift(B1, 4), 0x7)) buffer.writeu32(Poly, PBase + 20, bit32.bor(bit32.rshift(B1, 7), bit32.lshift(bit32.band(B2, 0x3), 1))) buffer.writeu32(Poly, PBase + 24, bit32.band(bit32.rshift(B2, 2), 0x7)) buffer.writeu32(Poly, PBase + 28, bit32.rshift(B2, 5)) end elseif Sbw == 4 then for I = 0, 31 do local BBase = I * 4 local PBase = I * 32 local Word = buffer.readu32(Arr, BBase) buffer.writeu32(Poly, PBase, bit32.band(Word, 0xF)) buffer.writeu32(Poly, PBase + 4, bit32.band(bit32.rshift(Word, 4), 0xF)) buffer.writeu32(Poly, PBase + 8, bit32.band(bit32.rshift(Word, 8), 0xF)) buffer.writeu32(Poly, PBase + 12, bit32.band(bit32.rshift(Word, 12), 0xF)) buffer.writeu32(Poly, PBase + 16, bit32.band(bit32.rshift(Word, 16), 0xF)) buffer.writeu32(Poly, PBase + 20, bit32.band(bit32.rshift(Word, 20), 0xF)) buffer.writeu32(Poly, PBase + 24, bit32.band(bit32.rshift(Word, 24), 0xF)) buffer.writeu32(Poly, PBase + 28, bit32.rshift(Word, 28)) end elseif Sbw == 6 then for I = 0, 63 do local BBase = I * 3 local PBase = I * 16 local B0 = buffer.readu8(Arr, BBase) local B1 = buffer.readu8(Arr, BBase + 1) local B2 = buffer.readu8(Arr, BBase + 2) local Packed = bit32.bor(B0, bit32.lshift(B1, 8), bit32.lshift(B2, 16)) buffer.writeu32(Poly, PBase, bit32.band(Packed, 0x3F)) buffer.writeu32(Poly, PBase + 4, bit32.band(bit32.rshift(Packed, 6), 0x3F)) buffer.writeu32(Poly, PBase + 8, bit32.band(bit32.rshift(Packed, 12), 0x3F)) buffer.writeu32(Poly, PBase + 12, bit32.rshift(Packed, 18)) end elseif Sbw == 10 then for I = 0, 63 do local BBase = I * 5 local PBase = I * 16 local Lo = buffer.readu32(Arr, BBase) local Hi = buffer.readu8(Arr, BBase + 4) buffer.writeu32(Poly, PBase, bit32.band(Lo, 0x3FF)) buffer.writeu32(Poly, PBase + 4, bit32.band(bit32.rshift(Lo, 10), 0x3FF)) buffer.writeu32(Poly, PBase + 8, bit32.bor(bit32.rshift(Lo, 20), bit32.lshift(bit32.band(Hi, 0x3), 12))) buffer.writeu32(Poly, PBase + 12, bit32.rshift(Hi, 2)) end elseif Sbw == 13 then for I = 0, 31 do local BBase = I * 13 local PBase = I * 32 local W0 = buffer.readu32(Arr, BBase) local W1 = buffer.readu32(Arr, BBase + 4) local W2 = buffer.readu32(Arr, BBase + 8) local W3 = buffer.readu8(Arr, BBase + 12) buffer.writeu32(Poly, PBase, bit32.band(W0, 0x1FFF)) buffer.writeu32(Poly, PBase + 4, bit32.band(bit32.rshift(W0, 13), 0x1FFF)) buffer.writeu32(Poly, PBase + 8, bit32.bor(bit32.rshift(W0, 26), bit32.lshift(bit32.band(W1, 0x7F), 6))) buffer.writeu32(Poly, PBase + 12, bit32.band(bit32.rshift(W1, 7), 0x1FFF)) buffer.writeu32(Poly, PBase + 16, bit32.bor(bit32.rshift(W1, 20), bit32.lshift(bit32.band(W2, 0x1), 12))) buffer.writeu32(Poly, PBase + 20, bit32.band(bit32.rshift(W2, 1), 0x1FFF)) buffer.writeu32(Poly, PBase + 24, bit32.band(bit32.rshift(W2, 14), 0x1FFF)) buffer.writeu32(Poly, PBase + 28, bit32.bor(bit32.rshift(W2, 27), bit32.lshift(W3, 5))) end elseif Sbw == 18 then for I = 0, 63 do local BBase = I * 9 local PBase = I * 16 local W0 = buffer.readu32(Arr, BBase) local W1 = buffer.readu32(Arr, BBase + 4) local W2 = buffer.readu8(Arr, BBase + 8) buffer.writeu32(Poly, PBase, bit32.band(W0, 0x3FFFF)) buffer.writeu32(Poly, PBase + 4, bit32.bor(bit32.rshift(W0, 18), bit32.lshift(bit32.band(W1, 0xF), 14))) buffer.writeu32(Poly, PBase + 8, bit32.band(bit32.rshift(W1, 4), 0x3FFFF)) buffer.writeu32(Poly, PBase + 12, bit32.bor(bit32.rshift(W1, 22), bit32.lshift(W2, 10))) end elseif Sbw == 20 then for I = 0, 63 do local BBase = I * 10 local PBase = I * 16 local W0 = buffer.readu32(Arr, BBase) local W1 = buffer.readu32(Arr, BBase + 4) local W2 = buffer.readu16(Arr, BBase + 8) buffer.writeu32(Poly, PBase, bit32.band(W0, 0xFFFFF)) buffer.writeu32(Poly, PBase + 4, bit32.bor(bit32.rshift(W0, 20), bit32.lshift(bit32.band(W1, 0xFF), 12))) buffer.writeu32(Poly, PBase + 8, bit32.bor(bit32.rshift(W1, 8), bit32.lshift(bit32.band(W2, 0xF), 24))) buffer.writeu32(Poly, PBase + 12, bit32.bor(bit32.rshift(W1, 28), bit32.lshift(W2, 4))) end else local Mask = bit32.lshift(1, Sbw) - 1 local BitPos = 0 for I = 0, N - 1 do local Value = 0 local BitsCollected = 0 while BitsCollected < Sbw do local ByteIdx = bit32.rshift(BitPos, 3) local BitOffset = bit32.band(BitPos, 7) local BitsAvailable = 8 - BitOffset local BitsToRead = math.min(Sbw - BitsCollected, BitsAvailable) local ByteVal = buffer.readu8(Arr, ByteIdx) local Extracted = bit32.band(bit32.rshift(ByteVal, BitOffset), bit32.lshift(1, BitsToRead) - 1) Value = bit32.bor(Value, bit32.lshift(Extracted, BitsCollected)) BitPos += BitsToRead BitsCollected += BitsToRead end buffer.writeu32(Poly, I * 4, bit32.band(Value, Mask)) end end end function BitPacking.EncodeHintBits(H: buffer, Arr: buffer, K: number, Omega: number) buffer.fill(Arr, 0, 0, Omega + K) local Idx = 0 for I = 0, K - 1 do local PolyOffset = I * N * 4 for J = 0, N - 1 do if buffer.readu32(H, PolyOffset + J * 4) ~= 0 then buffer.writeu8(Arr, Idx, J) Idx += 1 if Idx >= Omega then break end end end buffer.writeu8(Arr, Omega + I, Idx) end end function BitPacking.DecodeHintBits(Arr: buffer, H: buffer, K: number, Omega: number): boolean buffer.fill(H, 0, 0, K * N * 4) local Idx = 0 local Failed = false for I = 0, K - 1 do local PolyOffset = I * N * 4 local Till = buffer.readu8(Arr, Omega + I) if Till < Idx or Till > Omega then Failed = true end if not Failed then local Prev = -1 for J = Idx, Till - 1 do local Position = buffer.readu8(Arr, J) if Position <= Prev or Position >= N then Failed = true break end buffer.writeu32(H, PolyOffset + Position * 4, 1) Prev = Position end end Idx = Till end if not Failed then for I = Idx, Omega - 1 do if buffer.readu8(Arr, I) ~= 0 then Failed = true break end end end return Failed end return BitPacking
5,403
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/Params.luau
--[=[ Parameter validation for ML-DSA algorithms FIPS 204 specification. Example usage: local Params = require(script) local IsValid = Params.CheckKeygenParams(4, 4, 13, 2) -- ML-DSA-44 local ValidEta = Params.CheckEta(2) --]=] --!strict --!optimize 2 --!native local Q = 8380417 local Params = {} function Params.CheckEta(Eta: number): boolean return Eta == 2 or Eta == 4 end function Params.CheckNonce(Nonce: number): boolean return Nonce == 0 or Nonce == 4 or Nonce == 5 or Nonce == 7 end function Params.CheckGamma1(Gamma1: number): boolean return Gamma1 == bit32.lshift(1, 17) or Gamma1 == bit32.lshift(1, 19) end function Params.CheckGamma2(Gamma2: number): boolean return Gamma2 == math.floor((Q - 1) / 88) or Gamma2 == math.floor((Q - 1) / 32) end function Params.CheckTau(Tau: number): boolean return Tau == 39 or Tau == 49 or Tau == 60 end function Params.CheckD(D: number): boolean return D == 13 end function Params.CheckKeygenParams(K: number, L: number, D: number, Eta: number): boolean return (K == 4 and L == 4 and D == 13 and Eta == 2) or (K == 6 and L == 5 and D == 13 and Eta == 4) or (K == 8 and L == 7 and D == 13 and Eta == 2) end function Params.CheckSigningParams(K: number, L: number, D: number, Eta: number, Gamma1: number, Gamma2: number, Tau: number, Beta: number, Omega: number, Lambda: number): boolean return (K == 4 and L == 4 and D == 13 and Eta == 2 and Gamma1 == bit32.lshift(1, 17) and Gamma2 == math.floor((Q - 1) / 88) and Tau == 39 and Beta == Tau * Eta and Omega == 80 and Lambda == 128) or (K == 6 and L == 5 and D == 13 and Eta == 4 and Gamma1 == bit32.lshift(1, 19) and Gamma2 == math.floor((Q - 1) / 32) and Tau == 49 and Beta == Tau * Eta and Omega == 55 and Lambda == 192) or (K == 8 and L == 7 and D == 13 and Eta == 2 and Gamma1 == bit32.lshift(1, 19) and Gamma2 == math.floor((Q - 1) / 32) and Tau == 60 and Beta == Tau * Eta and Omega == 75 and Lambda == 256) end function Params.CheckVerifyParams(K: number, L: number, D: number, Gamma1: number, Gamma2: number, Tau: number, Beta: number, Omega: number, Lambda: number): boolean return (K == 4 and L == 4 and D == 13 and Gamma1 == bit32.lshift(1, 17) and Gamma2 == math.floor((Q - 1) / 88) and Tau == 39 and Beta == Tau * 2 and Omega == 80 and Lambda == 128) or (K == 6 and L == 5 and D == 13 and Gamma1 == bit32.lshift(1, 19) and Gamma2 == math.floor((Q - 1) / 32) and Tau == 49 and Beta == Tau * 4 and Omega == 55 and Lambda == 192) or (K == 8 and L == 7 and D == 13 and Gamma1 == bit32.lshift(1, 19) and Gamma2 == math.floor((Q - 1) / 32) and Tau == 60 and Beta == Tau * 2 and Omega == 75 and Lambda == 256) end return Params
993
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/PolyVec.luau
--[=[ Vector operations on degree-255 polynomials Works on vectors of polynomials including matrix multiplication, NTT transforms, and encoding/decoding for ML-DSA. Example usage: local PolyVec = require(script) local Vec = buffer.create(4 * 256 * 4) -- 4 polynomials PolyVec.ForwardNTT(Vec, 4) local Norm = PolyVec.InfinityNorm(Vec, 4) --]=] --!strict --!optimize 2 --!native local Field = require("./Field") local NTT = require("./NTT") local BitPacking = require("./Pack") local LOG2N = 8 local ZETA = 1753 local Q = 8380417 local N = 256 local INV_N = Field.Inverse(N) local ZETA_EXP, ZETA_NEG_EXP = buffer.create(N * 4), buffer.create(N * 4) do for I = 0, N - 1 do local Reversed = 0 local Value = I for J = 0, LOG2N - 1 do local Bit = bit32.band(bit32.rshift(Value, J), 1) Reversed = bit32.bxor(Reversed, bit32.lshift(Bit, LOG2N - 1 - J)) end local ZetaExp = Field.Power(ZETA, Reversed) local ZetaNegExp = Field.Negate(ZetaExp) buffer.writeu32(ZETA_EXP, I * 4, ZetaExp) buffer.writeu32(ZETA_NEG_EXP, I * 4, ZetaNegExp) end end local PolyVec = {} function PolyVec.ForwardNTT(Vec: buffer, K: number) local Num = N for I = 0, K - 1 do local Offset = I * Num * 4 NTT.ForwardNTTWithOffset(Vec, Offset) end end function PolyVec.InverseNTT(Vec: buffer, K: number) local Zeta = ZETA_NEG_EXP local InvN = INV_N local Num = N local Modulus = Q for I = 0, K - 1 do local Offset = I * Num * 4 for L = 0, 7 do local Len = bit32.lshift(1, L) local LenX2 = bit32.lshift(Len, 1) local KBeg = bit32.rshift(Num, L) - 1 for Start = 0, Num - 1, LenX2 do local KNow = KBeg - bit32.rshift(Start, L + 1) local NegZetaExpValue = buffer.readu32(Zeta, KNow * 4) for J = Start, Start + Len - 1 do local JOffset = Offset + J * 4 local JLenOffset = Offset + (J + Len) * 4 local PolyJ = buffer.readu32(Vec, JOffset) local PolyJLen = buffer.readu32(Vec, JLenOffset) local Sum = PolyJ + PolyJLen Sum = if Sum >= Modulus then Sum - Modulus else Sum local Diff = if PolyJ >= PolyJLen then PolyJ - PolyJLen else PolyJ - PolyJLen + Modulus local Product = (Diff * NegZetaExpValue) % Modulus buffer.writeu32(Vec, JOffset, Sum) buffer.writeu32(Vec, JLenOffset, Product) end end end for J = 0, Num - 1 do local JOffset = Offset + J * 4 local PolyValue = buffer.readu32(Vec, JOffset) local Result = (PolyValue * InvN) % Modulus buffer.writeu32(Vec, JOffset, Result) end end end function PolyVec.Power2Round(PolyVec: buffer, PolyHi: buffer, PolyLo: buffer, K: number, D: number) local Max = bit32.lshift(1, D - 1) local Num = N local Modulus = Q for I = 0, K - 1 do local Offset = I * Num * 4 for J = 0, Num - 1 do local JOffset = Offset + J * 4 local R = buffer.readu32(PolyVec, JOffset) local T1 = R + Max - 1 local T2 = bit32.rshift(T1, D) local T3 = bit32.lshift(T2, D) local Hi = T2 local Lo = if R >= T3 then R - T3 else R - T3 + Modulus buffer.writeu32(PolyHi, JOffset, Hi) buffer.writeu32(PolyLo, JOffset, Lo) end end end function PolyVec.MatrixMultiply(A: buffer, B: buffer, C: buffer, ARows: number, ACols: number, BRows: number, BCols: number) local Num = N local Modulus = Q buffer.fill(C, 0, 0, ARows * BCols * N * 4) for I = 0, ARows - 1 do for J = 0, BCols - 1 do local COffset = (I * BCols + J) * Num * 4 for K = 0, ACols - 1 do local AOffset = (I * ACols + K) * Num * 4 local BOffset = (K * BCols + J) * Num * 4 for L = 0, Num - 1 do local ElementOffset = L * 4 local AValue = buffer.readu32(A, AOffset + ElementOffset) local BValue = buffer.readu32(B, BOffset + ElementOffset) local Product = (AValue * BValue) % Modulus local CValue = buffer.readu32(C, COffset + ElementOffset) local Sum = CValue + Product Sum = if Sum >= Modulus then Sum - Modulus else Sum buffer.writeu32(C, COffset + ElementOffset, Sum) end end end end end function PolyVec.AddTo(Src: buffer, Dst: buffer, K: number) local TotalElements = K * N local Modulus = Q for I = 0, TotalElements - 1 do local Offset = I * 4 local SrcValue = buffer.readu32(Src, Offset) local DstValue = buffer.readu32(Dst, Offset) local Sum = DstValue + SrcValue Sum = if Sum >= Modulus then Sum - Modulus else Sum buffer.writeu32(Dst, Offset, Sum) end end function PolyVec.Negate(Vec: buffer, K: number) local TotalElements = K * N local Modulus = Q for I = 0, TotalElements - 1 do local Offset = I * 4 local Value = buffer.readu32(Vec, Offset) local Negated = if Value == 0 then 0 else Modulus - Value buffer.writeu32(Vec, Offset, Negated) end end function PolyVec.SubFromX(Vec: buffer, K: number, X: number) local Modulus = Q local Num = N for I = 0, K - 1 do local Offset = I * Num * 4 for J = 0, Num - 1 do local JOffset = Offset + J * 4 local PolyValue = buffer.readu32(Vec, JOffset) local Result = if X >= PolyValue then X - PolyValue else X - PolyValue + Modulus buffer.writeu32(Vec, JOffset, Result) end end end function PolyVec.Encode(Src: buffer, Dst: buffer, K: number, Sbw: number) local PolyByteLength = math.floor((N * Sbw) / 8) local Num = N for I = 0, K - 1 do local SrcOffset = I * Num * 4 local DstOffset = I * PolyByteLength if Sbw == 3 then local ItrCnt = 32 for J = 0, ItrCnt - 1 do local POffset = SrcOffset + J * 32 local BOffset = DstOffset + J * 3 local P0 = bit32.band(buffer.readu32(Src, POffset + 0), 0x7) local P1 = bit32.band(buffer.readu32(Src, POffset + 4), 0x7) local P2 = bit32.band(buffer.readu32(Src, POffset + 8), 0x7) local P3 = bit32.band(buffer.readu32(Src, POffset + 12), 0x7) local P4 = bit32.band(buffer.readu32(Src, POffset + 16), 0x7) local P5 = bit32.band(buffer.readu32(Src, POffset + 20), 0x7) local P6 = bit32.band(buffer.readu32(Src, POffset + 24), 0x7) local P7 = bit32.band(buffer.readu32(Src, POffset + 28), 0x7) buffer.writeu8(Dst, BOffset + 0, bit32.bor(bit32.lshift(bit32.band(P2, 0x3), 6), bit32.lshift(P1, 3), P0)) buffer.writeu8(Dst, BOffset + 1, bit32.bor(bit32.lshift(bit32.band(P5, 0x1), 7), bit32.lshift(P4, 4), bit32.lshift(P3, 1), bit32.rshift(P2, 2))) buffer.writeu8(Dst, BOffset + 2, bit32.bor(bit32.lshift(P7, 5), bit32.lshift(P6, 2), bit32.rshift(P5, 1))) end elseif Sbw == 4 then for J = 0, 127 do local POffset = SrcOffset + J * 8 local P0 = bit32.band(buffer.readu32(Src, POffset), 0xF) local P1 = bit32.band(buffer.readu32(Src, POffset + 4), 0xF) buffer.writeu8(Dst, DstOffset + J, bit32.bor(bit32.lshift(P1, 4), P0)) end elseif Sbw == 6 then for J = 0, 63 do local POffset = SrcOffset + J * 16 local BOffset = DstOffset + J * 3 local P0 = bit32.band(buffer.readu32(Src, POffset + 0), 0x3F) local P1 = bit32.band(buffer.readu32(Src, POffset + 4), 0x3F) local P2 = bit32.band(buffer.readu32(Src, POffset + 8), 0x3F) local P3 = bit32.band(buffer.readu32(Src, POffset + 12), 0x3F) buffer.writeu8(Dst, BOffset + 0, bit32.bor(bit32.lshift(bit32.band(P1, 0x3), 6), P0)) buffer.writeu8(Dst, BOffset + 1, bit32.bor(bit32.lshift(bit32.band(P2, 0xF), 4), bit32.rshift(P1, 2))) buffer.writeu8(Dst, BOffset + 2, bit32.bor(bit32.lshift(P3, 2), bit32.rshift(P2, 4))) end elseif Sbw == 10 then for J = 0, 63 do local POffset = SrcOffset + J * 16 local BOffset = DstOffset + J * 5 local P0 = bit32.band(buffer.readu32(Src, POffset + 0), 0x3FF) local P1 = bit32.band(buffer.readu32(Src, POffset + 4), 0x3FF) local P2 = bit32.band(buffer.readu32(Src, POffset + 8), 0x3FF) local P3 = bit32.band(buffer.readu32(Src, POffset + 12), 0x3FF) buffer.writeu8(Dst, BOffset + 0, bit32.band(P0, 0xFF)) buffer.writeu8(Dst, BOffset + 1, bit32.bor(bit32.lshift(bit32.band(P1, 0x3F), 2), bit32.rshift(P0, 8))) buffer.writeu8(Dst, BOffset + 2, bit32.bor(bit32.lshift(bit32.band(P2, 0xF), 4), bit32.rshift(P1, 6))) buffer.writeu8(Dst, BOffset + 3, bit32.bor(bit32.lshift(bit32.band(P3, 0x3), 6), bit32.rshift(P2, 4))) buffer.writeu8(Dst, BOffset + 4, bit32.rshift(P3, 2)) end elseif Sbw == 13 then for J = 0, 31 do local POffset = SrcOffset + J * 32 local BOffset = DstOffset + J * 13 local P0 = bit32.band(buffer.readu32(Src, POffset + 0), 0x1FFF) local P1 = bit32.band(buffer.readu32(Src, POffset + 4), 0x1FFF) local P2 = bit32.band(buffer.readu32(Src, POffset + 8), 0x1FFF) local P3 = bit32.band(buffer.readu32(Src, POffset + 12), 0x1FFF) local P4 = bit32.band(buffer.readu32(Src, POffset + 16), 0x1FFF) local P5 = bit32.band(buffer.readu32(Src, POffset + 20), 0x1FFF) local P6 = bit32.band(buffer.readu32(Src, POffset + 24), 0x1FFF) local P7 = bit32.band(buffer.readu32(Src, POffset + 28), 0x1FFF) buffer.writeu8(Dst, BOffset + 0, bit32.band(P0, 0xFF)) buffer.writeu8(Dst, BOffset + 1, bit32.bor(bit32.lshift(bit32.band(P1, 0x7), 5), bit32.rshift(P0, 8))) buffer.writeu8(Dst, BOffset + 2, bit32.rshift(P1, 3)) buffer.writeu8(Dst, BOffset + 3, bit32.bor(bit32.lshift(bit32.band(P2, 0x3F), 2), bit32.rshift(P1, 11))) buffer.writeu8(Dst, BOffset + 4, bit32.bor(bit32.lshift(bit32.band(P3, 0x1), 7), bit32.rshift(P2, 6))) buffer.writeu8(Dst, BOffset + 5, bit32.rshift(P3, 1)) buffer.writeu8(Dst, BOffset + 6, bit32.bor(bit32.lshift(bit32.band(P4, 0xF), 4), bit32.rshift(P3, 9))) buffer.writeu8(Dst, BOffset + 7, bit32.rshift(P4, 4)) buffer.writeu8(Dst, BOffset + 8, bit32.bor(bit32.lshift(bit32.band(P5, 0x7F), 1), bit32.rshift(P4, 12))) buffer.writeu8(Dst, BOffset + 9, bit32.bor(bit32.lshift(bit32.band(P6, 0x3), 6), bit32.rshift(P5, 7))) buffer.writeu8(Dst, BOffset + 10, bit32.rshift(P6, 2)) buffer.writeu8(Dst, BOffset + 11, bit32.bor(bit32.lshift(bit32.band(P7, 0x1F), 3), bit32.rshift(P6, 10))) buffer.writeu8(Dst, BOffset + 12, bit32.rshift(P7, 5)) end elseif Sbw == 18 then for J = 0, 63 do local POffset = SrcOffset + J * 16 local BOffset = DstOffset + J * 9 local P0 = bit32.band(buffer.readu32(Src, POffset + 0), 0x3FFFF) local P1 = bit32.band(buffer.readu32(Src, POffset + 4), 0x3FFFF) local P2 = bit32.band(buffer.readu32(Src, POffset + 8), 0x3FFFF) local P3 = bit32.band(buffer.readu32(Src, POffset + 12), 0x3FFFF) buffer.writeu8(Dst, BOffset + 0, bit32.band(P0, 0xFF)) buffer.writeu8(Dst, BOffset + 1, bit32.band(bit32.rshift(P0, 8), 0xFF)) buffer.writeu8(Dst, BOffset + 2, bit32.bor(bit32.rshift(P0, 16), bit32.lshift(bit32.band(P1, 0x3F), 2))) buffer.writeu8(Dst, BOffset + 3, bit32.band(bit32.rshift(P1, 6), 0xFF)) buffer.writeu8(Dst, BOffset + 4, bit32.bor(bit32.rshift(P1, 14), bit32.lshift(bit32.band(P2, 0xF), 4))) buffer.writeu8(Dst, BOffset + 5, bit32.band(bit32.rshift(P2, 4), 0xFF)) buffer.writeu8(Dst, BOffset + 6, bit32.bor(bit32.rshift(P2, 12), bit32.lshift(bit32.band(P3, 0x3), 6))) buffer.writeu8(Dst, BOffset + 7, bit32.band(bit32.rshift(P3, 2), 0xFF)) buffer.writeu8(Dst, BOffset + 8, bit32.rshift(P3, 10)) end elseif Sbw == 20 then for J = 0, 63 do local POffset = SrcOffset + J * 16 local BOffset = DstOffset + J * 10 local P0 = bit32.band(buffer.readu32(Src, POffset + 0), 0xFFFFF) local P1 = bit32.band(buffer.readu32(Src, POffset + 4), 0xFFFFF) local P2 = bit32.band(buffer.readu32(Src, POffset + 8), 0xFFFFF) local P3 = bit32.band(buffer.readu32(Src, POffset + 12), 0xFFFFF) buffer.writeu8(Dst, BOffset + 0, bit32.band(P0, 0xFF)) buffer.writeu8(Dst, BOffset + 1, bit32.band(bit32.rshift(P0, 8), 0xFF)) buffer.writeu8(Dst, BOffset + 2, bit32.bor(bit32.rshift(P0, 16), bit32.lshift(bit32.band(P1, 0xF), 4))) buffer.writeu8(Dst, BOffset + 3, bit32.band(bit32.rshift(P1, 4), 0xFF)) buffer.writeu8(Dst, BOffset + 4, bit32.band(bit32.rshift(P1, 12), 0xFF)) buffer.writeu8(Dst, BOffset + 5, bit32.band(P2, 0xFF)) buffer.writeu8(Dst, BOffset + 6, bit32.band(bit32.rshift(P2, 8), 0xFF)) buffer.writeu8(Dst, BOffset + 7, bit32.bor(bit32.rshift(P2, 16), bit32.lshift(bit32.band(P3, 0xF), 4))) buffer.writeu8(Dst, BOffset + 8, bit32.band(bit32.rshift(P3, 4), 0xFF)) buffer.writeu8(Dst, BOffset + 9, bit32.rshift(P3, 12)) end else local PolyBuffer = buffer.create(N * 4) local ByteBuffer = buffer.create(PolyByteLength) buffer.copy(PolyBuffer, 0, Src, SrcOffset, N * 4) BitPacking.Encode(PolyBuffer, ByteBuffer, Sbw) buffer.copy(Dst, DstOffset, ByteBuffer, 0, PolyByteLength) end end end function PolyVec.Decode(Src: buffer, Dst: buffer, K: number, Sbw: number) local PolyByteLength = math.floor((N * Sbw) / 8) local Num = N for I = 0, K - 1 do local SrcOffset = I * PolyByteLength local DstOffset = I * Num * 4 if Sbw == 3 then for J = 0, 31 do local BOffset = SrcOffset + J * 3 local POffset = DstOffset + J * 32 local B0 = buffer.readu8(Src, BOffset + 0) local B1 = buffer.readu8(Src, BOffset + 1) local B2 = buffer.readu8(Src, BOffset + 2) buffer.writeu32(Dst, POffset + 0, bit32.band(B0, 0x7)) buffer.writeu32(Dst, POffset + 4, bit32.band(bit32.rshift(B0, 3), 0x7)) buffer.writeu32(Dst, POffset + 8, bit32.bor(bit32.rshift(B0, 6), bit32.lshift(bit32.band(B1, 0x1), 2))) buffer.writeu32(Dst, POffset + 12, bit32.band(bit32.rshift(B1, 1), 0x7)) buffer.writeu32(Dst, POffset + 16, bit32.band(bit32.rshift(B1, 4), 0x7)) buffer.writeu32(Dst, POffset + 20, bit32.bor(bit32.rshift(B1, 7), bit32.lshift(bit32.band(B2, 0x3), 1))) buffer.writeu32(Dst, POffset + 24, bit32.band(bit32.rshift(B2, 2), 0x7)) buffer.writeu32(Dst, POffset + 28, bit32.rshift(B2, 5)) end elseif Sbw == 4 then for J = 0, 127 do local B = buffer.readu8(Src, SrcOffset + J) local POffset = DstOffset + J * 8 buffer.writeu32(Dst, POffset, bit32.band(B, 0xF)) buffer.writeu32(Dst, POffset + 4, bit32.rshift(B, 4)) end elseif Sbw == 6 then for J = 0, 63 do local BOffset = SrcOffset + J * 3 local POffset = DstOffset + J * 16 local B0 = buffer.readu8(Src, BOffset + 0) local B1 = buffer.readu8(Src, BOffset + 1) local B2 = buffer.readu8(Src, BOffset + 2) buffer.writeu32(Dst, POffset + 0, bit32.band(B0, 0x3F)) buffer.writeu32(Dst, POffset + 4, bit32.bor(bit32.rshift(B0, 6), bit32.lshift(bit32.band(B1, 0xF), 2))) buffer.writeu32(Dst, POffset + 8, bit32.bor(bit32.rshift(B1, 4), bit32.lshift(bit32.band(B2, 0x3), 4))) buffer.writeu32(Dst, POffset + 12, bit32.rshift(B2, 2)) end elseif Sbw == 10 then for J = 0, 63 do local BOffset = SrcOffset + J * 5 local POffset = DstOffset + J * 16 local B0 = buffer.readu8(Src, BOffset + 0) local B1 = buffer.readu8(Src, BOffset + 1) local B2 = buffer.readu8(Src, BOffset + 2) local B3 = buffer.readu8(Src, BOffset + 3) local B4 = buffer.readu8(Src, BOffset + 4) buffer.writeu32(Dst, POffset + 0, bit32.bor(B0, bit32.lshift(bit32.band(B1, 0x3), 8))) buffer.writeu32(Dst, POffset + 4, bit32.bor(bit32.rshift(B1, 2), bit32.lshift(bit32.band(B2, 0xF), 6))) buffer.writeu32(Dst, POffset + 8, bit32.bor(bit32.rshift(B2, 4), bit32.lshift(bit32.band(B3, 0x3F), 4))) buffer.writeu32(Dst, POffset + 12, bit32.bor(bit32.rshift(B3, 6), bit32.lshift(B4, 2))) end elseif Sbw == 13 then for J = 0, 31 do local BOffset = SrcOffset + J * 13 local POffset = DstOffset + J * 32 local B0 = buffer.readu8(Src, BOffset + 0) local B1 = buffer.readu8(Src, BOffset + 1) local B2 = buffer.readu8(Src, BOffset + 2) local B3 = buffer.readu8(Src, BOffset + 3) local B4 = buffer.readu8(Src, BOffset + 4) local B5 = buffer.readu8(Src, BOffset + 5) local B6 = buffer.readu8(Src, BOffset + 6) local B7 = buffer.readu8(Src, BOffset + 7) local B8 = buffer.readu8(Src, BOffset + 8) local B9 = buffer.readu8(Src, BOffset + 9) local B10 = buffer.readu8(Src, BOffset + 10) local B11 = buffer.readu8(Src, BOffset + 11) local B12 = buffer.readu8(Src, BOffset + 12) buffer.writeu32(Dst, POffset + 0, bit32.bor(B0, bit32.lshift(bit32.band(B1, 0x1F), 8))) buffer.writeu32(Dst, POffset + 4, bit32.bor(bit32.rshift(B1, 5), bit32.lshift(B2, 3), bit32.lshift(bit32.band(B3, 0x3), 11))) buffer.writeu32(Dst, POffset + 8, bit32.bor(bit32.rshift(B3, 2), bit32.lshift(bit32.band(B4, 0x7F), 6))) buffer.writeu32(Dst, POffset + 12, bit32.bor(bit32.rshift(B4, 7), bit32.lshift(B5, 1), bit32.lshift(bit32.band(B6, 0xF), 9))) buffer.writeu32(Dst, POffset + 16, bit32.bor(bit32.rshift(B6, 4), bit32.lshift(B7, 4), bit32.lshift(bit32.band(B8, 0x1), 12))) buffer.writeu32(Dst, POffset + 20, bit32.bor(bit32.rshift(B8, 1), bit32.lshift(bit32.band(B9, 0x3F), 7))) buffer.writeu32(Dst, POffset + 24, bit32.bor(bit32.rshift(B9, 6), bit32.lshift(B10, 2), bit32.lshift(bit32.band(B11, 0x7), 10))) buffer.writeu32(Dst, POffset + 28, bit32.bor(bit32.rshift(B11, 3), bit32.lshift(B12, 5))) end elseif Sbw == 18 then for J = 0, 63 do local BOffset = SrcOffset + J * 9 local POffset = DstOffset + J * 16 local B0 = buffer.readu8(Src, BOffset + 0) local B1 = buffer.readu8(Src, BOffset + 1) local B2 = buffer.readu8(Src, BOffset + 2) local B3 = buffer.readu8(Src, BOffset + 3) local B4 = buffer.readu8(Src, BOffset + 4) local B5 = buffer.readu8(Src, BOffset + 5) local B6 = buffer.readu8(Src, BOffset + 6) local B7 = buffer.readu8(Src, BOffset + 7) local B8 = buffer.readu8(Src, BOffset + 8) buffer.writeu32(Dst, POffset + 0, bit32.bor(B0, bit32.lshift(B1, 8), bit32.lshift(bit32.band(B2, 0x3), 16))) buffer.writeu32(Dst, POffset + 4, bit32.bor(bit32.rshift(B2, 2), bit32.lshift(B3, 6), bit32.lshift(bit32.band(B4, 0xF), 14))) buffer.writeu32(Dst, POffset + 8, bit32.bor(bit32.rshift(B4, 4), bit32.lshift(B5, 4), bit32.lshift(bit32.band(B6, 0x3F), 12))) buffer.writeu32(Dst, POffset + 12, bit32.bor(bit32.rshift(B6, 6), bit32.lshift(B7, 2), bit32.lshift(B8, 10))) end elseif Sbw == 20 then for J = 0, 63 do local BOffset = SrcOffset + J * 10 local POffset = DstOffset + J * 16 local B0 = buffer.readu8(Src, BOffset + 0) local B1 = buffer.readu8(Src, BOffset + 1) local B2 = buffer.readu8(Src, BOffset + 2) local B3 = buffer.readu8(Src, BOffset + 3) local B4 = buffer.readu8(Src, BOffset + 4) local B5 = buffer.readu8(Src, BOffset + 5) local B6 = buffer.readu8(Src, BOffset + 6) local B7 = buffer.readu8(Src, BOffset + 7) local B8 = buffer.readu8(Src, BOffset + 8) local B9 = buffer.readu8(Src, BOffset + 9) buffer.writeu32(Dst, POffset + 0, bit32.bor(B0, bit32.lshift(B1, 8), bit32.lshift(bit32.band(B2, 0xF), 16))) buffer.writeu32(Dst, POffset + 4, bit32.bor(bit32.rshift(B2, 4), bit32.lshift(B3, 4), bit32.lshift(B4, 12))) buffer.writeu32(Dst, POffset + 8, bit32.bor(B5, bit32.lshift(B6, 8), bit32.lshift(bit32.band(B7, 0xF), 16))) buffer.writeu32(Dst, POffset + 12, bit32.bor(bit32.rshift(B7, 4), bit32.lshift(B8, 4), bit32.lshift(B9, 12))) end else local ByteBuffer = buffer.create(PolyByteLength) local PolyBuffer = buffer.create(N * 4) buffer.copy(ByteBuffer, 0, Src, SrcOffset, PolyByteLength) BitPacking.Decode(ByteBuffer, PolyBuffer, Sbw) buffer.copy(Dst, DstOffset, PolyBuffer, 0, N * 4) end end end function PolyVec.HighBits(Src: buffer, Dst: buffer, K: number, Alpha: number) local T0 = bit32.rshift(Alpha, 1) local T1 = Q - 1 local Modulus = Q local Num = N for I = 0, K - 1 do local Offset = I * Num * 4 for J = 0, Num - 1 do local JOffset = Offset + J * 4 local R = buffer.readu32(Src, JOffset) local T2 = R + T0 - 1 local T3 = math.floor(T2 / Alpha) local T4 = T3 * Alpha local R0 = if R >= T4 then R - T4 else R - T4 + Modulus local T5 = if R >= R0 then R - R0 else R - R0 + Modulus local Flag = (T5 == T1) local R1 = if Flag then 0 else T3 buffer.writeu32(Dst, JOffset, R1) end end end function PolyVec.LowBits(Src: buffer, Dst: buffer, K: number, Alpha: number) local T0 = bit32.rshift(Alpha, 1) local T1 = Q - 1 local Modulus = Q local Num = N for I = 0, K - 1 do local Offset = I * Num * 4 for J = 0, Num - 1 do local JOffset = Offset + J * 4 local R = buffer.readu32(Src, JOffset) local T2 = R + T0 - 1 local T3 = math.floor(T2 / Alpha) local T4 = T3 * Alpha local R0 = if R >= T4 then R - T4 else R - T4 + Modulus local T5 = if R >= R0 then R - R0 else R - R0 + Modulus local Flag = (T5 == T1) local R0_ = if Flag then (if R0 >= 1 then R0 - 1 else R0 - 1 + Modulus) else R0 buffer.writeu32(Dst, JOffset, R0_) end end end function PolyVec.MultiplyByPoly(PolyBuffer: buffer, SrcVec: buffer, DstVec: buffer, K: number) local Modulus = Q local Num = N for I = 0, K - 1 do local Offset = I * Num * 4 for J = 0, Num - 1 do local JOffset = Offset + J * 4 local PolyValue = buffer.readu32(PolyBuffer, J * 4) local SrcValue = buffer.readu32(SrcVec, JOffset) local Product = (PolyValue * SrcValue) % Modulus buffer.writeu32(DstVec, JOffset, Product) end end end function PolyVec.InfinityNorm(Vec: buffer, K: number): number local Result = 0 local QBy2 = math.floor(Q / 2) local Modulus = Q local Num = N for I = 0, K - 1 do local Offset = I * Num * 4 for J = 0, Num - 1 do local JOffset = Offset + J * 4 local PolyValue = buffer.readu32(Vec, JOffset) local CurrentValue = if PolyValue > QBy2 then (if PolyValue == 0 then 0 else Modulus - PolyValue) else PolyValue if CurrentValue > Result then Result = CurrentValue end end end return Result end function PolyVec.MakeHint(PolyA: buffer, PolyB: buffer, PolyC: buffer, K: number, Alpha: number) local T0 = bit32.rshift(Alpha, 1) local T1 = Q - 1 local Num = N local Modulus = Q for I = 0, K - 1 do local Offset = I * Num * 4 for J = 0, Num - 1 do local JOffset = Offset + J * 4 local Z = buffer.readu32(PolyA, JOffset) local R = buffer.readu32(PolyB, JOffset) local T2_R = R + T0 - 1 local T3_R = math.floor(T2_R / Alpha) local T4_R = T3_R * Alpha local R0_R = if R >= T4_R then R - T4_R else R - T4_R + Modulus local T5_R = if R >= R0_R then R - R0_R else R - R0_R + Modulus local Flag_R = (T5_R == T1) local R1 = if Flag_R then 0 else T3_R local Sum = R + Z Sum = if Sum >= Modulus then Sum - Modulus else Sum local T2_V = Sum + T0 - 1 local T3_V = math.floor(T2_V / Alpha) local T4_V = T3_V * Alpha local R0_V = if Sum >= T4_V then Sum - T4_V else Sum - T4_V + Modulus local T5_V = if Sum >= R0_V then Sum - R0_V else Sum - R0_V + Modulus local Flag_V = (T5_V == T1) local V1 = if Flag_V then 0 else T3_V local Hint = if R1 ~= V1 then 1 else 0 buffer.writeu32(PolyC, JOffset, Hint) end end end function PolyVec.UseHint(PolyH: buffer, PolyR: buffer, PolyRZ: buffer, K: number, Alpha: number) local M = math.floor((Q - 1) / Alpha) local T0 = bit32.rshift(Alpha, 1) local T1 = Q - T0 local T1_Q = Q - 1 local Modulus = Q for I = 0, K - 1 do local Offset = I * N * 4 for J = 0, N - 1 do local JOffset = Offset + J * 4 local H = buffer.readu32(PolyH, JOffset) local R = buffer.readu32(PolyR, JOffset) local T2 = R + T0 - 1 local T3 = math.floor(T2 / Alpha) local T4 = T3 * Alpha local R0 = if R >= T4 then R - T4 else R - T4 + Modulus local T5 = if R >= R0 then R - R0 else R - R0 + Modulus local Flag = (T5 == T1_Q) local R1 = if Flag then 0 else T3 local R0_ = if Flag then (if R0 >= 1 then R0 - 1 else R0 - 1 + Modulus) else R0 if H == 1 then if R0_ > 0 and R0_ < T1 then R1 += 1 else R1 -= 1 end end buffer.writeu32(PolyRZ, JOffset, (R1 % M + M) % M) end end end function PolyVec.Count1s(Vec: buffer, K: number): number local Count = 0 for I = 0, K * N - 1 do local Value = buffer.readu32(Vec, I * 4) Count += Value end return Count end function PolyVec.LeftShift(Vec: buffer, K: number, D: number) local Num = N local Modulus = Q for I = 0, K - 1 do local Offset = I * Num * 4 for J = 0, Num - 1 do local JOffset = Offset + J * 4 local PolyValue = buffer.readu32(Vec, JOffset) local Shifted = bit32.lshift(PolyValue, D) local Result = if Shifted >= Modulus then Shifted % Modulus else Shifted buffer.writeu32(Vec, JOffset, Result) end end end function PolyVec.Copy(Src: buffer, Dst: buffer, K: number) buffer.copy(Dst, 0, Src, 0, K * N * 4) end return PolyVec
9,419
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/SHA3.luau
--!strict --!optimize 2 --!native local SHA3 = {} local LOW_ROUND, HIGH_ROUND = buffer.create(96), buffer.create(96) do local HighFactorKeccak = 0 local ShiftRegister = 29 local function GetNextBit(): number local Result = ShiftRegister % 2 ShiftRegister = bit32.bxor((ShiftRegister - Result) // 2, 142 * Result) return Result end for Index = 0, 23 do local LowValue = 0 local Multiplier: number for _ = 1, 6 do Multiplier = if Multiplier then Multiplier * Multiplier * 2 else 1 LowValue += GetNextBit() * Multiplier end local HighValue = GetNextBit() * Multiplier buffer.writeu32(HIGH_ROUND, Index * 4, HighValue) buffer.writeu32(LOW_ROUND, Index * 4, LowValue + HighValue * HighFactorKeccak) end end local LANES_LOW = buffer.create(100) local LANES_HIGH = buffer.create(100) local function Keccak(LanesLow: buffer, LanesHigh: buffer, InputBuffer: buffer, Offset: number, Size: number, BlockSizeInBytes: number): () local QuadWordsQuantity = BlockSizeInBytes // 8 local RCHigh, RCLow = HIGH_ROUND, LOW_ROUND for Position = Offset, Offset + Size - 1, BlockSizeInBytes do for Index = 0, (QuadWordsQuantity - 1) * 4, 4 do local BufferPos = Position + Index * 2 buffer.writeu32(LanesLow, Index, bit32.bxor( buffer.readu32(LanesLow, Index), buffer.readu32(InputBuffer, BufferPos) )) buffer.writeu32(LanesHigh, Index, bit32.bxor( buffer.readu32(LanesHigh, Index), buffer.readu32(InputBuffer, BufferPos + 4) )) end local Lane01Low, Lane01High = buffer.readu32(LanesLow, 0), buffer.readu32(LanesHigh, 0) local Lane02Low, Lane02High = buffer.readu32(LanesLow, 4), buffer.readu32(LanesHigh, 4) local Lane03Low, Lane03High = buffer.readu32(LanesLow, 8), buffer.readu32(LanesHigh, 8) local Lane04Low, Lane04High = buffer.readu32(LanesLow, 12), buffer.readu32(LanesHigh, 12) local Lane05Low, Lane05High = buffer.readu32(LanesLow, 16), buffer.readu32(LanesHigh, 16) local Lane06Low, Lane06High = buffer.readu32(LanesLow, 20), buffer.readu32(LanesHigh, 20) local Lane07Low, Lane07High = buffer.readu32(LanesLow, 24), buffer.readu32(LanesHigh, 24) local Lane08Low, Lane08High = buffer.readu32(LanesLow, 28), buffer.readu32(LanesHigh, 28) local Lane09Low, Lane09High = buffer.readu32(LanesLow, 32), buffer.readu32(LanesHigh, 32) local Lane10Low, Lane10High = buffer.readu32(LanesLow, 36), buffer.readu32(LanesHigh, 36) local Lane11Low, Lane11High = buffer.readu32(LanesLow, 40), buffer.readu32(LanesHigh, 40) local Lane12Low, Lane12High = buffer.readu32(LanesLow, 44), buffer.readu32(LanesHigh, 44) local Lane13Low, Lane13High = buffer.readu32(LanesLow, 48), buffer.readu32(LanesHigh, 48) local Lane14Low, Lane14High = buffer.readu32(LanesLow, 52), buffer.readu32(LanesHigh, 52) local Lane15Low, Lane15High = buffer.readu32(LanesLow, 56), buffer.readu32(LanesHigh, 56) local Lane16Low, Lane16High = buffer.readu32(LanesLow, 60), buffer.readu32(LanesHigh, 60) local Lane17Low, Lane17High = buffer.readu32(LanesLow, 64), buffer.readu32(LanesHigh, 64) local Lane18Low, Lane18High = buffer.readu32(LanesLow, 68), buffer.readu32(LanesHigh, 68) local Lane19Low, Lane19High = buffer.readu32(LanesLow, 72), buffer.readu32(LanesHigh, 72) local Lane20Low, Lane20High = buffer.readu32(LanesLow, 76), buffer.readu32(LanesHigh, 76) local Lane21Low, Lane21High = buffer.readu32(LanesLow, 80), buffer.readu32(LanesHigh, 80) local Lane22Low, Lane22High = buffer.readu32(LanesLow, 84), buffer.readu32(LanesHigh, 84) local Lane23Low, Lane23High = buffer.readu32(LanesLow, 88), buffer.readu32(LanesHigh, 88) local Lane24Low, Lane24High = buffer.readu32(LanesLow, 92), buffer.readu32(LanesHigh, 92) local Lane25Low, Lane25High = buffer.readu32(LanesLow, 96), buffer.readu32(LanesHigh, 96) for RoundIndex = 0, 92, 4 do local Column1Low, Column1High = bit32.bxor(Lane01Low, Lane06Low, Lane11Low, Lane16Low, Lane21Low), bit32.bxor(Lane01High, Lane06High, Lane11High, Lane16High, Lane21High) local Column2Low, Column2High = bit32.bxor(Lane02Low, Lane07Low, Lane12Low, Lane17Low, Lane22Low), bit32.bxor(Lane02High, Lane07High, Lane12High, Lane17High, Lane22High) local Column3Low, Column3High = bit32.bxor(Lane03Low, Lane08Low, Lane13Low, Lane18Low, Lane23Low), bit32.bxor(Lane03High, Lane08High, Lane13High, Lane18High, Lane23High) local Column4Low, Column4High = bit32.bxor(Lane04Low, Lane09Low, Lane14Low, Lane19Low, Lane24Low), bit32.bxor(Lane04High, Lane09High, Lane14High, Lane19High, Lane24High) local Column5Low, Column5High = bit32.bxor(Lane05Low, Lane10Low, Lane15Low, Lane20Low, Lane25Low), bit32.bxor(Lane05High, Lane10High, Lane15High, Lane20High, Lane25High) local DeltaLow, DeltaHigh = bit32.bxor(Column1Low, Column3Low * 2 + Column3High // 2147483648), bit32.bxor(Column1High, Column3High * 2 + Column3Low // 2147483648) local Temp0Low, Temp0High = bit32.bxor(DeltaLow, Lane02Low), bit32.bxor(DeltaHigh, Lane02High) local Temp1Low, Temp1High = bit32.bxor(DeltaLow, Lane07Low), bit32.bxor(DeltaHigh, Lane07High) local Temp2Low, Temp2High = bit32.bxor(DeltaLow, Lane12Low), bit32.bxor(DeltaHigh, Lane12High) local Temp3Low, Temp3High = bit32.bxor(DeltaLow, Lane17Low), bit32.bxor(DeltaHigh, Lane17High) local Temp4Low, Temp4High = bit32.bxor(DeltaLow, Lane22Low), bit32.bxor(DeltaHigh, Lane22High) Lane02Low = Temp1Low // 1048576 + (Temp1High * 4096); Lane02High = Temp1High // 1048576 + (Temp1Low * 4096) Lane07Low = Temp3Low // 524288 + (Temp3High * 8192); Lane07High = Temp3High // 524288 + (Temp3Low * 8192) Lane12Low = Temp0Low * 2 + Temp0High // 2147483648; Lane12High = Temp0High * 2 + Temp0Low // 2147483648 Lane17Low = Temp2Low * 1024 + Temp2High // 4194304; Lane17High = Temp2High * 1024 + Temp2Low // 4194304 Lane22Low = Temp4Low * 4 + Temp4High // 1073741824; Lane22High = Temp4High * 4 + Temp4Low // 1073741824 DeltaLow = bit32.bxor(Column2Low, Column4Low * 2 + Column4High // 2147483648); DeltaHigh = bit32.bxor(Column2High, Column4High * 2 + Column4Low // 2147483648) Temp0Low = bit32.bxor(DeltaLow, Lane03Low); Temp0High = bit32.bxor(DeltaHigh, Lane03High) Temp1Low = bit32.bxor(DeltaLow, Lane08Low); Temp1High = bit32.bxor(DeltaHigh, Lane08High) Temp2Low = bit32.bxor(DeltaLow, Lane13Low); Temp2High = bit32.bxor(DeltaHigh, Lane13High) Temp3Low = bit32.bxor(DeltaLow, Lane18Low); Temp3High = bit32.bxor(DeltaHigh, Lane18High) Temp4Low = bit32.bxor(DeltaLow, Lane23Low); Temp4High = bit32.bxor(DeltaHigh, Lane23High) Lane03Low = Temp2Low // 2097152 + (Temp2High * 2048); Lane03High = Temp2High // 2097152 + (Temp2Low * 2048) Lane08Low = Temp4Low // 8 + bit32.bor(Temp4High * 536870912, 0); Lane08High = Temp4High // 8 + bit32.bor(Temp4Low * 536870912, 0) Lane13Low = Temp1Low * 64 + Temp1High // 67108864; Lane13High = Temp1High * 64 + Temp1Low // 67108864 Lane18Low = (Temp3Low * 32768) + Temp3High // 131072; Lane18High = (Temp3High * 32768) + Temp3Low // 131072 Lane23Low = Temp0Low // 4 + bit32.bor(Temp0High * 1073741824, 0); Lane23High = Temp0High // 4 + bit32.bor(Temp0Low * 1073741824, 0) DeltaLow = bit32.bxor(Column3Low, Column5Low * 2 + Column5High // 2147483648); DeltaHigh = bit32.bxor(Column3High, Column5High * 2 + Column5Low // 2147483648) Temp0Low = bit32.bxor(DeltaLow, Lane04Low); Temp0High = bit32.bxor(DeltaHigh, Lane04High) Temp1Low = bit32.bxor(DeltaLow, Lane09Low); Temp1High = bit32.bxor(DeltaHigh, Lane09High) Temp2Low = bit32.bxor(DeltaLow, Lane14Low); Temp2High = bit32.bxor(DeltaHigh, Lane14High) Temp3Low = bit32.bxor(DeltaLow, Lane19Low); Temp3High = bit32.bxor(DeltaHigh, Lane19High) Temp4Low = bit32.bxor(DeltaLow, Lane24Low); Temp4High = bit32.bxor(DeltaHigh, Lane24High) Lane04Low = bit32.bor(Temp3Low * 2097152, 0) + Temp3High // 2048; Lane04High = bit32.bor(Temp3High * 2097152, 0) + Temp3Low // 2048 Lane09Low = bit32.bor(Temp0Low * 268435456, 0) + Temp0High // 16; Lane09High = bit32.bor(Temp0High * 268435456, 0) + Temp0Low // 16 Lane14Low = bit32.bor(Temp2Low * 33554432, 0) + Temp2High // 128; Lane14High = bit32.bor(Temp2High * 33554432, 0) + Temp2Low // 128 Lane19Low = Temp4Low // 256 + bit32.bor(Temp4High * 16777216, 0); Lane19High = Temp4High // 256 + bit32.bor(Temp4Low * 16777216, 0) Lane24Low = Temp1Low // 512 + bit32.bor(Temp1High * 8388608, 0); Lane24High = Temp1High // 512 + bit32.bor(Temp1Low * 8388608, 0) DeltaLow = bit32.bxor(Column4Low, Column1Low * 2 + Column1High // 2147483648); DeltaHigh = bit32.bxor(Column4High, Column1High * 2 + Column1Low // 2147483648) Temp0Low = bit32.bxor(DeltaLow, Lane05Low); Temp0High = bit32.bxor(DeltaHigh, Lane05High) Temp1Low = bit32.bxor(DeltaLow, Lane10Low); Temp1High = bit32.bxor(DeltaHigh, Lane10High) Temp2Low = bit32.bxor(DeltaLow, Lane15Low); Temp2High = bit32.bxor(DeltaHigh, Lane15High) Temp3Low = bit32.bxor(DeltaLow, Lane20Low); Temp3High = bit32.bxor(DeltaHigh, Lane20High) Temp4Low = bit32.bxor(DeltaLow, Lane25Low); Temp4High = bit32.bxor(DeltaHigh, Lane25High) Lane05Low = (Temp4Low * 16384) + Temp4High // 262144; Lane05High = (Temp4High * 16384) + Temp4Low // 262144 Lane10Low = bit32.bor(Temp1Low * 1048576, 0) + Temp1High // 4096; Lane10High = bit32.bor(Temp1High * 1048576, 0) + Temp1Low // 4096 Lane15Low = Temp3Low * 256 + Temp3High // 16777216; Lane15High = Temp3High * 256 + Temp3Low // 16777216 Lane20Low = bit32.bor(Temp0Low * 134217728, 0) + Temp0High // 32; Lane20High = bit32.bor(Temp0High * 134217728, 0) + Temp0Low // 32 Lane25Low = Temp2Low // 33554432 + Temp2High * 128; Lane25High = Temp2High // 33554432 + Temp2Low * 128 DeltaLow = bit32.bxor(Column5Low, Column2Low * 2 + Column2High // 2147483648); DeltaHigh = bit32.bxor(Column5High, Column2High * 2 + Column2Low // 2147483648) Temp1Low = bit32.bxor(DeltaLow, Lane06Low); Temp1High = bit32.bxor(DeltaHigh, Lane06High) Temp2Low = bit32.bxor(DeltaLow, Lane11Low); Temp2High = bit32.bxor(DeltaHigh, Lane11High) Temp3Low = bit32.bxor(DeltaLow, Lane16Low); Temp3High = bit32.bxor(DeltaHigh, Lane16High) Temp4Low = bit32.bxor(DeltaLow, Lane21Low); Temp4High = bit32.bxor(DeltaHigh, Lane21High) Lane06Low = Temp2Low * 8 + Temp2High // 536870912; Lane06High = Temp2High * 8 + Temp2Low // 536870912 Lane11Low = (Temp4Low * 262144) + Temp4High // 16384; Lane11High = (Temp4High * 262144) + Temp4Low // 16384 Lane16Low = Temp1Low // 268435456 + Temp1High * 16; Lane16High = Temp1High // 268435456 + Temp1Low * 16 Lane21Low = Temp3Low // 8388608 + Temp3High * 512; Lane21High = Temp3High // 8388608 + Temp3Low * 512 Lane01Low = bit32.bxor(DeltaLow, Lane01Low); Lane01High = bit32.bxor(DeltaHigh, Lane01High) Lane01Low, Lane02Low, Lane03Low, Lane04Low, Lane05Low = bit32.bxor(Lane01Low, bit32.band(-1 - Lane02Low, Lane03Low)), bit32.bxor(Lane02Low, bit32.band(-1 - Lane03Low, Lane04Low)), bit32.bxor(Lane03Low, bit32.band(-1 - Lane04Low, Lane05Low)), bit32.bxor(Lane04Low, bit32.band(-1 - Lane05Low, Lane01Low)), bit32.bxor(Lane05Low, bit32.band(-1 - Lane01Low, Lane02Low)) :: number Lane01High, Lane02High, Lane03High, Lane04High, Lane05High = bit32.bxor(Lane01High, bit32.band(-1 - Lane02High, Lane03High)), bit32.bxor(Lane02High, bit32.band(-1 - Lane03High, Lane04High)), bit32.bxor(Lane03High, bit32.band(-1 - Lane04High, Lane05High)), bit32.bxor(Lane04High, bit32.band(-1 - Lane05High, Lane01High)), bit32.bxor(Lane05High, bit32.band(-1 - Lane01High, Lane02High)) :: number Lane06Low, Lane07Low, Lane08Low, Lane09Low, Lane10Low = bit32.bxor(Lane09Low, bit32.band(-1 - Lane10Low, Lane06Low)), bit32.bxor(Lane10Low, bit32.band(-1 - Lane06Low, Lane07Low)), bit32.bxor(Lane06Low, bit32.band(-1 - Lane07Low, Lane08Low)), bit32.bxor(Lane07Low, bit32.band(-1 - Lane08Low, Lane09Low)), bit32.bxor(Lane08Low, bit32.band(-1 - Lane09Low, Lane10Low)) :: number Lane06High, Lane07High, Lane08High, Lane09High, Lane10High = bit32.bxor(Lane09High, bit32.band(-1 - Lane10High, Lane06High)), bit32.bxor(Lane10High, bit32.band(-1 - Lane06High, Lane07High)), bit32.bxor(Lane06High, bit32.band(-1 - Lane07High, Lane08High)), bit32.bxor(Lane07High, bit32.band(-1 - Lane08High, Lane09High)), bit32.bxor(Lane08High, bit32.band(-1 - Lane09High, Lane10High)) :: number Lane11Low, Lane12Low, Lane13Low, Lane14Low, Lane15Low = bit32.bxor(Lane12Low, bit32.band(-1 - Lane13Low, Lane14Low)), bit32.bxor(Lane13Low, bit32.band(-1 - Lane14Low, Lane15Low)), bit32.bxor(Lane14Low, bit32.band(-1 - Lane15Low, Lane11Low)), bit32.bxor(Lane15Low, bit32.band(-1 - Lane11Low, Lane12Low)), bit32.bxor(Lane11Low, bit32.band(-1 - Lane12Low, Lane13Low)) :: number Lane11High, Lane12High, Lane13High, Lane14High, Lane15High = bit32.bxor(Lane12High, bit32.band(-1 - Lane13High, Lane14High)), bit32.bxor(Lane13High, bit32.band(-1 - Lane14High, Lane15High)), bit32.bxor(Lane14High, bit32.band(-1 - Lane15High, Lane11High)), bit32.bxor(Lane15High, bit32.band(-1 - Lane11High, Lane12High)), bit32.bxor(Lane11High, bit32.band(-1 - Lane12High, Lane13High)) :: number Lane16Low, Lane17Low, Lane18Low, Lane19Low, Lane20Low = bit32.bxor(Lane20Low, bit32.band(-1 - Lane16Low, Lane17Low)), bit32.bxor(Lane16Low, bit32.band(-1 - Lane17Low, Lane18Low)), bit32.bxor(Lane17Low, bit32.band(-1 - Lane18Low, Lane19Low)), bit32.bxor(Lane18Low, bit32.band(-1 - Lane19Low, Lane20Low)), bit32.bxor(Lane19Low, bit32.band(-1 - Lane20Low, Lane16Low)) :: number Lane16High, Lane17High, Lane18High, Lane19High, Lane20High = bit32.bxor(Lane20High, bit32.band(-1 - Lane16High, Lane17High)), bit32.bxor(Lane16High, bit32.band(-1 - Lane17High, Lane18High)), bit32.bxor(Lane17High, bit32.band(-1 - Lane18High, Lane19High)), bit32.bxor(Lane18High, bit32.band(-1 - Lane19High, Lane20High)), bit32.bxor(Lane19High, bit32.band(-1 - Lane20High, Lane16High)) :: number Lane21Low, Lane22Low, Lane23Low, Lane24Low, Lane25Low = bit32.bxor(Lane23Low, bit32.band(-1 - Lane24Low, Lane25Low)), bit32.bxor(Lane24Low, bit32.band(-1 - Lane25Low, Lane21Low)), bit32.bxor(Lane25Low, bit32.band(-1 - Lane21Low, Lane22Low)), bit32.bxor(Lane21Low, bit32.band(-1 - Lane22Low, Lane23Low)), bit32.bxor(Lane22Low, bit32.band(-1 - Lane23Low, Lane24Low)) :: number Lane21High, Lane22High, Lane23High, Lane24High, Lane25High = bit32.bxor(Lane23High, bit32.band(-1 - Lane24High, Lane25High)), bit32.bxor(Lane24High, bit32.band(-1 - Lane25High, Lane21High)), bit32.bxor(Lane25High, bit32.band(-1 - Lane21High, Lane22High)), bit32.bxor(Lane21High, bit32.band(-1 - Lane22High, Lane23High)), bit32.bxor(Lane22High, bit32.band(-1 - Lane23High, Lane24High)) :: number Lane01Low = bit32.bxor(Lane01Low, buffer.readu32(RCLow, RoundIndex)) Lane01High = bit32.bxor(Lane01High, buffer.readu32(RCHigh, RoundIndex)) end buffer.writeu32(LanesLow, 0, Lane01Low); buffer.writeu32(LanesHigh, 0, Lane01High) buffer.writeu32(LanesLow, 4, Lane02Low); buffer.writeu32(LanesHigh, 4, Lane02High) buffer.writeu32(LanesLow, 8, Lane03Low); buffer.writeu32(LanesHigh, 8, Lane03High) buffer.writeu32(LanesLow, 12, Lane04Low); buffer.writeu32(LanesHigh, 12, Lane04High) buffer.writeu32(LanesLow, 16, Lane05Low); buffer.writeu32(LanesHigh, 16, Lane05High) buffer.writeu32(LanesLow, 20, Lane06Low); buffer.writeu32(LanesHigh, 20, Lane06High) buffer.writeu32(LanesLow, 24, Lane07Low); buffer.writeu32(LanesHigh, 24, Lane07High) buffer.writeu32(LanesLow, 28, Lane08Low); buffer.writeu32(LanesHigh, 28, Lane08High) buffer.writeu32(LanesLow, 32, Lane09Low); buffer.writeu32(LanesHigh, 32, Lane09High) buffer.writeu32(LanesLow, 36, Lane10Low); buffer.writeu32(LanesHigh, 36, Lane10High) buffer.writeu32(LanesLow, 40, Lane11Low); buffer.writeu32(LanesHigh, 40, Lane11High) buffer.writeu32(LanesLow, 44, Lane12Low); buffer.writeu32(LanesHigh, 44, Lane12High) buffer.writeu32(LanesLow, 48, Lane13Low); buffer.writeu32(LanesHigh, 48, Lane13High) buffer.writeu32(LanesLow, 52, Lane14Low); buffer.writeu32(LanesHigh, 52, Lane14High) buffer.writeu32(LanesLow, 56, Lane15Low); buffer.writeu32(LanesHigh, 56, Lane15High) buffer.writeu32(LanesLow, 60, Lane16Low); buffer.writeu32(LanesHigh, 60, Lane16High) buffer.writeu32(LanesLow, 64, Lane17Low); buffer.writeu32(LanesHigh, 64, Lane17High) buffer.writeu32(LanesLow, 68, Lane18Low); buffer.writeu32(LanesHigh, 68, Lane18High) buffer.writeu32(LanesLow, 72, Lane19Low); buffer.writeu32(LanesHigh, 72, Lane19High) buffer.writeu32(LanesLow, 76, Lane20Low); buffer.writeu32(LanesHigh, 76, Lane20High) buffer.writeu32(LanesLow, 80, Lane21Low); buffer.writeu32(LanesHigh, 80, Lane21High) buffer.writeu32(LanesLow, 84, Lane22Low); buffer.writeu32(LanesHigh, 84, Lane22High) buffer.writeu32(LanesLow, 88, Lane23Low); buffer.writeu32(LanesHigh, 88, Lane23High) buffer.writeu32(LanesLow, 92, Lane24Low); buffer.writeu32(LanesHigh, 92, Lane24High) buffer.writeu32(LanesLow, 96, Lane25Low); buffer.writeu32(LanesHigh, 96, Lane25High) end end local function ProcessSponge(Message: buffer, CapacityBits: number, OutputBytes: number, DomainSeparator: number): buffer local RateBytes = (1600 - CapacityBits) // 8 buffer.fill(LANES_LOW, 0, 0, 100) buffer.fill(LANES_HIGH, 0, 0, 100) local LanesLow = LANES_LOW local LanesHigh = LANES_HIGH local MessageLength: number = buffer.len(Message) local PaddedLength: number = MessageLength + 1 local Remainder = PaddedLength % RateBytes if Remainder ~= 0 then PaddedLength += (RateBytes - Remainder) end local PaddedMessage = buffer.create(PaddedLength) if MessageLength > 0 then buffer.copy(PaddedMessage, 0, Message, 0, MessageLength) end if PaddedLength - MessageLength == 1 then buffer.writeu8(PaddedMessage, MessageLength, bit32.bor(DomainSeparator, 0x80)) else buffer.writeu8(PaddedMessage, MessageLength, DomainSeparator) if PaddedLength - MessageLength > 2 then buffer.fill(PaddedMessage, MessageLength + 1, 0, PaddedLength - MessageLength - 2) end buffer.writeu8(PaddedMessage, PaddedLength - 1, 0x80) end Keccak(LanesLow, LanesHigh, PaddedMessage, 0, PaddedLength, RateBytes) local Output = buffer.create(OutputBytes) local OutputOffset = 0 local ZeroBuffer = buffer.create(RateBytes) while OutputOffset < OutputBytes do local BytesThisRound = math.min(RateBytes, OutputBytes - OutputOffset) for ByteIndex = 0, BytesThisRound - 1 do local AbsoluteIndex = OutputOffset + ByteIndex if AbsoluteIndex < OutputBytes then local Lane = ByteIndex // 8 local ByteInLane = ByteIndex % 8 local LaneOffset = Lane * 4 local Value if ByteInLane < 4 then Value = bit32.extract(buffer.readu32(LanesLow, LaneOffset), ByteInLane * 8, 8) else Value = bit32.extract(buffer.readu32(LanesHigh, LaneOffset), (ByteInLane - 4) * 8, 8) end buffer.writeu8(Output, AbsoluteIndex, Value) end end OutputOffset += BytesThisRound if OutputOffset < OutputBytes then Keccak(LanesLow, LanesHigh, ZeroBuffer, 0, RateBytes, RateBytes) end end return Output end function SHA3.SHAKE128(Message: buffer, OutputBytes: number): buffer return ProcessSponge(Message, 256, OutputBytes, 0x1F) end function SHA3.SHAKE256(Message: buffer, OutputBytes: number): buffer return ProcessSponge(Message, 512, OutputBytes, 0x1F) end return SHA3
6,803
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/Sampling.luau
--[=[ ML-DSA Sampling Example usage: local Sampling = require(script) local Rho = buffer.create(32) local Matrix = buffer.create(4 * 4 * 256 * 4) Sampling.ExpandA(Rho, Matrix, 4, 4) --]=] --!strict --!optimize 2 --!native local XOF = require("./XOF") local Params = require("./Params") local N = 256 local Q = 8380417 local Sampling = {} local WORKSPACE_MSG_34 = buffer.create(34) local WORKSPACE_MSG_66 = buffer.create(66) function Sampling.ExpandA(Rho: buffer, Mat: buffer, K: number, L: number) buffer.copy(WORKSPACE_MSG_34, 0, Rho, 0, 32) local Message = WORKSPACE_MSG_34 local Num = N local Modulus = Q local XOF = XOF for I = 0, K - 1 do for J = 0, L - 1 do local Offset = (I * L + J) * Num * 4 buffer.writeu8(Message, 32, J) buffer.writeu8(Message, 33, I) XOF.Reset128() XOF.Absorb128(Message) local CoeffCount = 0 local ChunkSize = 504 while CoeffCount < Num do local TotalOutput = XOF.Squeeze128(ChunkSize) local ByteOffset = 0 local OutputLen = buffer.len(TotalOutput) while CoeffCount < Num and ByteOffset + 5 < OutputLen do local Chunk = buffer.readu32(TotalOutput, ByteOffset) local B3 = buffer.readu8(TotalOutput, ByteOffset + 4) local B4 = buffer.readu8(TotalOutput, ByteOffset + 5) local T3 = bit32.band(Chunk, 0x7FFFFF) if T3 < Modulus then buffer.writeu32(Mat, Offset + CoeffCount * 4, T3) CoeffCount += 1 end local T4 = bit32.bor( bit32.rshift(Chunk, 24), bit32.lshift(B3, 8), bit32.lshift(bit32.band(B4, 0x7F), 16) ) if T4 < Modulus and CoeffCount < Num then buffer.writeu32(Mat, Offset + CoeffCount * 4, T4) CoeffCount += 1 end ByteOffset += 6 end while CoeffCount < Num and ByteOffset + 2 < OutputLen do local T0 = bit32.band(buffer.readu8(TotalOutput, ByteOffset + 2), 0x7F) local T1 = buffer.readu8(TotalOutput, ByteOffset + 1) local T2 = buffer.readu8(TotalOutput, ByteOffset) local T3 = bit32.bor( bit32.lshift(T0, 16), bit32.lshift(T1, 8), T2 ) if T3 < Modulus then buffer.writeu32(Mat, Offset + CoeffCount * 4, T3) CoeffCount += 1 end ByteOffset += 3 end end end end end function Sampling.ExpandS(RhoPrime: buffer, Vec: buffer, Eta: number, K: number, StartNonce: number) if not Params.CheckEta(Eta) or not Params.CheckNonce(StartNonce) then error("Invalid parameters for ExpandS") end buffer.copy(WORKSPACE_MSG_66, 0, RhoPrime, 0, 64) local Message = WORKSPACE_MSG_66 local Num = N local Modulus = Q for I = 0, K - 1 do local Offset = I * Num * 4 local NewNonce = StartNonce + I buffer.writeu8(Message, 64, bit32.band(NewNonce, 0xFF)) buffer.writeu8(Message, 65, bit32.band(bit32.rshift(NewNonce, 8), 0xFF)) XOF.Reset256() XOF.Absorb256(Message) local CoeffCount = 0 local ChunkSize = if Eta == 2 then 136 else 272 while CoeffCount < Num do local TotalOutput = XOF.Squeeze256(ChunkSize) local ByteOffset = 0 local OutputLen = buffer.len(TotalOutput) if Eta == 2 then while CoeffCount < Num and ByteOffset + 3 < OutputLen do local Chunk = buffer.readu32(TotalOutput, ByteOffset) local T0 = bit32.band(Chunk, 0x0F) local T1 = bit32.band(bit32.rshift(Chunk, 4), 0x0F) local T2 = bit32.band(bit32.rshift(Chunk, 8), 0x0F) local T3 = bit32.band(bit32.rshift(Chunk, 12), 0x0F) local T4 = bit32.band(bit32.rshift(Chunk, 16), 0x0F) local T5 = bit32.band(bit32.rshift(Chunk, 20), 0x0F) local T6 = bit32.band(bit32.rshift(Chunk, 24), 0x0F) local T7 = bit32.band(bit32.rshift(Chunk, 28), 0x0F) if T0 < 15 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T0 % 5) + (if (T0 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end if T1 < 15 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T1 % 5) + (if (T1 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end if T2 < 15 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T2 % 5) + (if (T2 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end if T3 < 15 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T3 % 5) + (if (T3 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end if T4 < 15 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T4 % 5) + (if (T4 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end if T5 < 15 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T5 % 5) + (if (T5 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end if T6 < 15 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T6 % 5) + (if (T6 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end if T7 < 15 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T7 % 5) + (if (T7 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end ByteOffset += 4 end else while CoeffCount < Num and ByteOffset + 3 < OutputLen do local Chunk = buffer.readu32(TotalOutput, ByteOffset) local T0 = bit32.band(Chunk, 0x0F) local T1 = bit32.band(bit32.rshift(Chunk, 4), 0x0F) local T2 = bit32.band(bit32.rshift(Chunk, 8), 0x0F) local T3 = bit32.band(bit32.rshift(Chunk, 12), 0x0F) local T4 = bit32.band(bit32.rshift(Chunk, 16), 0x0F) local T5 = bit32.band(bit32.rshift(Chunk, 20), 0x0F) local T6 = bit32.band(bit32.rshift(Chunk, 24), 0x0F) local T7 = bit32.band(bit32.rshift(Chunk, 28), 0x0F) if T0 < 9 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T0 + (if T0 > 4 then Modulus else 0)) CoeffCount += 1 end if T1 < 9 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T1 + (if T1 > 4 then Modulus else 0)) CoeffCount += 1 end if T2 < 9 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T2 + (if T2 > 4 then Modulus else 0)) CoeffCount += 1 end if T3 < 9 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T3 + (if T3 > 4 then Modulus else 0)) CoeffCount += 1 end if T4 < 9 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T4 + (if T4 > 4 then Modulus else 0)) CoeffCount += 1 end if T5 < 9 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T5 + (if T5 > 4 then Modulus else 0)) CoeffCount += 1 end if T6 < 9 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T6 + (if T6 > 4 then Modulus else 0)) CoeffCount += 1 end if T7 < 9 and CoeffCount < Num then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T7 + (if T7 > 4 then Modulus else 0)) CoeffCount += 1 end ByteOffset += 4 end end while CoeffCount < Num and ByteOffset < OutputLen do local Byte = buffer.readu8(TotalOutput, ByteOffset) local T0 = bit32.band(Byte, 0x0F) local T1 = bit32.band(bit32.rshift(Byte, 4), 0x0F) if Eta == 2 then if T0 < 15 then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T0 % 5) + (if (T0 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end if CoeffCount < Num and T1 < 15 then buffer.writeu32(Vec, Offset + CoeffCount * 4, 2 - (T1 % 5) + (if (T1 % 5) > 2 then Modulus else 0)) CoeffCount += 1 end else if T0 < 9 then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T0 + (if T0 > 4 then Modulus else 0)) CoeffCount += 1 end if CoeffCount < Num and T1 < 9 then buffer.writeu32(Vec, Offset + CoeffCount * 4, 4 - T1 + (if T1 > 4 then Modulus else 0)) CoeffCount += 1 end end ByteOffset += 1 end end end end function Sampling.ExpandMask(Seed: buffer, Nonce: number, Vec: buffer, Gamma1: number, L: number) if not Params.CheckGamma1(Gamma1) then error("Invalid Gamma1 parameter") end local Gamma1BitWidth = if Gamma1 == 131072 then 18 else 20 local BufSize = math.floor((N * Gamma1BitWidth) / 8) buffer.copy(WORKSPACE_MSG_66, 0, Seed, 0, 64) local Message = WORKSPACE_MSG_66 local Num = N local Modulus = Q local G1 = Gamma1 for I = 0, L - 1 do local Offset = I * Num * 4 local NewNonce = Nonce + I buffer.writeu8(Message, 64, bit32.band(NewNonce, 0xFF)) buffer.writeu8(Message, 65, bit32.band(bit32.rshift(NewNonce, 8), 0xFF)) XOF.Reset256() XOF.Absorb256(Message) local Src = XOF.Squeeze256(BufSize) if Gamma1BitWidth == 18 then for J = 0, 63 do local BOffset = J * 9 local POffset = Offset + J * 16 local B0 = buffer.readu8(Src, BOffset + 0) local B1 = buffer.readu8(Src, BOffset + 1) local B2 = buffer.readu8(Src, BOffset + 2) local B3 = buffer.readu8(Src, BOffset + 3) local B4 = buffer.readu8(Src, BOffset + 4) local B5 = buffer.readu8(Src, BOffset + 5) local B6 = buffer.readu8(Src, BOffset + 6) local B7 = buffer.readu8(Src, BOffset + 7) local B8 = buffer.readu8(Src, BOffset + 8) local V0 = bit32.bor(B0, bit32.lshift(B1, 8), bit32.lshift(bit32.band(B2, 0x3), 16)) local V1 = bit32.bor(bit32.rshift(B2, 2), bit32.lshift(B3, 6), bit32.lshift(bit32.band(B4, 0xF), 14)) local V2 = bit32.bor(bit32.rshift(B4, 4), bit32.lshift(B5, 4), bit32.lshift(bit32.band(B6, 0x3F), 12)) local V3 = bit32.bor(bit32.rshift(B6, 6), bit32.lshift(B7, 2), bit32.lshift(B8, 10)) local D0 = G1 - V0 local D1 = G1 - V1 local D2 = G1 - V2 local D3 = G1 - V3 buffer.writeu32(Vec, POffset + 0, if D0 < 0 then D0 + Modulus else D0) buffer.writeu32(Vec, POffset + 4, if D1 < 0 then D1 + Modulus else D1) buffer.writeu32(Vec, POffset + 8, if D2 < 0 then D2 + Modulus else D2) buffer.writeu32(Vec, POffset + 12, if D3 < 0 then D3 + Modulus else D3) end else for J = 0, 63 do local BOffset = J * 10 local POffset = Offset + J * 16 local B0 = buffer.readu8(Src, BOffset + 0) local B1 = buffer.readu8(Src, BOffset + 1) local B2 = buffer.readu8(Src, BOffset + 2) local B3 = buffer.readu8(Src, BOffset + 3) local B4 = buffer.readu8(Src, BOffset + 4) local B5 = buffer.readu8(Src, BOffset + 5) local B6 = buffer.readu8(Src, BOffset + 6) local B7 = buffer.readu8(Src, BOffset + 7) local B8 = buffer.readu8(Src, BOffset + 8) local B9 = buffer.readu8(Src, BOffset + 9) local V0 = bit32.bor(B0, bit32.lshift(B1, 8), bit32.lshift(bit32.band(B2, 0xF), 16)) local V1 = bit32.bor(bit32.rshift(B2, 4), bit32.lshift(B3, 4), bit32.lshift(B4, 12)) local V2 = bit32.bor(B5, bit32.lshift(B6, 8), bit32.lshift(bit32.band(B7, 0xF), 16)) local V3 = bit32.bor(bit32.rshift(B7, 4), bit32.lshift(B8, 4), bit32.lshift(B9, 12)) local D0 = G1 - V0 local D1 = G1 - V1 local D2 = G1 - V2 local D3 = G1 - V3 buffer.writeu32(Vec, POffset + 0, if D0 < 0 then D0 + Modulus else D0) buffer.writeu32(Vec, POffset + 4, if D1 < 0 then D1 + Modulus else D1) buffer.writeu32(Vec, POffset + 8, if D2 < 0 then D2 + Modulus else D2) buffer.writeu32(Vec, POffset + 12, if D3 < 0 then D3 + Modulus else D3) end end end end function Sampling.SampleInBall(Seed: buffer, Poly: buffer, Tau: number, Lambda: number) if not Params.CheckTau(Tau) then error("Invalid Tau parameter") end buffer.fill(Poly, 0, 0, N * 4) XOF.Reset256() XOF.Absorb256(Seed) local TauBits = XOF.Squeeze256(8) local TauBitsLow = buffer.readu32(TauBits, 0) local TauBitsHigh = buffer.readu32(TauBits, 4) local From = N - Tau local I = From local ChunkSize = 136 local Modulus = Q while I < N do local RandomBytes = XOF.Squeeze256(ChunkSize) local ByteOffset = 0 local OutputLen = buffer.len(RandomBytes) while I < N and ByteOffset + 3 < OutputLen do local Chunk = buffer.readu32(RandomBytes, ByteOffset) for B = 0, 3 do if I >= N then break end local J = bit32.band(bit32.rshift(Chunk, B * 8), 0xFF) if J <= I then local TauBit = I - From local S if TauBit < 32 then S = bit32.band(bit32.rshift(TauBitsLow, TauBit), 1) else S = bit32.band(bit32.rshift(TauBitsHigh, TauBit - 32), 1) end buffer.writeu32(Poly, I * 4, buffer.readu32(Poly, J * 4)) buffer.writeu32(Poly, J * 4, if S == 0 then 1 else Modulus - 1) I += 1 end end ByteOffset += 4 end while I < N and ByteOffset < OutputLen do local J = buffer.readu8(RandomBytes, ByteOffset) if J <= I then local TauBit = I - From local S if TauBit < 32 then S = bit32.band(bit32.rshift(TauBitsLow, TauBit), 1) else S = bit32.band(bit32.rshift(TauBitsHigh, TauBit - 32), 1) end buffer.writeu32(Poly, I * 4, buffer.readu32(Poly, J * 4)) buffer.writeu32(Poly, J * 4, if S == 0 then 1 else Modulus - 1) I += 1 end ByteOffset += 1 end end end return Sampling
4,853
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/Utils.luau
--[=[ Utility functions for ML-DSA key and signature sizes ML-DSA parameters. Example usage: local Utils = require(script) local PubKeySize = Utils.PubKeyLen(4, 13) -- 1312 bytes for ML-DSA-44 local SecKeySize = Utils.SecKeyLen(4, 4, 2, 13) -- 2560 bytes local SigSize = Utils.SigLen(4, 4, 131072, 80, 128) -- Variable --]=] --!strict --!optimize 2 --!native local Q_BIT_WIDTH = 23 local Utils = {} local function BitWidth(Value: number): number if Value == 0 then return 0 end local Width = 0 local TempValue = Value while TempValue > 0 do Width += 1 TempValue = bit32.rshift(TempValue, 1) end return Width end function Utils.PubKeyLen(K: number, D: number): number local T1Bw = Q_BIT_WIDTH - D local PkLen = 32 + K * 32 * T1Bw return PkLen end function Utils.SecKeyLen(K: number, L: number, Eta: number, D: number): number local EtaBw = BitWidth(2 * Eta) local SkLen = 32 + 32 + 64 + 32 * (EtaBw * (K + L) + K * D) return SkLen end function Utils.SigLen(K: number, L: number, Gamma1: number, Omega: number, Lambda: number): number local Gamma1Bw = BitWidth(Gamma1) local SigLen = math.floor((2 * Lambda) / 8) + (32 * L * Gamma1Bw) + (Omega + K) return SigLen end function Utils.BitWidth(Value: number): number return BitWidth(Value) end return Utils
448
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/XOF.luau
--[=[ Stateful SHAKE XOF (Extensible Output Function) Non-OOP implementation with reusable state buffers. For ML-DSA sampling functions that use rejection sampling. Example usage: local XOF = require(script) XOF.Reset128() XOF.Absorb128(message) local Chunk1 = XOF.Squeeze128(168) local Chunk2 = XOF.Squeeze128(168) --]=] --!strict --!optimize 2 --!native local RATE_128 = 168 local RATE_256 = 136 local LanesLow128 = buffer.create(100) local LanesHigh128 = buffer.create(100) local SqueezeOffset128 = 0 local LanesLow256 = buffer.create(100) local LanesHigh256 = buffer.create(100) local SqueezeOffset256 = 0 local ZeroBuffer128 = buffer.create(RATE_128) local ZeroBuffer256 = buffer.create(RATE_256) local PaddedBuffer128 = buffer.create(RATE_128) local PaddedBuffer256 = buffer.create(RATE_256) local SqueezeBuffer128_168 = buffer.create(168) local SqueezeBuffer256_128 = buffer.create(128) local SqueezeBuffer256_192 = buffer.create(192) local LOW_ROUND, HIGH_ROUND = buffer.create(96), buffer.create(96) do local HighFactorKeccak = 0 local ShiftRegister = 29 local function GetNextBit(): number local Result = ShiftRegister % 2 ShiftRegister = bit32.bxor((ShiftRegister - Result) // 2, 142 * Result) return Result end for Index = 0, 23 do local LowValue = 0 local Multiplier: number for _ = 1, 6 do Multiplier = if Multiplier then Multiplier * Multiplier * 2 else 1 LowValue += GetNextBit() * Multiplier end local HighValue = GetNextBit() * Multiplier buffer.writeu32(HIGH_ROUND, Index * 4, HighValue) buffer.writeu32(LOW_ROUND, Index * 4, LowValue + HighValue * HighFactorKeccak) end end local function Keccak(LanesLow: buffer, LanesHigh: buffer, InputBuffer: buffer, Offset: number, Size: number, BlockSizeInBytes: number): () local QuadWordsQuantity = BlockSizeInBytes // 8 local RCHigh, RCLow = HIGH_ROUND, LOW_ROUND for Position = Offset, Offset + Size - 1, BlockSizeInBytes do for Index = 0, (QuadWordsQuantity - 1) * 4, 4 do local BufferPos = Position + Index * 2 buffer.writeu32(LanesLow, Index, bit32.bxor( buffer.readu32(LanesLow, Index), buffer.readu32(InputBuffer, BufferPos) )) buffer.writeu32(LanesHigh, Index, bit32.bxor( buffer.readu32(LanesHigh, Index), buffer.readu32(InputBuffer, BufferPos + 4) )) end local Lane01Low, Lane01High = buffer.readu32(LanesLow, 0), buffer.readu32(LanesHigh, 0) local Lane02Low, Lane02High = buffer.readu32(LanesLow, 4), buffer.readu32(LanesHigh, 4) local Lane03Low, Lane03High = buffer.readu32(LanesLow, 8), buffer.readu32(LanesHigh, 8) local Lane04Low, Lane04High = buffer.readu32(LanesLow, 12), buffer.readu32(LanesHigh, 12) local Lane05Low, Lane05High = buffer.readu32(LanesLow, 16), buffer.readu32(LanesHigh, 16) local Lane06Low, Lane06High = buffer.readu32(LanesLow, 20), buffer.readu32(LanesHigh, 20) local Lane07Low, Lane07High = buffer.readu32(LanesLow, 24), buffer.readu32(LanesHigh, 24) local Lane08Low, Lane08High = buffer.readu32(LanesLow, 28), buffer.readu32(LanesHigh, 28) local Lane09Low, Lane09High = buffer.readu32(LanesLow, 32), buffer.readu32(LanesHigh, 32) local Lane10Low, Lane10High = buffer.readu32(LanesLow, 36), buffer.readu32(LanesHigh, 36) local Lane11Low, Lane11High = buffer.readu32(LanesLow, 40), buffer.readu32(LanesHigh, 40) local Lane12Low, Lane12High = buffer.readu32(LanesLow, 44), buffer.readu32(LanesHigh, 44) local Lane13Low, Lane13High = buffer.readu32(LanesLow, 48), buffer.readu32(LanesHigh, 48) local Lane14Low, Lane14High = buffer.readu32(LanesLow, 52), buffer.readu32(LanesHigh, 52) local Lane15Low, Lane15High = buffer.readu32(LanesLow, 56), buffer.readu32(LanesHigh, 56) local Lane16Low, Lane16High = buffer.readu32(LanesLow, 60), buffer.readu32(LanesHigh, 60) local Lane17Low, Lane17High = buffer.readu32(LanesLow, 64), buffer.readu32(LanesHigh, 64) local Lane18Low, Lane18High = buffer.readu32(LanesLow, 68), buffer.readu32(LanesHigh, 68) local Lane19Low, Lane19High = buffer.readu32(LanesLow, 72), buffer.readu32(LanesHigh, 72) local Lane20Low, Lane20High = buffer.readu32(LanesLow, 76), buffer.readu32(LanesHigh, 76) local Lane21Low, Lane21High = buffer.readu32(LanesLow, 80), buffer.readu32(LanesHigh, 80) local Lane22Low, Lane22High = buffer.readu32(LanesLow, 84), buffer.readu32(LanesHigh, 84) local Lane23Low, Lane23High = buffer.readu32(LanesLow, 88), buffer.readu32(LanesHigh, 88) local Lane24Low, Lane24High = buffer.readu32(LanesLow, 92), buffer.readu32(LanesHigh, 92) local Lane25Low, Lane25High = buffer.readu32(LanesLow, 96), buffer.readu32(LanesHigh, 96) for RoundIndex = 0, 92, 4 do local Column1Low, Column1High = bit32.bxor(Lane01Low, Lane06Low, Lane11Low, Lane16Low, Lane21Low), bit32.bxor(Lane01High, Lane06High, Lane11High, Lane16High, Lane21High) local Column2Low, Column2High = bit32.bxor(Lane02Low, Lane07Low, Lane12Low, Lane17Low, Lane22Low), bit32.bxor(Lane02High, Lane07High, Lane12High, Lane17High, Lane22High) local Column3Low, Column3High = bit32.bxor(Lane03Low, Lane08Low, Lane13Low, Lane18Low, Lane23Low), bit32.bxor(Lane03High, Lane08High, Lane13High, Lane18High, Lane23High) local Column4Low, Column4High = bit32.bxor(Lane04Low, Lane09Low, Lane14Low, Lane19Low, Lane24Low), bit32.bxor(Lane04High, Lane09High, Lane14High, Lane19High, Lane24High) local Column5Low, Column5High = bit32.bxor(Lane05Low, Lane10Low, Lane15Low, Lane20Low, Lane25Low), bit32.bxor(Lane05High, Lane10High, Lane15High, Lane20High, Lane25High) local DeltaLow, DeltaHigh = bit32.bxor(Column1Low, Column3Low * 2 + Column3High // 2147483648), bit32.bxor(Column1High, Column3High * 2 + Column3Low // 2147483648) local Temp0Low, Temp0High = bit32.bxor(DeltaLow, Lane02Low), bit32.bxor(DeltaHigh, Lane02High) local Temp1Low, Temp1High = bit32.bxor(DeltaLow, Lane07Low), bit32.bxor(DeltaHigh, Lane07High) local Temp2Low, Temp2High = bit32.bxor(DeltaLow, Lane12Low), bit32.bxor(DeltaHigh, Lane12High) local Temp3Low, Temp3High = bit32.bxor(DeltaLow, Lane17Low), bit32.bxor(DeltaHigh, Lane17High) local Temp4Low, Temp4High = bit32.bxor(DeltaLow, Lane22Low), bit32.bxor(DeltaHigh, Lane22High) Lane02Low = Temp1Low // 1048576 + (Temp1High * 4096); Lane02High = Temp1High // 1048576 + (Temp1Low * 4096) Lane07Low = Temp3Low // 524288 + (Temp3High * 8192); Lane07High = Temp3High // 524288 + (Temp3Low * 8192) Lane12Low = Temp0Low * 2 + Temp0High // 2147483648; Lane12High = Temp0High * 2 + Temp0Low // 2147483648 Lane17Low = Temp2Low * 1024 + Temp2High // 4194304; Lane17High = Temp2High * 1024 + Temp2Low // 4194304 Lane22Low = Temp4Low * 4 + Temp4High // 1073741824; Lane22High = Temp4High * 4 + Temp4Low // 1073741824 DeltaLow = bit32.bxor(Column2Low, Column4Low * 2 + Column4High // 2147483648); DeltaHigh = bit32.bxor(Column2High, Column4High * 2 + Column4Low // 2147483648) Temp0Low = bit32.bxor(DeltaLow, Lane03Low); Temp0High = bit32.bxor(DeltaHigh, Lane03High) Temp1Low = bit32.bxor(DeltaLow, Lane08Low); Temp1High = bit32.bxor(DeltaHigh, Lane08High) Temp2Low = bit32.bxor(DeltaLow, Lane13Low); Temp2High = bit32.bxor(DeltaHigh, Lane13High) Temp3Low = bit32.bxor(DeltaLow, Lane18Low); Temp3High = bit32.bxor(DeltaHigh, Lane18High) Temp4Low = bit32.bxor(DeltaLow, Lane23Low); Temp4High = bit32.bxor(DeltaHigh, Lane23High) Lane03Low = Temp2Low // 2097152 + (Temp2High * 2048); Lane03High = Temp2High // 2097152 + (Temp2Low * 2048) Lane08Low = Temp4Low // 8 + bit32.bor(Temp4High * 536870912, 0); Lane08High = Temp4High // 8 + bit32.bor(Temp4Low * 536870912, 0) Lane13Low = Temp1Low * 64 + Temp1High // 67108864; Lane13High = Temp1High * 64 + Temp1Low // 67108864 Lane18Low = (Temp3Low * 32768) + Temp3High // 131072; Lane18High = (Temp3High * 32768) + Temp3Low // 131072 Lane23Low = Temp0Low // 4 + bit32.bor(Temp0High * 1073741824, 0); Lane23High = Temp0High // 4 + bit32.bor(Temp0Low * 1073741824, 0) DeltaLow = bit32.bxor(Column3Low, Column5Low * 2 + Column5High // 2147483648); DeltaHigh = bit32.bxor(Column3High, Column5High * 2 + Column5Low // 2147483648) Temp0Low = bit32.bxor(DeltaLow, Lane04Low); Temp0High = bit32.bxor(DeltaHigh, Lane04High) Temp1Low = bit32.bxor(DeltaLow, Lane09Low); Temp1High = bit32.bxor(DeltaHigh, Lane09High) Temp2Low = bit32.bxor(DeltaLow, Lane14Low); Temp2High = bit32.bxor(DeltaHigh, Lane14High) Temp3Low = bit32.bxor(DeltaLow, Lane19Low); Temp3High = bit32.bxor(DeltaHigh, Lane19High) Temp4Low = bit32.bxor(DeltaLow, Lane24Low); Temp4High = bit32.bxor(DeltaHigh, Lane24High) Lane04Low = bit32.bor(Temp3Low * 2097152, 0) + Temp3High // 2048; Lane04High = bit32.bor(Temp3High * 2097152, 0) + Temp3Low // 2048 Lane09Low = bit32.bor(Temp0Low * 268435456, 0) + Temp0High // 16; Lane09High = bit32.bor(Temp0High * 268435456, 0) + Temp0Low // 16 Lane14Low = bit32.bor(Temp2Low * 33554432, 0) + Temp2High // 128; Lane14High = bit32.bor(Temp2High * 33554432, 0) + Temp2Low // 128 Lane19Low = Temp4Low // 256 + bit32.bor(Temp4High * 16777216, 0); Lane19High = Temp4High // 256 + bit32.bor(Temp4Low * 16777216, 0) Lane24Low = Temp1Low // 512 + bit32.bor(Temp1High * 8388608, 0); Lane24High = Temp1High // 512 + bit32.bor(Temp1Low * 8388608, 0) DeltaLow = bit32.bxor(Column4Low, Column1Low * 2 + Column1High // 2147483648); DeltaHigh = bit32.bxor(Column4High, Column1High * 2 + Column1Low // 2147483648) Temp0Low = bit32.bxor(DeltaLow, Lane05Low); Temp0High = bit32.bxor(DeltaHigh, Lane05High) Temp1Low = bit32.bxor(DeltaLow, Lane10Low); Temp1High = bit32.bxor(DeltaHigh, Lane10High) Temp2Low = bit32.bxor(DeltaLow, Lane15Low); Temp2High = bit32.bxor(DeltaHigh, Lane15High) Temp3Low = bit32.bxor(DeltaLow, Lane20Low); Temp3High = bit32.bxor(DeltaHigh, Lane20High) Temp4Low = bit32.bxor(DeltaLow, Lane25Low); Temp4High = bit32.bxor(DeltaHigh, Lane25High) Lane05Low = (Temp4Low * 16384) + Temp4High // 262144; Lane05High = (Temp4High * 16384) + Temp4Low // 262144 Lane10Low = bit32.bor(Temp1Low * 1048576, 0) + Temp1High // 4096; Lane10High = bit32.bor(Temp1High * 1048576, 0) + Temp1Low // 4096 Lane15Low = Temp3Low * 256 + Temp3High // 16777216; Lane15High = Temp3High * 256 + Temp3Low // 16777216 Lane20Low = bit32.bor(Temp0Low * 134217728, 0) + Temp0High // 32; Lane20High = bit32.bor(Temp0High * 134217728, 0) + Temp0Low // 32 Lane25Low = Temp2Low // 33554432 + Temp2High * 128; Lane25High = Temp2High // 33554432 + Temp2Low * 128 DeltaLow = bit32.bxor(Column5Low, Column2Low * 2 + Column2High // 2147483648); DeltaHigh = bit32.bxor(Column5High, Column2High * 2 + Column2Low // 2147483648) Temp1Low = bit32.bxor(DeltaLow, Lane06Low); Temp1High = bit32.bxor(DeltaHigh, Lane06High) Temp2Low = bit32.bxor(DeltaLow, Lane11Low); Temp2High = bit32.bxor(DeltaHigh, Lane11High) Temp3Low = bit32.bxor(DeltaLow, Lane16Low); Temp3High = bit32.bxor(DeltaHigh, Lane16High) Temp4Low = bit32.bxor(DeltaLow, Lane21Low); Temp4High = bit32.bxor(DeltaHigh, Lane21High) Lane06Low = Temp2Low * 8 + Temp2High // 536870912; Lane06High = Temp2High * 8 + Temp2Low // 536870912 Lane11Low = (Temp4Low * 262144) + Temp4High // 16384; Lane11High = (Temp4High * 262144) + Temp4Low // 16384 Lane16Low = Temp1Low // 268435456 + Temp1High * 16; Lane16High = Temp1High // 268435456 + Temp1Low * 16 Lane21Low = Temp3Low // 8388608 + Temp3High * 512; Lane21High = Temp3High // 8388608 + Temp3Low * 512 Lane01Low = bit32.bxor(DeltaLow, Lane01Low); Lane01High = bit32.bxor(DeltaHigh, Lane01High) Lane01Low, Lane02Low, Lane03Low, Lane04Low, Lane05Low = bit32.bxor(Lane01Low, bit32.band(-1 - Lane02Low, Lane03Low)), bit32.bxor(Lane02Low, bit32.band(-1 - Lane03Low, Lane04Low)), bit32.bxor(Lane03Low, bit32.band(-1 - Lane04Low, Lane05Low)), bit32.bxor(Lane04Low, bit32.band(-1 - Lane05Low, Lane01Low)), bit32.bxor(Lane05Low, bit32.band(-1 - Lane01Low, Lane02Low)) :: number Lane01High, Lane02High, Lane03High, Lane04High, Lane05High = bit32.bxor(Lane01High, bit32.band(-1 - Lane02High, Lane03High)), bit32.bxor(Lane02High, bit32.band(-1 - Lane03High, Lane04High)), bit32.bxor(Lane03High, bit32.band(-1 - Lane04High, Lane05High)), bit32.bxor(Lane04High, bit32.band(-1 - Lane05High, Lane01High)), bit32.bxor(Lane05High, bit32.band(-1 - Lane01High, Lane02High)) :: number Lane06Low, Lane07Low, Lane08Low, Lane09Low, Lane10Low = bit32.bxor(Lane09Low, bit32.band(-1 - Lane10Low, Lane06Low)), bit32.bxor(Lane10Low, bit32.band(-1 - Lane06Low, Lane07Low)), bit32.bxor(Lane06Low, bit32.band(-1 - Lane07Low, Lane08Low)), bit32.bxor(Lane07Low, bit32.band(-1 - Lane08Low, Lane09Low)), bit32.bxor(Lane08Low, bit32.band(-1 - Lane09Low, Lane10Low)) :: number Lane06High, Lane07High, Lane08High, Lane09High, Lane10High = bit32.bxor(Lane09High, bit32.band(-1 - Lane10High, Lane06High)), bit32.bxor(Lane10High, bit32.band(-1 - Lane06High, Lane07High)), bit32.bxor(Lane06High, bit32.band(-1 - Lane07High, Lane08High)), bit32.bxor(Lane07High, bit32.band(-1 - Lane08High, Lane09High)), bit32.bxor(Lane08High, bit32.band(-1 - Lane09High, Lane10High)) :: number Lane11Low, Lane12Low, Lane13Low, Lane14Low, Lane15Low = bit32.bxor(Lane12Low, bit32.band(-1 - Lane13Low, Lane14Low)), bit32.bxor(Lane13Low, bit32.band(-1 - Lane14Low, Lane15Low)), bit32.bxor(Lane14Low, bit32.band(-1 - Lane15Low, Lane11Low)), bit32.bxor(Lane15Low, bit32.band(-1 - Lane11Low, Lane12Low)), bit32.bxor(Lane11Low, bit32.band(-1 - Lane12Low, Lane13Low)) :: number Lane11High, Lane12High, Lane13High, Lane14High, Lane15High = bit32.bxor(Lane12High, bit32.band(-1 - Lane13High, Lane14High)), bit32.bxor(Lane13High, bit32.band(-1 - Lane14High, Lane15High)), bit32.bxor(Lane14High, bit32.band(-1 - Lane15High, Lane11High)), bit32.bxor(Lane15High, bit32.band(-1 - Lane11High, Lane12High)), bit32.bxor(Lane11High, bit32.band(-1 - Lane12High, Lane13High)) :: number Lane16Low, Lane17Low, Lane18Low, Lane19Low, Lane20Low = bit32.bxor(Lane20Low, bit32.band(-1 - Lane16Low, Lane17Low)), bit32.bxor(Lane16Low, bit32.band(-1 - Lane17Low, Lane18Low)), bit32.bxor(Lane17Low, bit32.band(-1 - Lane18Low, Lane19Low)), bit32.bxor(Lane18Low, bit32.band(-1 - Lane19Low, Lane20Low)), bit32.bxor(Lane19Low, bit32.band(-1 - Lane20Low, Lane16Low)) :: number Lane16High, Lane17High, Lane18High, Lane19High, Lane20High = bit32.bxor(Lane20High, bit32.band(-1 - Lane16High, Lane17High)), bit32.bxor(Lane16High, bit32.band(-1 - Lane17High, Lane18High)), bit32.bxor(Lane17High, bit32.band(-1 - Lane18High, Lane19High)), bit32.bxor(Lane18High, bit32.band(-1 - Lane19High, Lane20High)), bit32.bxor(Lane19High, bit32.band(-1 - Lane20High, Lane16High)) :: number Lane21Low, Lane22Low, Lane23Low, Lane24Low, Lane25Low = bit32.bxor(Lane23Low, bit32.band(-1 - Lane24Low, Lane25Low)), bit32.bxor(Lane24Low, bit32.band(-1 - Lane25Low, Lane21Low)), bit32.bxor(Lane25Low, bit32.band(-1 - Lane21Low, Lane22Low)), bit32.bxor(Lane21Low, bit32.band(-1 - Lane22Low, Lane23Low)), bit32.bxor(Lane22Low, bit32.band(-1 - Lane23Low, Lane24Low)) :: number Lane21High, Lane22High, Lane23High, Lane24High, Lane25High = bit32.bxor(Lane23High, bit32.band(-1 - Lane24High, Lane25High)), bit32.bxor(Lane24High, bit32.band(-1 - Lane25High, Lane21High)), bit32.bxor(Lane25High, bit32.band(-1 - Lane21High, Lane22High)), bit32.bxor(Lane21High, bit32.band(-1 - Lane22High, Lane23High)), bit32.bxor(Lane22High, bit32.band(-1 - Lane23High, Lane24High)) :: number Lane01Low = bit32.bxor(Lane01Low, buffer.readu32(RCLow, RoundIndex)) Lane01High = bit32.bxor(Lane01High, buffer.readu32(RCHigh, RoundIndex)) end buffer.writeu32(LanesLow, 0, Lane01Low); buffer.writeu32(LanesHigh, 0, Lane01High) buffer.writeu32(LanesLow, 4, Lane02Low); buffer.writeu32(LanesHigh, 4, Lane02High) buffer.writeu32(LanesLow, 8, Lane03Low); buffer.writeu32(LanesHigh, 8, Lane03High) buffer.writeu32(LanesLow, 12, Lane04Low); buffer.writeu32(LanesHigh, 12, Lane04High) buffer.writeu32(LanesLow, 16, Lane05Low); buffer.writeu32(LanesHigh, 16, Lane05High) buffer.writeu32(LanesLow, 20, Lane06Low); buffer.writeu32(LanesHigh, 20, Lane06High) buffer.writeu32(LanesLow, 24, Lane07Low); buffer.writeu32(LanesHigh, 24, Lane07High) buffer.writeu32(LanesLow, 28, Lane08Low); buffer.writeu32(LanesHigh, 28, Lane08High) buffer.writeu32(LanesLow, 32, Lane09Low); buffer.writeu32(LanesHigh, 32, Lane09High) buffer.writeu32(LanesLow, 36, Lane10Low); buffer.writeu32(LanesHigh, 36, Lane10High) buffer.writeu32(LanesLow, 40, Lane11Low); buffer.writeu32(LanesHigh, 40, Lane11High) buffer.writeu32(LanesLow, 44, Lane12Low); buffer.writeu32(LanesHigh, 44, Lane12High) buffer.writeu32(LanesLow, 48, Lane13Low); buffer.writeu32(LanesHigh, 48, Lane13High) buffer.writeu32(LanesLow, 52, Lane14Low); buffer.writeu32(LanesHigh, 52, Lane14High) buffer.writeu32(LanesLow, 56, Lane15Low); buffer.writeu32(LanesHigh, 56, Lane15High) buffer.writeu32(LanesLow, 60, Lane16Low); buffer.writeu32(LanesHigh, 60, Lane16High) buffer.writeu32(LanesLow, 64, Lane17Low); buffer.writeu32(LanesHigh, 64, Lane17High) buffer.writeu32(LanesLow, 68, Lane18Low); buffer.writeu32(LanesHigh, 68, Lane18High) buffer.writeu32(LanesLow, 72, Lane19Low); buffer.writeu32(LanesHigh, 72, Lane19High) buffer.writeu32(LanesLow, 76, Lane20Low); buffer.writeu32(LanesHigh, 76, Lane20High) buffer.writeu32(LanesLow, 80, Lane21Low); buffer.writeu32(LanesHigh, 80, Lane21High) buffer.writeu32(LanesLow, 84, Lane22Low); buffer.writeu32(LanesHigh, 84, Lane22High) buffer.writeu32(LanesLow, 88, Lane23Low); buffer.writeu32(LanesHigh, 88, Lane23High) buffer.writeu32(LanesLow, 92, Lane24Low); buffer.writeu32(LanesHigh, 92, Lane24High) buffer.writeu32(LanesLow, 96, Lane25Low); buffer.writeu32(LanesHigh, 96, Lane25High) end end local XOF = {} function XOF.Reset128() buffer.fill(LanesLow128, 0, 0, 100) buffer.fill(LanesHigh128, 0, 0, 100) SqueezeOffset128 = 0 end function XOF.Reset256() buffer.fill(LanesLow256, 0, 0, 100) buffer.fill(LanesHigh256, 0, 0, 100) SqueezeOffset256 = 0 end function XOF.Absorb128(Message: buffer) local MessageLength = buffer.len(Message) local RateBytes = RATE_128 local PaddedMessage = PaddedBuffer128 buffer.fill(PaddedMessage, 0, 0, RateBytes) if MessageLength > 0 then buffer.copy(PaddedMessage, 0, Message, 0, MessageLength) end if RateBytes - MessageLength == 1 then buffer.writeu8(PaddedMessage, MessageLength, 0x9F) else buffer.writeu8(PaddedMessage, MessageLength, 0x1F) buffer.writeu8(PaddedMessage, RateBytes - 1, 0x80) end Keccak(LanesLow128, LanesHigh128, PaddedMessage, 0, RateBytes, RateBytes) end function XOF.Absorb256(Message: buffer) local MessageLength = buffer.len(Message) local RateBytes = RATE_256 local PaddedMessage = PaddedBuffer256 buffer.fill(PaddedMessage, 0, 0, RateBytes) if MessageLength > 0 then buffer.copy(PaddedMessage, 0, Message, 0, MessageLength) end if RateBytes - MessageLength == 1 then buffer.writeu8(PaddedMessage, MessageLength, 0x9F) else buffer.writeu8(PaddedMessage, MessageLength, 0x1F) buffer.writeu8(PaddedMessage, RateBytes - 1, 0x80) end Keccak(LanesLow256, LanesHigh256, PaddedMessage, 0, RateBytes, RateBytes) end function XOF.Squeeze128Into(Output: buffer, OutputBytes: number, OutputOffset: number?) local OutOffset = OutputOffset or 0 local RateBytes = RATE_128 local LanesLow = LanesLow128 local LanesHigh = LanesHigh128 local SqueezeOffset = SqueezeOffset128 local ZeroBuffer = ZeroBuffer128 local Written = 0 while Written < OutputBytes do if SqueezeOffset >= RateBytes then Keccak(LanesLow, LanesHigh, ZeroBuffer, 0, RateBytes, RateBytes) SqueezeOffset = 0 end local BytesThisRound = RateBytes - SqueezeOffset if BytesThisRound > OutputBytes - Written then BytesThisRound = OutputBytes - Written end local ByteIndex = 0 while ByteIndex < BytesThisRound do local AbsoluteIndex = SqueezeOffset + ByteIndex local Lane = bit32.rshift(AbsoluteIndex, 3) local ByteInLane = bit32.band(AbsoluteIndex, 7) local LaneOffset = bit32.lshift(Lane, 2) if ByteInLane == 0 and ByteIndex + 8 <= BytesThisRound then buffer.writeu32(Output, OutOffset + Written + ByteIndex, buffer.readu32(LanesLow, LaneOffset)) buffer.writeu32(Output, OutOffset + Written + ByteIndex + 4, buffer.readu32(LanesHigh, LaneOffset)) ByteIndex += 8 elseif ByteInLane == 0 and ByteIndex + 4 <= BytesThisRound then buffer.writeu32(Output, OutOffset + Written + ByteIndex, buffer.readu32(LanesLow, LaneOffset)) ByteIndex += 4 elseif ByteInLane == 4 and ByteIndex + 4 <= BytesThisRound then buffer.writeu32(Output, OutOffset + Written + ByteIndex, buffer.readu32(LanesHigh, LaneOffset)) ByteIndex += 4 else local Value if ByteInLane < 4 then Value = bit32.extract(buffer.readu32(LanesLow, LaneOffset), bit32.lshift(ByteInLane, 3), 8) else Value = bit32.extract(buffer.readu32(LanesHigh, LaneOffset), bit32.lshift(ByteInLane - 4, 3), 8) end buffer.writeu8(Output, OutOffset + Written + ByteIndex, Value) ByteIndex += 1 end end Written += BytesThisRound SqueezeOffset += BytesThisRound end SqueezeOffset128 = SqueezeOffset end function XOF.Squeeze128(OutputBytes: number): buffer local Output = if OutputBytes == 168 then SqueezeBuffer128_168 else buffer.create(OutputBytes) XOF.Squeeze128Into(Output, OutputBytes, 0) return Output end function XOF.Squeeze256Into(Output: buffer, OutputBytes: number, OutputOffset: number?) local OutOffset = OutputOffset or 0 local RateBytes = RATE_256 local LanesLow = LanesLow256 local LanesHigh = LanesHigh256 local SqueezeOffset = SqueezeOffset256 local ZeroBuffer = ZeroBuffer256 local Written = 0 while Written < OutputBytes do if SqueezeOffset >= RateBytes then Keccak(LanesLow, LanesHigh, ZeroBuffer, 0, RateBytes, RateBytes) SqueezeOffset = 0 end local BytesThisRound = RateBytes - SqueezeOffset if BytesThisRound > OutputBytes - Written then BytesThisRound = OutputBytes - Written end local ByteIndex = 0 while ByteIndex < BytesThisRound do local AbsoluteIndex = SqueezeOffset + ByteIndex local Lane = bit32.rshift(AbsoluteIndex, 3) local ByteInLane = bit32.band(AbsoluteIndex, 7) local LaneOffset = bit32.lshift(Lane, 2) if ByteInLane == 0 and ByteIndex + 8 <= BytesThisRound then buffer.writeu32(Output, OutOffset + Written + ByteIndex, buffer.readu32(LanesLow, LaneOffset)) buffer.writeu32(Output, OutOffset + Written + ByteIndex + 4, buffer.readu32(LanesHigh, LaneOffset)) ByteIndex += 8 elseif ByteInLane == 0 and ByteIndex + 4 <= BytesThisRound then buffer.writeu32(Output, OutOffset + Written + ByteIndex, buffer.readu32(LanesLow, LaneOffset)) ByteIndex += 4 elseif ByteInLane == 4 and ByteIndex + 4 <= BytesThisRound then buffer.writeu32(Output, OutOffset + Written + ByteIndex, buffer.readu32(LanesHigh, LaneOffset)) ByteIndex += 4 else local Value if ByteInLane < 4 then Value = bit32.extract(buffer.readu32(LanesLow, LaneOffset), bit32.lshift(ByteInLane, 3), 8) else Value = bit32.extract(buffer.readu32(LanesHigh, LaneOffset), bit32.lshift(ByteInLane - 4, 3), 8) end buffer.writeu8(Output, OutOffset + Written + ByteIndex, Value) ByteIndex += 1 end end Written += BytesThisRound SqueezeOffset += BytesThisRound end SqueezeOffset256 = SqueezeOffset end function XOF.Squeeze256(OutputBytes: number): buffer local Output = if OutputBytes == 128 then SqueezeBuffer256_128 elseif OutputBytes == 192 then SqueezeBuffer256_192 else buffer.create(OutputBytes) XOF.Squeeze256Into(Output, OutputBytes, 0) return Output end return XOF
8,128
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlDSA/init.luau
--[=[ ML-DSA (FIPS 204) Digital Signature Algorithm Post quantum digital signature scheme based on lattice cryptography. Has three security levels: ML-DSA-44, ML-DSA-65, ML-DSA-87. Example usage: local MLDSA = require("@self/MlDSA") local PubKey, SecKey = MLDSA.ML_DSA_44.GenerateKeys() local Message = buffer.fromstring("Hello World") local Context = buffer.create(0) local Signature = buffer.create(MLDSA.ML_DSA_44.SigByteLen) local Random = buffer.create(32) local Success = MLDSA.ML_DSA_44.Sign(Message, Random, SecKey, Context, Signature) local Valid = MLDSA.ML_DSA_44.Verify(Message, PubKey, Context, Signature) --]=] --!strict --!optimize 2 --!native local SHA3 = require("@self/SHA3") local NTT = require("@self/NTT") local PolyVec = require("@self/PolyVec") local BitPacking = require("@self/Pack") local Sampling = require("@self/Sampling") local Params = require("@self/Params") local Utils = require("@self/Utils") local CSPRNG = require("@self/CSPRNG") local KEYGEN_SEED_BYTE_LEN = 32 local RND_BYTE_LEN = 32 local N = 256 local Q = 8380417 local Mldsa = { CSPRNG = CSPRNG } local function CompareBufferSlices(A: buffer, AOffset: number, B: buffer, BOffset: number, Length: number): boolean local Difference = 0 if Length == 32 then Difference = bit32.bor( bit32.bxor(buffer.readu32(A, AOffset), buffer.readu32(B, BOffset)), bit32.bxor(buffer.readu32(A, AOffset + 4), buffer.readu32(B, BOffset + 4)), bit32.bxor(buffer.readu32(A, AOffset + 8), buffer.readu32(B, BOffset + 8)), bit32.bxor(buffer.readu32(A, AOffset + 12), buffer.readu32(B, BOffset + 12)), bit32.bxor(buffer.readu32(A, AOffset + 16), buffer.readu32(B, BOffset + 16)), bit32.bxor(buffer.readu32(A, AOffset + 20), buffer.readu32(B, BOffset + 20)), bit32.bxor(buffer.readu32(A, AOffset + 24), buffer.readu32(B, BOffset + 24)), bit32.bxor(buffer.readu32(A, AOffset + 28), buffer.readu32(B, BOffset + 28)) ) return Difference == 0 end local AlignedLength = bit32.band(Length, bit32.bnot(3)) for I = 0, AlignedLength - 4, 4 do Difference = bit32.bor(Difference, bit32.bxor(buffer.readu32(A, AOffset + I), buffer.readu32(B, BOffset + I))) end for I = AlignedLength, Length - 1 do Difference = bit32.bor(Difference, bit32.bxor(buffer.readu8(A, AOffset + I), buffer.readu8(B, BOffset + I))) end return Difference == 0 end local function Keygen(Seed: buffer, PubKey: buffer, SecKey: buffer, K: number, L: number, D: number, Eta: number) if not Params.CheckKeygenParams(K, L, D, Eta) then error("Invalid keygen parameters") end local T1Bw = Utils.BitWidth(Q) - D local EtaBw = Utils.BitWidth(2 * Eta) local S1Len = L * EtaBw * 32 local S2Len = K * EtaBw * 32 local T0Rng = bit32.lshift(1, D - 1) local PkOff1 = 32 local SkOff0 = 0 local SkOff1 = SkOff0 + 32 local SkOff2 = SkOff1 + 32 local SkOff3 = SkOff2 + 64 local SkOff4 = SkOff3 + S1Len local SkOff5 = SkOff4 + S2Len local DomainSeparator = buffer.create(2) buffer.writeu8(DomainSeparator, 0, K) buffer.writeu8(DomainSeparator, 1, L) local SeedHashInput = buffer.create(34) buffer.copy(SeedHashInput, 0, Seed, 0, 32) buffer.copy(SeedHashInput, 32, DomainSeparator, 0, 2) local SeedHash = SHA3.SHAKE256(SeedHashInput, 128) local Rho = buffer.create(32) local RhoPrime = buffer.create(64) local Key = buffer.create(32) buffer.copy(Rho, 0, SeedHash, 0, 32) buffer.copy(RhoPrime, 0, SeedHash, 32, 64) buffer.copy(Key, 0, SeedHash, 96, 32) local A = buffer.create(K * L * N * 4) Sampling.ExpandA(Rho, A, K, L) local S1 = buffer.create(L * N * 4) local S2 = buffer.create(K * N * 4) Sampling.ExpandS(RhoPrime, S1, Eta, L, 0) Sampling.ExpandS(RhoPrime, S2, Eta, K, L) local S1Prime = buffer.create(L * N * 4) PolyVec.Copy(S1, S1Prime, L) PolyVec.ForwardNTT(S1Prime, L) local T = buffer.create(K * N * 4) PolyVec.MatrixMultiply(A, S1Prime, T, K, L, L, 1) PolyVec.InverseNTT(T, K) PolyVec.AddTo(S2, T, K) local T1 = buffer.create(K * N * 4) local T0 = buffer.create(K * N * 4) PolyVec.Power2Round(T, T1, T0, K, D) buffer.copy(PubKey, 0, Rho, 0, 32) local T1Encoded = buffer.create(buffer.len(PubKey) - PkOff1) PolyVec.Encode(T1, T1Encoded, K, T1Bw) buffer.copy(PubKey, PkOff1, T1Encoded, 0, buffer.len(T1Encoded)) local Tr = SHA3.SHAKE256(PubKey, 64) buffer.copy(SecKey, SkOff0, Rho, 0, 32) buffer.copy(SecKey, SkOff1, Key, 0, 32) buffer.copy(SecKey, SkOff2, Tr, 0, 64) PolyVec.SubFromX(S1, L, Eta) PolyVec.SubFromX(S2, K, Eta) local S1Encoded = buffer.create(S1Len) local S2Encoded = buffer.create(S2Len) PolyVec.Encode(S1, S1Encoded, L, EtaBw) PolyVec.Encode(S2, S2Encoded, K, EtaBw) buffer.copy(SecKey, SkOff3, S1Encoded, 0, S1Len) buffer.copy(SecKey, SkOff4, S2Encoded, 0, S2Len) PolyVec.SubFromX(T0, K, T0Rng) local T0Encoded = buffer.create(buffer.len(SecKey) - SkOff5) PolyVec.Encode(T0, T0Encoded, K, D) buffer.copy(SecKey, SkOff5, T0Encoded, 0, buffer.len(T0Encoded)) end local function SignMuCore(Mu: buffer, Rnd: buffer, SecKey: buffer, Sig: buffer, K: number, L: number, D: number, Eta: number, Gamma1: number, Gamma2: number, Tau: number, Beta: number, Omega: number, Lambda: number): boolean local T0Rng = bit32.lshift(1, D - 1) local EtaBw = Utils.BitWidth(2 * Eta) local S1Len = L * EtaBw * 32 local S2Len = K * EtaBw * 32 local Alpha = bit32.lshift(Gamma2, 1) local M = math.floor((Q - 1) / Alpha) local W1Bw = Utils.BitWidth(M - 1) local CTildaSize = math.floor((2 * Lambda) / 8) local Gamma1Bw = Utils.BitWidth(Gamma1) local SkOff0 = 0 local SkOff1 = SkOff0 + 32 local SkOff2 = SkOff1 + 32 local SkOff3 = SkOff2 + 64 local SkOff4 = SkOff3 + S1Len local SkOff5 = SkOff4 + S2Len local Rho = buffer.create(32) local Key = buffer.create(32) buffer.copy(Rho, 0, SecKey, SkOff0, 32) buffer.copy(Key, 0, SecKey, SkOff1, 32) local A = buffer.create(K * L * N * 4) Sampling.ExpandA(Rho, A, K, L) local RhoPrimeInput = buffer.create(32 + 32 + 64) buffer.copy(RhoPrimeInput, 0, Key, 0, 32) buffer.copy(RhoPrimeInput, 32, Rnd, 0, 32) buffer.copy(RhoPrimeInput, 64, Mu, 0, 64) local RhoPrime = SHA3.SHAKE256(RhoPrimeInput, 64) local S1 = buffer.create(L * N * 4) local S2 = buffer.create(K * N * 4) local T0 = buffer.create(K * N * 4) local S1Encoded = buffer.create(S1Len) local S2Encoded = buffer.create(S2Len) local T0Encoded = buffer.create(buffer.len(SecKey) - SkOff5) buffer.copy(S1Encoded, 0, SecKey, SkOff3, S1Len) buffer.copy(S2Encoded, 0, SecKey, SkOff4, S2Len) buffer.copy(T0Encoded, 0, SecKey, SkOff5, buffer.len(T0Encoded)) PolyVec.Decode(S1Encoded, S1, L, EtaBw) PolyVec.Decode(S2Encoded, S2, K, EtaBw) PolyVec.Decode(T0Encoded, T0, K, D) PolyVec.SubFromX(S1, L, Eta) PolyVec.SubFromX(S2, K, Eta) PolyVec.SubFromX(T0, K, T0Rng) PolyVec.ForwardNTT(S1, L) PolyVec.ForwardNTT(S2, K) PolyVec.ForwardNTT(T0, K) local HasSigned = false local Kappa = 0 local Y = buffer.create(L * N * 4) local YPrime = buffer.create(L * N * 4) local W = buffer.create(K * N * 4) local W1 = buffer.create(K * N * 4) local C = buffer.create(N * 4) local Z = buffer.create(L * N * 4) local R0 = buffer.create(K * N * 4) local R1 = buffer.create(K * N * 4) local H0 = buffer.create(K * N * 4) local H1 = buffer.create(K * N * 4) local H = buffer.create(K * N * 4) local CTilda = buffer.create(CTildaSize) local W1Encoded = buffer.create(K * W1Bw * 32) while not HasSigned do Sampling.ExpandMask(RhoPrime, Kappa, Y, Gamma1, L) PolyVec.Copy(Y, YPrime, L) PolyVec.ForwardNTT(YPrime, L) PolyVec.MatrixMultiply(A, YPrime, W, K, L, L, 1) PolyVec.InverseNTT(W, K) PolyVec.HighBits(W, W1, K, Alpha) PolyVec.Encode(W1, W1Encoded, K, W1Bw) local ChallengeInput = buffer.create(64 + buffer.len(W1Encoded)) buffer.copy(ChallengeInput, 0, Mu, 0, 64) buffer.copy(ChallengeInput, 64, W1Encoded, 0, buffer.len(W1Encoded)) local CTildaFull = SHA3.SHAKE256(ChallengeInput, CTildaSize) buffer.copy(CTilda, 0, CTildaFull, 0, CTildaSize) Sampling.SampleInBall(CTilda, C, Tau, Lambda) NTT.ForwardNTT(C) PolyVec.MultiplyByPoly(C, S1, Z, L) PolyVec.InverseNTT(Z, L) PolyVec.AddTo(Y, Z, L) PolyVec.MultiplyByPoly(C, S2, R1, K) PolyVec.InverseNTT(R1, K) PolyVec.Negate(R1, K) PolyVec.AddTo(W, R1, K) PolyVec.LowBits(R1, R0, K, Alpha) local ZNorm = PolyVec.InfinityNorm(Z, L) local R0Norm = PolyVec.InfinityNorm(R0, K) if ZNorm >= (Gamma1 - Beta) or R0Norm >= (Gamma2 - Beta) then HasSigned = false else PolyVec.MultiplyByPoly(C, T0, H0, K) PolyVec.InverseNTT(H0, K) PolyVec.Copy(H0, H1, K) PolyVec.Negate(H0, K) PolyVec.AddTo(H1, R1, K) PolyVec.MakeHint(H0, R1, H, K, Alpha) local CT0Norm = PolyVec.InfinityNorm(H1, K) local Count1s = PolyVec.Count1s(H, K) if CT0Norm >= Gamma2 or Count1s > Omega then HasSigned = false else HasSigned = true end end Kappa += L end local SigOff0 = 0 local SigOff1 = SigOff0 + CTildaSize local SigOff2 = SigOff1 + (32 * L * Gamma1Bw) buffer.copy(Sig, SigOff0, CTilda, 0, CTildaSize) PolyVec.SubFromX(Z, L, Gamma1) local ZEncoded = buffer.create(32 * L * Gamma1Bw) PolyVec.Encode(Z, ZEncoded, L, Gamma1Bw) buffer.copy(Sig, SigOff1, ZEncoded, 0, buffer.len(ZEncoded)) local HEncoded = buffer.create(buffer.len(Sig) - SigOff2) BitPacking.EncodeHintBits(H, HEncoded, K, Omega) buffer.copy(Sig, SigOff2, HEncoded, 0, buffer.len(HEncoded)) return HasSigned end local function Sign(Msg: buffer, Rnd: buffer, SecKey: buffer, Ctx: buffer, Sig: buffer, K: number, L: number, D: number, Eta: number, Gamma1: number, Gamma2: number, Tau: number, Beta: number, Omega: number, Lambda: number): boolean if not Params.CheckSigningParams(K, L, D, Eta, Gamma1, Gamma2, Tau, Beta, Omega, Lambda) then error("Invalid signing parameters") end if buffer.len(Ctx) > 255 then return false end local SkOff2 = 64 local Tr = buffer.create(64) buffer.copy(Tr, 0, SecKey, SkOff2, 64) local DomainSeparator = buffer.create(2) buffer.writeu8(DomainSeparator, 0, 0) buffer.writeu8(DomainSeparator, 1, buffer.len(Ctx)) local MuInput = buffer.create(64 + 2 + buffer.len(Ctx) + buffer.len(Msg)) local Offset = 0 buffer.copy(MuInput, Offset, Tr, 0, 64) Offset += 64 buffer.copy(MuInput, Offset, DomainSeparator, 0, 2) Offset += 2 buffer.copy(MuInput, Offset, Ctx, 0, buffer.len(Ctx)) Offset += buffer.len(Ctx) buffer.copy(MuInput, Offset, Msg, 0, buffer.len(Msg)) local Mu = SHA3.SHAKE256(MuInput, 64) return SignMuCore(Mu, Rnd, SecKey, Sig, K, L, D, Eta, Gamma1, Gamma2, Tau, Beta, Omega, Lambda) end local function SignInternal(MPrime: buffer, Rnd: buffer, SecKey: buffer, Sig: buffer, K: number, L: number, D: number, Eta: number, Gamma1: number, Gamma2: number, Tau: number, Beta: number, Omega: number, Lambda: number): boolean if not Params.CheckSigningParams(K, L, D, Eta, Gamma1, Gamma2, Tau, Beta, Omega, Lambda) then error("Invalid signing parameters") end local SkOff2 = 64 local Tr = buffer.create(64) buffer.copy(Tr, 0, SecKey, SkOff2, 64) local MuInput = buffer.create(64 + buffer.len(MPrime)) buffer.copy(MuInput, 0, Tr, 0, 64) buffer.copy(MuInput, 64, MPrime, 0, buffer.len(MPrime)) local Mu = SHA3.SHAKE256(MuInput, 64) return SignMuCore(Mu, Rnd, SecKey, Sig, K, L, D, Eta, Gamma1, Gamma2, Tau, Beta, Omega, Lambda) end local function SignMu(Mu: buffer, Rnd: buffer, SecKey: buffer, Sig: buffer, K: number, L: number, D: number, Eta: number, Gamma1: number, Gamma2: number, Tau: number, Beta: number, Omega: number, Lambda: number): boolean if not Params.CheckSigningParams(K, L, D, Eta, Gamma1, Gamma2, Tau, Beta, Omega, Lambda) then error("Invalid signing parameters") end if buffer.len(Mu) ~= 64 then error("Mu must be 64 bytes") end return SignMuCore(Mu, Rnd, SecKey, Sig, K, L, D, Eta, Gamma1, Gamma2, Tau, Beta, Omega, Lambda) end local function Verify(Msg: buffer, PubKey: buffer, Ctx: buffer, Sig: buffer, K: number, L: number, D: number, Gamma1: number, Gamma2: number, Tau: number, Beta: number, Omega: number, Lambda: number): boolean if not Params.CheckVerifyParams(K, L, D, Gamma1, Gamma2, Tau, Beta, Omega, Lambda) then error("Invalid verify parameters") end if buffer.len(Ctx) > 255 then return false end local T1Bw = Utils.BitWidth(Q) - D local Gamma1Bw = Utils.BitWidth(Gamma1) local CTildaSize = math.floor((2 * Lambda) / 8) local ExpectedPkLen = Utils.PubKeyLen(K, D) if buffer.len(PubKey) ~= ExpectedPkLen then return false end local ExpectedSigLen = Utils.SigLen(K, L, Gamma1, Omega, Lambda) if buffer.len(Sig) ~= ExpectedSigLen then return false end local Alpha = bit32.lshift(Gamma2, 1) local M = math.floor((Q - 1) / Alpha) local W1Bw = Utils.BitWidth(M - 1) local PkOff1 = 32 local SigOff0 = 0 local SigOff1 = SigOff0 + CTildaSize local SigOff2 = SigOff1 + (32 * L * Gamma1Bw) local VerificationFailed = false local Rho = buffer.create(32) buffer.copy(Rho, 0, PubKey, 0, 32) local T1Encoded = buffer.create(buffer.len(PubKey) - PkOff1) buffer.copy(T1Encoded, 0, PubKey, PkOff1, buffer.len(T1Encoded)) local T1 = buffer.create(K * N * 4) PolyVec.Decode(T1Encoded, T1, K, T1Bw) local CTilda = buffer.create(CTildaSize) buffer.copy(CTilda, 0, Sig, SigOff0, CTildaSize) local ZEncoded = buffer.create(32 * L * Gamma1Bw) buffer.copy(ZEncoded, 0, Sig, SigOff1, buffer.len(ZEncoded)) local Z = buffer.create(L * N * 4) PolyVec.Decode(ZEncoded, Z, L, Gamma1Bw) PolyVec.SubFromX(Z, L, Gamma1) local ZNorm = PolyVec.InfinityNorm(Z, L) VerificationFailed = VerificationFailed or (ZNorm >= (Gamma1 - Beta)) local HEncoded = buffer.create(buffer.len(Sig) - SigOff2) buffer.copy(HEncoded, 0, Sig, SigOff2, buffer.len(HEncoded)) local H = buffer.create(K * N * 4) local HintDecodeFailed = BitPacking.DecodeHintBits(HEncoded, H, K, Omega) VerificationFailed = VerificationFailed or HintDecodeFailed local A = buffer.create(K * L * N * 4) Sampling.ExpandA(Rho, A, K, L) local Tr = SHA3.SHAKE256(PubKey, 64) local DomainSeparator = buffer.create(2) buffer.writeu8(DomainSeparator, 0, 0) buffer.writeu8(DomainSeparator, 1, buffer.len(Ctx)) local MuInput = buffer.create(64 + 2 + buffer.len(Ctx) + buffer.len(Msg)) local Offset = 0 buffer.copy(MuInput, Offset, Tr, 0, 64) Offset += 64 buffer.copy(MuInput, Offset, DomainSeparator, 0, 2) Offset += 2 buffer.copy(MuInput, Offset, Ctx, 0, buffer.len(Ctx)) Offset += buffer.len(Ctx) buffer.copy(MuInput, Offset, Msg, 0, buffer.len(Msg)) local Mu = SHA3.SHAKE256(MuInput, 64) local C = buffer.create(N * 4) Sampling.SampleInBall(CTilda, C, Tau, Lambda) NTT.ForwardNTT(C) local W0 = buffer.create(K * N * 4) local W1 = buffer.create(K * N * 4) local W2 = buffer.create(K * N * 4) PolyVec.ForwardNTT(Z, L) PolyVec.MatrixMultiply(A, Z, W0, K, L, L, 1) PolyVec.LeftShift(T1, K, D) PolyVec.ForwardNTT(T1, K) PolyVec.MultiplyByPoly(C, T1, W2, K) PolyVec.Negate(W2, K) PolyVec.AddTo(W0, W2, K) PolyVec.InverseNTT(W2, K) PolyVec.UseHint(H, W2, W1, K, Alpha) local W1Encoded = buffer.create(K * W1Bw * 32) PolyVec.Encode(W1, W1Encoded, K, W1Bw) local ChallengeInput = buffer.create(64 + buffer.len(W1Encoded)) buffer.copy(ChallengeInput, 0, Mu, 0, 64) buffer.copy(ChallengeInput, 64, W1Encoded, 0, buffer.len(W1Encoded)) local CTildaPrime = SHA3.SHAKE256(ChallengeInput, CTildaSize) local CompareResult = CompareBufferSlices(CTilda, 0, CTildaPrime, 0, CTildaSize) VerificationFailed = VerificationFailed or (not CompareResult) return not VerificationFailed end Mldsa.ML_DSA_44 = { D = 13, Tau = 39, Gamma1 = bit32.lshift(1, 17), Gamma2 = math.floor((Q - 1) / 88), K = 4, L = 4, Eta = 2, Beta = 39 * 2, Omega = 80, Lambda = 128, KeygenSeedByteLen = KEYGEN_SEED_BYTE_LEN, PubKeyByteLen = Utils.PubKeyLen(4, 13), SecKeyByteLen = Utils.SecKeyLen(4, 4, 2, 13), SigningSeedByteLen = RND_BYTE_LEN, SigByteLen = Utils.SigLen(4, 4, 131072, 80, 128), KeyGen = function(Seed: buffer, PubKey: buffer, SecKey: buffer) Keygen(Seed, PubKey, SecKey, 4, 4, 13, 2) end, Sign = function(Msg: buffer, Rnd: buffer, SecKey: buffer, Ctx: buffer, Sig: buffer): boolean return Sign(Msg, Rnd, SecKey, Ctx, Sig, 4, 4, 13, 2, 131072, 95232, 39, 78, 80, 128) end, SignInternal = function(MPrime: buffer, Rnd: buffer, SecKey: buffer, Sig: buffer): boolean return SignInternal(MPrime, Rnd, SecKey, Sig, 4, 4, 13, 2, 131072, 95232, 39, 78, 80, 128) end, SignMu = function(Mu: buffer, Rnd: buffer, SecKey: buffer, Sig: buffer): boolean return SignMu(Mu, Rnd, SecKey, Sig, 4, 4, 13, 2, 131072, 95232, 39, 78, 80, 128) end, Verify = function(Msg: buffer, PubKey: buffer, Ctx: buffer, Sig: buffer): boolean return Verify(Msg, PubKey, Ctx, Sig, 4, 4, 13, 131072, 95232, 39, 78, 80, 128) end, GenerateKeys = function(): (buffer, buffer) local Seed = CSPRNG.RandomBytes(32) local PubKey = buffer.create(1312) local SecKey = buffer.create(2560) Mldsa.ML_DSA_44.KeyGen(Seed, PubKey, SecKey) return PubKey, SecKey end } Mldsa.ML_DSA_65 = { D = 13, Tau = 49, Gamma1 = bit32.lshift(1, 19), Gamma2 = math.floor((Q - 1) / 32), K = 6, L = 5, Eta = 4, Beta = 49 * 4, Omega = 55, Lambda = 192, KeygenSeedByteLen = KEYGEN_SEED_BYTE_LEN, PubKeyByteLen = Utils.PubKeyLen(6, 13), SecKeyByteLen = Utils.SecKeyLen(6, 5, 4, 13), SigningSeedByteLen = RND_BYTE_LEN, SigByteLen = Utils.SigLen(6, 5, 524288, 55, 192), KeyGen = function(Seed: buffer, PubKey: buffer, SecKey: buffer) Keygen(Seed, PubKey, SecKey, 6, 5, 13, 4) end, Sign = function(Msg: buffer, Rnd: buffer, SecKey: buffer, Ctx: buffer, Sig: buffer): boolean return Sign(Msg, Rnd, SecKey, Ctx, Sig, 6, 5, 13, 4, 524288, 261888, 49, 196, 55, 192) end, SignInternal = function(MPrime: buffer, Rnd: buffer, SecKey: buffer, Sig: buffer): boolean return SignInternal(MPrime, Rnd, SecKey, Sig, 6, 5, 13, 4, 524288, 261888, 49, 196, 55, 192) end, SignMu = function(Mu: buffer, Rnd: buffer, SecKey: buffer, Sig: buffer): boolean return SignMu(Mu, Rnd, SecKey, Sig, 6, 5, 13, 4, 524288, 261888, 49, 196, 55, 192) end, Verify = function(Msg: buffer, PubKey: buffer, Ctx: buffer, Sig: buffer): boolean return Verify(Msg, PubKey, Ctx, Sig, 6, 5, 13, 524288, 261888, 49, 196, 55, 192) end, GenerateKeys = function(): (buffer, buffer) local Seed = CSPRNG.RandomBytes(32) local PubKey = buffer.create(1952) local SecKey = buffer.create(4032) Mldsa.ML_DSA_65.KeyGen(Seed, PubKey, SecKey) return PubKey, SecKey end } Mldsa.ML_DSA_87 = { D = 13, Tau = 60, Gamma1 = bit32.lshift(1, 19), Gamma2 = math.floor((Q - 1) / 32), K = 8, L = 7, Eta = 2, Beta = 60 * 2, Omega = 75, Lambda = 256, KeygenSeedByteLen = KEYGEN_SEED_BYTE_LEN, PubKeyByteLen = Utils.PubKeyLen(8, 13), SecKeyByteLen = Utils.SecKeyLen(8, 7, 2, 13), SigningSeedByteLen = RND_BYTE_LEN, SigByteLen = Utils.SigLen(8, 7, 524288, 75, 256), KeyGen = function(Seed: buffer, PubKey: buffer, SecKey: buffer) Keygen(Seed, PubKey, SecKey, 8, 7, 13, 2) end, Sign = function(Msg: buffer, Rnd: buffer, SecKey: buffer, Ctx: buffer, Sig: buffer): boolean return Sign(Msg, Rnd, SecKey, Ctx, Sig, 8, 7, 13, 2, 524288, 261888, 60, 120, 75, 256) end, SignInternal = function(MPrime: buffer, Rnd: buffer, SecKey: buffer, Sig: buffer): boolean return SignInternal(MPrime, Rnd, SecKey, Sig, 8, 7, 13, 2, 524288, 261888, 60, 120, 75, 256) end, SignMu = function(Mu: buffer, Rnd: buffer, SecKey: buffer, Sig: buffer): boolean return SignMu(Mu, Rnd, SecKey, Sig, 8, 7, 13, 2, 524288, 261888, 60, 120, 75, 256) end, Verify = function(Msg: buffer, PubKey: buffer, Ctx: buffer, Sig: buffer): boolean return Verify(Msg, PubKey, Ctx, Sig, 8, 7, 13, 524288, 261888, 60, 120, 75, 256) end, GenerateKeys = function(): (buffer, buffer) local Seed = CSPRNG.RandomBytes(32) local PubKey = buffer.create(2592) local SecKey = buffer.create(4896) Mldsa.ML_DSA_87.KeyGen(Seed, PubKey, SecKey) return PubKey, SecKey end } Mldsa.PubKeyLen = Utils.PubKeyLen Mldsa.SecKeyLen = Utils.SecKeyLen Mldsa.SigLen = Utils.SigLen return Mldsa
7,249
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/Compression.luau
--[=[ ML-KEM Compression Module Polynomial coefficient compression and decompression operations for ML-KEM. Maps field elements to and from reduced bit representations. --]=] --!strict --!optimize 2 --!native local Params = require("./Params") local N = 256 local Q = 3329 local Compression = {} function Compression.Compress(Value: number, D: number): number local Shifted = Value * (2^D) local QHalf = 1664 local Rounded = Shifted + QHalf local Quotient = Rounded // Q local Mask = (2^D) - 1 return bit32.band(Quotient, Mask) end function Compression.Decompress(Value: number, D: number): number local Product = Value * Q local Quotient = bit32.rshift(Product, D) local RoundBit = bit32.band(bit32.rshift(Product, D - 1), 1) return Quotient + RoundBit end function Compression.PolyCompress(Poly: buffer, D: number) if not Params.CheckD(D) then error("Invalid compression parameter d") end local Modulus = Q if D == 1 then for Index = 0, N - 1 do local Value = buffer.readu16(Poly, Index * 2) local Shifted = Value * 2 local Rounded = Shifted + 1664 local Quotient = Rounded // Modulus buffer.writeu16(Poly, Index * 2, bit32.band(Quotient, 1)) end elseif D == 4 then for Index = 0, N - 1 do local Value = buffer.readu16(Poly, Index * 2) local Shifted = Value * 16 local Rounded = Shifted + 1664 local Quotient = Rounded // Modulus buffer.writeu16(Poly, Index * 2, bit32.band(Quotient, 15)) end elseif D == 5 then for Index = 0, N - 1 do local Value = buffer.readu16(Poly, Index * 2) local Shifted = Value * 32 local Rounded = Shifted + 1664 local Quotient = Rounded // Modulus buffer.writeu16(Poly, Index * 2, bit32.band(Quotient, 31)) end elseif D == 10 then for Index = 0, N - 1 do local Value = buffer.readu16(Poly, Index * 2) local Shifted = Value * 1024 local Rounded = Shifted + 1664 local Quotient = Rounded // Modulus buffer.writeu16(Poly, Index * 2, bit32.band(Quotient, 1023)) end elseif D == 11 then for Index = 0, N - 1 do local Value = buffer.readu16(Poly, Index * 2) local Shifted = Value * 2048 local Rounded = Shifted + 1664 local Quotient = Rounded // Modulus buffer.writeu16(Poly, Index * 2, bit32.band(Quotient, 2047)) end else local Compress = Compression.Compress for Index = 0, N - 1 do local Value = buffer.readu16(Poly, Index * 2) local Compressed = Compress(Value, D) buffer.writeu16(Poly, Index * 2, Compressed) end end end function Compression.PolyDecompress(Poly: buffer, D: number) if not Params.CheckD(D) then error("Invalid decompression parameter d") end local Modulus = Q if D == 1 then for Index = 0, N - 1 do local Compressed = buffer.readu16(Poly, Index * 2) local Product = Compressed * Modulus local Quotient = bit32.rshift(Product, 1) local RoundBit = bit32.band(Product, 1) buffer.writeu16(Poly, Index * 2, Quotient + RoundBit) end elseif D == 4 then for Index = 0, N - 1 do local Compressed = buffer.readu16(Poly, Index * 2) local Product = Compressed * Modulus local Quotient = bit32.rshift(Product, 4) local RoundBit = bit32.band(bit32.rshift(Product, 3), 1) buffer.writeu16(Poly, Index * 2, Quotient + RoundBit) end elseif D == 5 then for Index = 0, N - 1 do local Compressed = buffer.readu16(Poly, Index * 2) local Product = Compressed * Modulus local Quotient = bit32.rshift(Product, 5) local RoundBit = bit32.band(bit32.rshift(Product, 4), 1) buffer.writeu16(Poly, Index * 2, Quotient + RoundBit) end elseif D == 10 then for Index = 0, N - 1 do local Compressed = buffer.readu16(Poly, Index * 2) local Product = Compressed * Modulus local Quotient = bit32.rshift(Product, 10) local RoundBit = bit32.band(bit32.rshift(Product, 9), 1) buffer.writeu16(Poly, Index * 2, Quotient + RoundBit) end elseif D == 11 then for Index = 0, N - 1 do local Compressed = buffer.readu16(Poly, Index * 2) local Product = Compressed * Modulus local Quotient = bit32.rshift(Product, 11) local RoundBit = bit32.band(bit32.rshift(Product, 10), 1) buffer.writeu16(Poly, Index * 2, Quotient + RoundBit) end else local Decompress = Compression.Decompress for Index = 0, N - 1 do local Compressed = buffer.readu16(Poly, Index * 2) local Decompressed = Decompress(Compressed, D) buffer.writeu16(Poly, Index * 2, Decompressed) end end end return Compression
1,449
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/Field.luau
--[=[ ML-KEM Field Arithmetic Module Prime field Zq arithmetic operations for ML-KEM. Modular arithmetic over the field Z_q where q = 3329. Example usage: local Field = require(script.Field) local Sum = Field.Add(1234, 567) local Product = Field.Multiply(1234, 567) local Inverse = Field.Invert(1234) local Buffer = Field.BufferCreate(256) Field.BufferReduce(Buffer, 256) local Sum = Field.BufferAdd(BufferA, BufferB, Result, 256) --]=] --!strict --!optimize 2 --!native local Q = 13 * 256 + 1 local Field = {} function Field.Add(A: number, B: number): number local Sum = A + B return if Sum >= Q then Sum - Q else Sum end function Field.Subtract(A: number, B: number): number local Diff = A - B return if Diff < 0 then Diff + Q else Diff end function Field.Multiply(A: number, B: number): number return (A * B) % Q end function Field.Negate(A: number): number return if A == 0 then 0 else Q - A end function Field.Power(Base: number, Exponent: number): number local Result = if bit32.band(Exponent, 1) == 1 then Base else 1 local CurrentBase = Base local Exp = Exponent while Exp > 1 do Exp = bit32.rshift(Exp, 1) CurrentBase = Field.Multiply(CurrentBase, CurrentBase) if bit32.band(Exp, 1) == 1 then Result = Field.Multiply(Result, CurrentBase) end end return Result end function Field.Invert(A: number): number if A == 0 then return 0 end return Field.Power(A, Q - 2) end function Field.BufferReduce(Buffer: buffer, Count: number) local Modulus = Q for Index = 0, Count - 1 do local Value = buffer.readu16(Buffer, Index * 2) buffer.writeu16(Buffer, Index * 2, (Value % Modulus)) end end return Field
511
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/NTT.luau
--[=[ ML-KEM Number Theoretic Transform Module Number Theoretic Transform (NTT) operations for polynomial multiplication. Cooley-Tukey NTT and Gentleman-Sande inverse NTT algorithms Example usage: local NTT = require(script.NTT) local Poly = buffer.create(512) -- 256 coefficients * 2 bytes NTT.Ntt(Poly) -- Forward transform NTT.Intt(Poly) -- Inverse transform --]=] --!strict --!optimize 2 --!native local Field = require("./Field") local Utils = require("./Utils") local LOG2N = 8 local N = 2^LOG2N local Q = 3329 local ZETA = 17 local INV_N = Field.Invert(N / 2) local Ntt = {} local NTT_ZETA_EXP = buffer.create((N / 2) * 2) do for I = 0, N / 2 - 1 do local BitRevIndex = Utils.BitReverse(I, LOG2N - 1) local ZetaExp = Field.Power(ZETA, BitRevIndex) buffer.writeu16(NTT_ZETA_EXP, I * 2, ZetaExp) end end local INTT_ZETA_EXP = buffer.create((N / 2) * 2) do for I = 0, N / 2 - 1 do local NttZeta = buffer.readu16(NTT_ZETA_EXP, I * 2) local NegZeta = if NttZeta == 0 then 0 else Q - NttZeta buffer.writeu16(INTT_ZETA_EXP, I * 2, NegZeta) end end local POLY_MUL_ZETA_EXP = buffer.create((N / 2) * 2) do for I = 0, N / 2 - 1 do local BitRevIndex = Utils.BitReverse(I, LOG2N - 1) local Exponent = bit32.bxor(bit32.lshift(BitRevIndex, 1), 1) local ZetaExp = Field.Power(ZETA, Exponent) buffer.writeu16(POLY_MUL_ZETA_EXP, I * 2, ZetaExp) end end local POWERS_OF_TWO = table.create(LOG2N) :: {{number}} for I = 0, LOG2N - 1 do POWERS_OF_TWO[I] = {2^I, (2^I) * 2} end function Ntt.Ntt(Poly: buffer) local Zeta = NTT_ZETA_EXP local Powers = POWERS_OF_TWO local Modulus = Q for L = LOG2N - 1, 1, -1 do local Len = Powers[L][1] local LenX2 = Powers[L][2] local KBeg = bit32.rshift(N, L + 1) for Start = 0, N - 1, LenX2 do local KNow = KBeg + bit32.rshift(Start, L + 1) local ZetaExp = buffer.readu16(Zeta, KNow * 2) for I = Start, Start + Len - 1 do local OffsetI = I * 2 local OffsetILen = (I + Len) * 2 local PolyI = buffer.readu16(Poly, OffsetI) local PolyILen = buffer.readu16(Poly, OffsetILen) local Tmp = (ZetaExp * PolyILen) % Modulus local SubResult = if PolyI >= Tmp then PolyI - Tmp else PolyI - Tmp + Modulus local Sum = PolyI + Tmp local AddResult = if Sum >= Modulus then Sum - Modulus else Sum buffer.writeu16(Poly, OffsetILen, SubResult) buffer.writeu16(Poly, OffsetI, AddResult) end end end end function Ntt.Intt(Poly: buffer) local Zeta = INTT_ZETA_EXP local InvN = INV_N local Powers = POWERS_OF_TWO local Modulus = Q for L = 1, LOG2N - 1 do local Len = Powers[L][1] local LenX2 = Powers[L][2] local KBeg = bit32.rshift(N, L) - 1 for Start = 0, N - 1, LenX2 do local KNow = KBeg - bit32.rshift(Start, L + 1) local NegZetaExp = buffer.readu16(Zeta, KNow * 2) for I = Start, Start + Len - 1 do local OffsetI = I * 2 local OffsetILen = (I + Len) * 2 local PolyI = buffer.readu16(Poly, OffsetI) local PolyILen = buffer.readu16(Poly, OffsetILen) local Sum = PolyI + PolyILen local AddResult = if Sum >= Modulus then Sum - Modulus else Sum local SubResult = if PolyI >= PolyILen then PolyI - PolyILen else PolyI - PolyILen + Modulus local MulResult = (SubResult * NegZetaExp) % Modulus buffer.writeu16(Poly, OffsetI, AddResult) buffer.writeu16(Poly, OffsetILen, MulResult) end end end for I = 0, N - 1 do local Offset = I * 2 local Coeff = buffer.readu16(Poly, Offset) local Scaled = (Coeff * InvN) % Q buffer.writeu16(Poly, Offset, Scaled) end end function Ntt.NttAt(Poly: buffer, BaseOffset: number) local Zeta = NTT_ZETA_EXP local Powers = POWERS_OF_TWO local Modulus = Q for L = LOG2N - 1, 1, -1 do local Len = Powers[L][1] local LenX2 = Powers[L][2] local KBeg = bit32.rshift(N, L + 1) for Start = 0, N - 1, LenX2 do local KNow = KBeg + bit32.rshift(Start, L + 1) local ZetaExp = buffer.readu16(Zeta, KNow * 2) for I = Start, Start + Len - 1 do local OffsetI = BaseOffset + I * 2 local OffsetILen = BaseOffset + (I + Len) * 2 local PolyI = buffer.readu16(Poly, OffsetI) local PolyILen = buffer.readu16(Poly, OffsetILen) local Tmp = (ZetaExp * PolyILen) % Modulus local SubResult = if PolyI >= Tmp then PolyI - Tmp else PolyI - Tmp + Modulus local Sum = PolyI + Tmp local AddResult = if Sum >= Modulus then Sum - Modulus else Sum buffer.writeu16(Poly, OffsetILen, SubResult) buffer.writeu16(Poly, OffsetI, AddResult) end end end end function Ntt.InttAt(Poly: buffer, BaseOffset: number) local Zeta = INTT_ZETA_EXP local InvN = INV_N local Powers = POWERS_OF_TWO local Modulus = Q for L = 1, LOG2N - 1 do local Len = Powers[L][1] local LenX2 = Powers[L][2] local KBeg = bit32.rshift(N, L) - 1 for Start = 0, N - 1, LenX2 do local KNow = KBeg - bit32.rshift(Start, L + 1) local NegZetaExp = buffer.readu16(Zeta, KNow * 2) for I = Start, Start + Len - 1 do local OffsetI = BaseOffset + I * 2 local OffsetILen = BaseOffset + (I + Len) * 2 local PolyI = buffer.readu16(Poly, OffsetI) local PolyILen = buffer.readu16(Poly, OffsetILen) local Sum = PolyI + PolyILen local AddResult = if Sum >= Modulus then Sum - Modulus else Sum local SubResult = if PolyI >= PolyILen then PolyI - PolyILen else PolyI - PolyILen + Modulus local MulResult = (SubResult * NegZetaExp) % Modulus buffer.writeu16(Poly, OffsetI, AddResult) buffer.writeu16(Poly, OffsetILen, MulResult) end end end for I = 0, N - 1 do local Offset = BaseOffset + I * 2 local Coeff = buffer.readu16(Poly, Offset) buffer.writeu16(Poly, Offset, (Coeff * InvN) % Modulus) end end function Ntt.PolyAddAt(F: buffer, FOffset: number, G: buffer, GOffset: number, H: buffer, HOffset: number) local Modulus = Q for Index = 0, 255 do local Offset = Index * 2 local AValue = buffer.readu16(F, FOffset + Offset) local BValue = buffer.readu16(G, GOffset + Offset) local Sum = AValue + BValue buffer.writeu16(H, HOffset + Offset, if Sum >= Modulus then Sum - Modulus else Sum) end end function Ntt.PolyMul(F: buffer, G: buffer, H: buffer) local PolyZeta = POLY_MUL_ZETA_EXP local Modulus = Q for I = 0, N / 2 - 1 do local Offset = I * 4 local ZetaExp = buffer.readu16(PolyZeta, I * 2) local F0 = buffer.readu16(F, Offset) local F1 = buffer.readu16(F, Offset + 2) local G0 = buffer.readu16(G, Offset) local G1 = buffer.readu16(G, Offset + 2) local Mul1 = (F0 * G0) % Modulus local Mul2 = (F1 * G1) % Modulus local Mul3 = (Mul2 * ZetaExp) % Modulus local Sum0 = Mul1 + Mul3 local H0 = if Sum0 >= Modulus then Sum0 - Modulus else Sum0 local Mul4 = (F0 * G1) % Modulus local Mul5 = (F1 * G0) % Modulus local Sum1 = Mul4 + Mul5 local H1 = if Sum1 >= Modulus then Sum1 - Modulus else Sum1 buffer.writeu16(H, Offset, H0) buffer.writeu16(H, Offset + 2, H1) end end function Ntt.PolyMulAt(F: buffer, FOffset: number, G: buffer, GOffset: number, H: buffer, HOffset: number) local PolyZeta = POLY_MUL_ZETA_EXP local Modulus = Q for I = 0, 127 do local LocalOffset = I * 4 local ZetaExp = buffer.readu16(PolyZeta, I * 2) local F0 = buffer.readu16(F, FOffset + LocalOffset) local F1 = buffer.readu16(F, FOffset + LocalOffset + 2) local G0 = buffer.readu16(G, GOffset + LocalOffset) local G1 = buffer.readu16(G, GOffset + LocalOffset + 2) local Mul1 = (F0 * G0) % Modulus local Mul2 = (F1 * G1) % Modulus local Mul3 = (Mul2 * ZetaExp) % Modulus local Sum0 = Mul1 + Mul3 local H0 = if Sum0 >= Modulus then Sum0 - Modulus else Sum0 local Mul4 = (F0 * G1) % Modulus local Mul5 = (F1 * G0) % Modulus local Sum1 = Mul4 + Mul5 local H1 = if Sum1 >= Modulus then Sum1 - Modulus else Sum1 buffer.writeu16(H, HOffset + LocalOffset, H0) buffer.writeu16(H, HOffset + LocalOffset + 2, H1) end end function Ntt.PolyAdd(F: buffer, G: buffer, H: buffer) local Modulus = Q for Index = 0, N - 1 do local Offset = Index * 2 local AValue = buffer.readu16(F, Offset) local BValue = buffer.readu16(G, Offset) local Sum = AValue + BValue local Result = if Sum >= Modulus then Sum - Modulus else Sum buffer.writeu16(H, Offset, Result) end end function Ntt.PolySub(F: buffer, G: buffer, H: buffer) local Modulus = Q for Index = 0, N - 1 do local Offset = Index * 2 local AValue = buffer.readu16(F, Offset) local BValue = buffer.readu16(G, Offset) local Diff = AValue - BValue local Result = if Diff < 0 then Diff + Modulus else Diff buffer.writeu16(H, Offset, Result) end end return Ntt
3,057
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/PKE.luau
--[=[ ML-KEM Public Key Encryption Module K-PKE (CPA-secure public key encryption) implementation for ML-KEM. Provides key generation, encryption, and decryption operations as specified in NIST FIPS 203. Example usage: local PKE = require(script.PKE) local Seed = buffer.fromstring("32_byte_seed_here...") local PublicKey, SecretKey = PKE.MLKEM_1024.KeyGen(Seed) local Message = buffer.create(32) local Randomness = buffer.create(32) local Ciphertext = PKE.MLKEM_1024.Encrypt(PublicKey, Message, Randomness) local Plaintext = PKE.MLKEM_1024.Decrypt(SecretKey, Ciphertext) --]=] --!strict --!optimize 2 --!native local Ntt = require("./NTT") local PolyVec = require("./PolyVec") local Sampling = require("./Sampling") local Serialize = require("./Serialize") local Compression = require("./Compression") local Params = require("./Params") local Utils = require("./Utils") local SHA3 = require("./SHA3") local LOG2N = 8 local N = 2^LOG2N local POLY_SIZE = N * 2 local TEMP_V = buffer.create(N * 2) local TEMP_V2 = buffer.create(N * 2) local TEMP_SINGLE_POLY = buffer.create(N * 2) local TEMP_R_POLY = buffer.create(N * 2) local TEMP_T = buffer.create(N * 2) local TEMP_T2 = buffer.create(N * 2) local TEMP_U_POLY = buffer.create(N * 2) local KEYGEN_G_INPUT = buffer.create(33) local KEYGEN_RHO = buffer.create(32) local KEYGEN_SIGMA = buffer.create(32) local Pke = {} function Pke.KeyGen(K: number, Eta1: number, Seed: buffer): (buffer, buffer) if not Params.CheckKeygenParams(K, Eta1) then error("Invalid keygen parameters") end if buffer.len(Seed) ~= 32 then error("Seed must be 32 bytes") end local GInput = KEYGEN_G_INPUT buffer.copy(GInput, 0, Seed, 0, 32) buffer.writeu8(GInput, 32, K) local GOutput = SHA3.SHA3_512(GInput) local Rho = KEYGEN_RHO local Sigma = KEYGEN_SIGMA buffer.copy(Rho, 0, GOutput, 0, 32) buffer.copy(Sigma, 0, GOutput, 32, 32) local APrime = Sampling.GenerateMatrix(K, Rho, false) local Nonce = 0 local S = Sampling.GenerateVector(K, Eta1, Sigma, Nonce) Nonce += K local E = Sampling.GenerateVector(K, Eta1, Sigma, Nonce) PolyVec.VecNtt(S, K) PolyVec.VecNtt(E, K) local TPrime = PolyVec.VecCreate(K) PolyVec.MatVecMultiply(APrime, S, TPrime, K, K, K) PolyVec.VecAddTo(E, TPrime, K) local PublicKeyLen = Utils.GetPkePublicKeyLen(K) local PublicKey = buffer.create(PublicKeyLen) local EncodedTPrime = PolyVec.VecEncode(TPrime, K, 12) local RhoOffset = K * 12 * 32 buffer.copy(PublicKey, 0, EncodedTPrime, 0, RhoOffset) buffer.copy(PublicKey, RhoOffset, Rho, 0, 32) return PublicKey, PolyVec.VecEncode(S, K, 12) end function Pke.Encrypt(K: number, Eta1: number, Eta2: number, Du: number, Dv: number, PublicKey: buffer, Message: buffer, Randomness: buffer): buffer if not Params.CheckEncryptParams(K, Eta1, Eta2, Du, Dv) then error("Invalid encryption parameters") end if buffer.len(PublicKey) ~= Utils.GetPkePublicKeyLen(K) then error("Invalid public key length") end if buffer.len(Message) ~= 32 then error("Message must be 32 bytes") end if buffer.len(Randomness) ~= 32 then error("Randomness must be 32 bytes") end local RhoOffset = K * 12 * 32 local EncodedTPrime = buffer.create(RhoOffset) local Rho = buffer.create(32) buffer.copy(EncodedTPrime, 0, PublicKey, 0, RhoOffset) buffer.copy(Rho, 0, PublicKey, RhoOffset, 32) local TPrime = PolyVec.VecDecode(EncodedTPrime, K, 12) local ReEncodedTPrime = PolyVec.VecEncode(TPrime, K, 12) local IsValid = Utils.CtMemcmp(EncodedTPrime, ReEncodedTPrime) if IsValid ~= 0xFFFFFFFF then error("Key encapsulation verification failed") end local APrime = Sampling.GenerateMatrix(K, Rho, true) local Nonce = 0 local R = Sampling.GenerateVector(K, Eta1, Randomness, Nonce) Nonce += K local E1 = Sampling.GenerateVector(K, Eta2, Randomness, Nonce) Nonce += K local E2 = Sampling.GenerateNoisePoly(Eta2, Randomness, Nonce) PolyVec.VecNtt(R, K) local U = PolyVec.VecCreate(K) PolyVec.MatVecMultiply(APrime, R, U, K, K, K) PolyVec.VecIntt(U, K) PolyVec.VecAddTo(E1, U, K) local V = TEMP_V local TempV = TEMP_V2 local SinglePoly = TEMP_SINGLE_POLY local RPoly = TEMP_R_POLY buffer.fill(V, 0, 0, N * 2) local PolySize = POLY_SIZE for I = 0, K - 1 do local TPolyOffset = I * PolySize local RPolyOffset = I * PolySize buffer.copy(SinglePoly, 0, TPrime, TPolyOffset, PolySize) buffer.copy(RPoly, 0, R, RPolyOffset, PolySize) Ntt.PolyMul(SinglePoly, RPoly, TempV) Ntt.PolyAdd(V, TempV, V) end Ntt.Intt(V) Ntt.PolyAdd(V, E2, V) local M = Serialize.Decode(Message, 1) Compression.PolyDecompress(M, 1) Ntt.PolyAdd(V, M, V) PolyVec.VecCompress(U, K, Du) local EncodedU = PolyVec.VecEncode(U, K, Du) Compression.PolyCompress(V, Dv) local EncodedV = Serialize.Encode(V, Dv) local CiphertextLen = Utils.GetPkeCipherTextLen(K, Du, Dv) local Ciphertext = buffer.create(CiphertextLen) local ULen = buffer.len(EncodedU) buffer.copy(Ciphertext, 0, EncodedU, 0, ULen) buffer.copy(Ciphertext, ULen, EncodedV, 0, buffer.len(EncodedV)) return Ciphertext end function Pke.Decrypt(K: number, Du: number, Dv: number, SecretKey: buffer, Ciphertext: buffer): buffer if not Params.CheckDecryptParams(K, Du, Dv) then error("Invalid decryption parameters") end if buffer.len(SecretKey) ~= Utils.GetPkeSecretKeyLen(K) then error("Invalid secret key length") end if buffer.len(Ciphertext) ~= Utils.GetPkeCipherTextLen(K, Du, Dv) then error("Invalid ciphertext length") end local ULen = K * Du * 32 local VLen = Dv * 32 local EncodedU = buffer.create(ULen) local EncodedV = buffer.create(VLen) buffer.copy(EncodedU, 0, Ciphertext, 0, ULen) buffer.copy(EncodedV, 0, Ciphertext, ULen, VLen) local U = PolyVec.VecDecode(EncodedU, K, Du) PolyVec.VecDecompress(U, K, Du) local V = Serialize.Decode(EncodedV, Dv) Compression.PolyDecompress(V, Dv) local SPrime = PolyVec.VecDecode(SecretKey, K, 12) PolyVec.VecNtt(U, K) local T = TEMP_T local TempT = TEMP_T2 local SinglePoly = TEMP_SINGLE_POLY local UPoly = TEMP_U_POLY buffer.fill(T, 0, 0, N * 2) local PolySize = POLY_SIZE for I = 0, K - 1 do local SPolyOffset = I * PolySize local UPolyOffset = I * PolySize buffer.copy(SinglePoly, 0, SPrime, SPolyOffset, PolySize) buffer.copy(UPoly, 0, U, UPolyOffset, PolySize) Ntt.PolyMul(SinglePoly, UPoly, TempT) Ntt.PolyAdd(T, TempT, T) end Ntt.Intt(T) Ntt.PolySub(V, T, V) Compression.PolyCompress(V, 1) local Plaintext = Serialize.Encode(V, 1) return Plaintext end Pke.MLKEM_512 = { KeyGen = function(Seed: buffer): (buffer, buffer) return Pke.KeyGen(2, 3, Seed) end, Encrypt = function(PublicKey: buffer, Message: buffer, Randomness: buffer): buffer return Pke.Encrypt(2, 3, 2, 10, 4, PublicKey, Message, Randomness) end, Decrypt = function(SecretKey: buffer, Ciphertext: buffer): buffer return Pke.Decrypt(2, 10, 4, SecretKey, Ciphertext) end } Pke.MLKEM_768 = { KeyGen = function(Seed: buffer): (buffer, buffer) return Pke.KeyGen(3, 2, Seed) end, Encrypt = function(PublicKey: buffer, Message: buffer, Randomness: buffer): buffer return Pke.Encrypt(3, 2, 2, 10, 4, PublicKey, Message, Randomness) end, Decrypt = function(SecretKey: buffer, Ciphertext: buffer): buffer return Pke.Decrypt(3, 10, 4, SecretKey, Ciphertext) end } Pke.MLKEM_1024 = { KeyGen = function(Seed: buffer): (buffer, buffer) return Pke.KeyGen(4, 2, Seed) end, Encrypt = function(PublicKey: buffer, Message: buffer, Randomness: buffer): buffer return Pke.Encrypt(4, 2, 2, 11, 5, PublicKey, Message, Randomness) end, Decrypt = function(SecretKey: buffer, Ciphertext: buffer): buffer return Pke.Decrypt(4, 11, 5, SecretKey, Ciphertext) end } return Pke
2,481
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/Params.luau
--[=[ ML-KEM Parameters Module Parameter validation functions for ML-KEM. NIST FIPS 203 specification. Example usage: local Params = require(script.Params) local IsValid = Params.CheckKeygenParams(4, 2) -- true local ValidD = Params.CheckD(11) -- true local ValidEncrypt = Params.CheckEncryptParams(4, 2, 2, 11, 5) -- true --]=] --!strict --!optimize 2 --!native local Params = {} function Params.CheckD(D: number): boolean return D < 12 end function Params.CheckEta(Eta: number): boolean return (Eta == 2) or (Eta == 3) end function Params.CheckK(K: number): boolean return (K == 2) or (K == 3) or (K == 4) end function Params.CheckL(L: number): boolean return (L == 1) or (L == 4) or (L == 5) or (L == 10) or (L == 11) or (L == 12) end function Params.CheckKeygenParams(K: number, Eta1: number): boolean local Flag0 = (K == 2) and (Eta1 == 3) local Flag1 = (K == 3) and (Eta1 == 2) local Flag2 = (K == 4) and (Eta1 == 2) return Flag0 or Flag1 or Flag2 end function Params.CheckEncryptParams(K: number, Eta1: number, Eta2: number, Du: number, Dv: number): boolean local Flag0 = (K == 2) and (Eta1 == 3) and (Eta2 == 2) and (Du == 10) and (Dv == 4) local Flag1 = (K == 3) and (Eta1 == 2) and (Eta2 == 2) and (Du == 10) and (Dv == 4) local Flag2 = (K == 4) and (Eta1 == 2) and (Eta2 == 2) and (Du == 11) and (Dv == 5) return Flag0 or Flag1 or Flag2 end function Params.CheckDecryptParams(K: number, Du: number, Dv: number): boolean local Flag0 = (K == 2) and (Du == 10) and (Dv == 4) local Flag1 = (K == 3) and (Du == 10) and (Dv == 4) local Flag2 = (K == 4) and (Du == 11) and (Dv == 5) return Flag0 or Flag1 or Flag2 end function Params.CheckEncapParams(K: number, Eta1: number, Eta2: number, Du: number, Dv: number): boolean return Params.CheckEncryptParams(K, Eta1, Eta2, Du, Dv) end function Params.CheckDecapParams(K: number, Eta1: number, Eta2: number, Du: number, Dv: number): boolean return Params.CheckEncapParams(K, Eta1, Eta2, Du, Dv) end return Params
722
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/PolyVec.luau
--[=[ ML-KEM Polynomial Vector Module Polynomial vector and matrix operations for ML-KEM. Vector arithmetic, matrix multiplication, and encoding/decoding operations on vectors of degree-255 polynomials. --]=] --!strict --!optimize 2 --!native local Ntt = require("./NTT") local MlKemParams = require("./Params") local MlKemSerialize = require("./Serialize") local Compression = require("./Compression") local LOG2N = 8 local N = 2^LOG2N local Q = 3329 local POLY_SIZE = N * 2 local TEMP_POLY_MUL = buffer.create(N * 2) local TEMP_POLY_ACCUM = buffer.create(N * 2) local TEMP_POLY_ENCODE = buffer.create(N * 2) local TEMP_POLY_COMPRESS = buffer.create(N * 2) local PolyVec = {} function PolyVec.VecCreate(K: number): buffer return buffer.create(K * POLY_SIZE) end function PolyVec.MatCreate(Rows: number, Cols: number): buffer return buffer.create(Rows * Cols * POLY_SIZE) end function PolyVec.MatSetPoly(Mat: buffer, Row: number, Col: number, Cols: number, Poly: buffer) local Index = Row * Cols + Col local Offset = Index * POLY_SIZE buffer.copy(Mat, Offset, Poly, 0, POLY_SIZE) end function PolyVec.MatVecMultiply(A: buffer, B: buffer, C: buffer, ARows: number, ACols: number, BRows: number) local PolySize = POLY_SIZE local AccumPoly = TEMP_POLY_ACCUM local TempPoly = TEMP_POLY_MUL local PolyMul = Ntt.PolyMulAt local PolyAdd = Ntt.PolyAddAt for I = 0, ARows - 1 do local COffset = I * PolySize buffer.fill(AccumPoly, 0, 0, PolySize) for K = 0, ACols - 1 do local AOffset = (I * ACols + K) * PolySize local BOffset = K * PolySize PolyMul(A, AOffset, B, BOffset, TempPoly, 0) PolyAdd(AccumPoly, 0, TempPoly, 0, AccumPoly, 0) end buffer.copy(C, COffset, AccumPoly, 0, PolySize) end end function PolyVec.VecNtt(Vec: buffer, K: number) local PolySize = POLY_SIZE local NttAt = Ntt.NttAt for I = 0, K - 1 do NttAt(Vec, I * PolySize) end end function PolyVec.VecIntt(Vec: buffer, K: number) local PolySize = POLY_SIZE local InttAt = Ntt.InttAt for I = 0, K - 1 do InttAt(Vec, I * PolySize) end end function PolyVec.VecAddTo(Src: buffer, Dst: buffer, K: number) local Modulus = Q local Total = K * N * 2 for Offset = 0, Total - 2, 2 do local SrcValue = buffer.readu16(Src, Offset) local DstValue = buffer.readu16(Dst, Offset) local Sum = SrcValue + DstValue buffer.writeu16(Dst, Offset, if Sum >= Modulus then Sum - Modulus else Sum) end end function PolyVec.VecAdd(A: buffer, B: buffer, Result: buffer, K: number) if not (MlKemParams.CheckK(K) or K == 1) then error("Invalid vector dimension K") end local TotalCoeffs = K * N local Modulus = Q for Index = 0, TotalCoeffs - 1 do local Offset = Index * 2 local AValue = buffer.readu16(A, Offset) local BValue = buffer.readu16(B, Offset) local Sum = AValue + BValue local AddResult = if Sum >= Modulus then Sum - Modulus else Sum buffer.writeu16(Result, Offset, AddResult) end end function PolyVec.VecEncode(Vec: buffer, K: number, L: number): buffer local OutputSize = K * 32 * L local Output = buffer.create(OutputSize) local PolySize = POLY_SIZE local ChunkSize = 32 * L local EncodeAt = MlKemSerialize.EncodeAt local Encode = MlKemSerialize.Encode if L == 12 then for I = 0, K - 1 do EncodeAt(Vec, I * PolySize, Output, I * ChunkSize, 12) end else local Poly = TEMP_POLY_ENCODE for I = 0, K - 1 do buffer.copy(Poly, 0, Vec, I * PolySize, PolySize) local EncodedPoly = Encode(Poly, L) buffer.copy(Output, I * ChunkSize, EncodedPoly, 0, ChunkSize) end end return Output end function PolyVec.VecDecode(Data: buffer, K: number, L: number): buffer local Vec = buffer.create(K * POLY_SIZE) local PolySize = POLY_SIZE local ChunkSize = 32 * L local DecodeAt = MlKemSerialize.DecodeAt local Decode = MlKemSerialize.Decode if L == 12 then for I = 0, K - 1 do DecodeAt(Data, I * ChunkSize, Vec, I * PolySize, 12) end else local PolyData = buffer.create(ChunkSize) for I = 0, K - 1 do buffer.copy(PolyData, 0, Data, I * ChunkSize, ChunkSize) local DecodedPoly = Decode(PolyData, L) buffer.copy(Vec, I * PolySize, DecodedPoly, 0, PolySize) end end return Vec end function PolyVec.VecCompress(Vec: buffer, K: number, D: number) local Poly = TEMP_POLY_COMPRESS local PolySize = POLY_SIZE for I = 0, K - 1 do local Offset = I * PolySize buffer.copy(Poly, 0, Vec, Offset, PolySize) Compression.PolyCompress(Poly, D) buffer.copy(Vec, Offset, Poly, 0, PolySize) end end function PolyVec.VecDecompress(Vec: buffer, K: number, D: number) local Poly = TEMP_POLY_COMPRESS local PolySize = POLY_SIZE for I = 0, K - 1 do local Offset = I * PolySize buffer.copy(Poly, 0, Vec, Offset, PolySize) Compression.PolyDecompress(Poly, D) buffer.copy(Vec, Offset, Poly, 0, PolySize) end end return PolyVec
1,569
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/SHA3.luau
--!strict --!optimize 2 --!native local SHA3 = {} local LOW_ROUND, HIGH_ROUND = buffer.create(96), buffer.create(96) do local HighFactorKeccak = 0 local ShiftRegister = 29 local function GetNextBit(): number local Result = ShiftRegister % 2 ShiftRegister = bit32.bxor((ShiftRegister - Result) // 2, 142 * Result) return Result end for Index = 0, 23 do local LowValue = 0 local Multiplier: number for _ = 1, 6 do Multiplier = if Multiplier then Multiplier * Multiplier * 2 else 1 LowValue += GetNextBit() * Multiplier end local HighValue = GetNextBit() * Multiplier buffer.writeu32(HIGH_ROUND, Index * 4, HighValue) buffer.writeu32(LOW_ROUND, Index * 4, LowValue + HighValue * HighFactorKeccak) end end local LANES_LOW = buffer.create(100) local LANES_HIGH = buffer.create(100) local function Keccak(LanesLow: buffer, LanesHigh: buffer, InputBuffer: buffer, Offset: number, Size: number, BlockSizeInBytes: number): () local QuadWordsQuantity = BlockSizeInBytes // 8 local RCHigh, RCLow = HIGH_ROUND, LOW_ROUND for Position = Offset, Offset + Size - 1, BlockSizeInBytes do for Index = 0, (QuadWordsQuantity - 1) * 4, 4 do local BufferPos = Position + Index * 2 buffer.writeu32(LanesLow, Index, bit32.bxor( buffer.readu32(LanesLow, Index), buffer.readu32(InputBuffer, BufferPos) )) buffer.writeu32(LanesHigh, Index, bit32.bxor( buffer.readu32(LanesHigh, Index), buffer.readu32(InputBuffer, BufferPos + 4) )) end local Lane01Low, Lane01High = buffer.readu32(LanesLow, 0), buffer.readu32(LanesHigh, 0) local Lane02Low, Lane02High = buffer.readu32(LanesLow, 4), buffer.readu32(LanesHigh, 4) local Lane03Low, Lane03High = buffer.readu32(LanesLow, 8), buffer.readu32(LanesHigh, 8) local Lane04Low, Lane04High = buffer.readu32(LanesLow, 12), buffer.readu32(LanesHigh, 12) local Lane05Low, Lane05High = buffer.readu32(LanesLow, 16), buffer.readu32(LanesHigh, 16) local Lane06Low, Lane06High = buffer.readu32(LanesLow, 20), buffer.readu32(LanesHigh, 20) local Lane07Low, Lane07High = buffer.readu32(LanesLow, 24), buffer.readu32(LanesHigh, 24) local Lane08Low, Lane08High = buffer.readu32(LanesLow, 28), buffer.readu32(LanesHigh, 28) local Lane09Low, Lane09High = buffer.readu32(LanesLow, 32), buffer.readu32(LanesHigh, 32) local Lane10Low, Lane10High = buffer.readu32(LanesLow, 36), buffer.readu32(LanesHigh, 36) local Lane11Low, Lane11High = buffer.readu32(LanesLow, 40), buffer.readu32(LanesHigh, 40) local Lane12Low, Lane12High = buffer.readu32(LanesLow, 44), buffer.readu32(LanesHigh, 44) local Lane13Low, Lane13High = buffer.readu32(LanesLow, 48), buffer.readu32(LanesHigh, 48) local Lane14Low, Lane14High = buffer.readu32(LanesLow, 52), buffer.readu32(LanesHigh, 52) local Lane15Low, Lane15High = buffer.readu32(LanesLow, 56), buffer.readu32(LanesHigh, 56) local Lane16Low, Lane16High = buffer.readu32(LanesLow, 60), buffer.readu32(LanesHigh, 60) local Lane17Low, Lane17High = buffer.readu32(LanesLow, 64), buffer.readu32(LanesHigh, 64) local Lane18Low, Lane18High = buffer.readu32(LanesLow, 68), buffer.readu32(LanesHigh, 68) local Lane19Low, Lane19High = buffer.readu32(LanesLow, 72), buffer.readu32(LanesHigh, 72) local Lane20Low, Lane20High = buffer.readu32(LanesLow, 76), buffer.readu32(LanesHigh, 76) local Lane21Low, Lane21High = buffer.readu32(LanesLow, 80), buffer.readu32(LanesHigh, 80) local Lane22Low, Lane22High = buffer.readu32(LanesLow, 84), buffer.readu32(LanesHigh, 84) local Lane23Low, Lane23High = buffer.readu32(LanesLow, 88), buffer.readu32(LanesHigh, 88) local Lane24Low, Lane24High = buffer.readu32(LanesLow, 92), buffer.readu32(LanesHigh, 92) local Lane25Low, Lane25High = buffer.readu32(LanesLow, 96), buffer.readu32(LanesHigh, 96) for RoundIndex = 0, 92, 4 do local Column1Low, Column1High = bit32.bxor(Lane01Low, Lane06Low, Lane11Low, Lane16Low, Lane21Low), bit32.bxor(Lane01High, Lane06High, Lane11High, Lane16High, Lane21High) local Column2Low, Column2High = bit32.bxor(Lane02Low, Lane07Low, Lane12Low, Lane17Low, Lane22Low), bit32.bxor(Lane02High, Lane07High, Lane12High, Lane17High, Lane22High) local Column3Low, Column3High = bit32.bxor(Lane03Low, Lane08Low, Lane13Low, Lane18Low, Lane23Low), bit32.bxor(Lane03High, Lane08High, Lane13High, Lane18High, Lane23High) local Column4Low, Column4High = bit32.bxor(Lane04Low, Lane09Low, Lane14Low, Lane19Low, Lane24Low), bit32.bxor(Lane04High, Lane09High, Lane14High, Lane19High, Lane24High) local Column5Low, Column5High = bit32.bxor(Lane05Low, Lane10Low, Lane15Low, Lane20Low, Lane25Low), bit32.bxor(Lane05High, Lane10High, Lane15High, Lane20High, Lane25High) local DeltaLow, DeltaHigh = bit32.bxor(Column1Low, Column3Low * 2 + Column3High // 2147483648), bit32.bxor(Column1High, Column3High * 2 + Column3Low // 2147483648) local Temp0Low, Temp0High = bit32.bxor(DeltaLow, Lane02Low), bit32.bxor(DeltaHigh, Lane02High) local Temp1Low, Temp1High = bit32.bxor(DeltaLow, Lane07Low), bit32.bxor(DeltaHigh, Lane07High) local Temp2Low, Temp2High = bit32.bxor(DeltaLow, Lane12Low), bit32.bxor(DeltaHigh, Lane12High) local Temp3Low, Temp3High = bit32.bxor(DeltaLow, Lane17Low), bit32.bxor(DeltaHigh, Lane17High) local Temp4Low, Temp4High = bit32.bxor(DeltaLow, Lane22Low), bit32.bxor(DeltaHigh, Lane22High) Lane02Low = Temp1Low // 1048576 + (Temp1High * 4096); Lane02High = Temp1High // 1048576 + (Temp1Low * 4096) Lane07Low = Temp3Low // 524288 + (Temp3High * 8192); Lane07High = Temp3High // 524288 + (Temp3Low * 8192) Lane12Low = Temp0Low * 2 + Temp0High // 2147483648; Lane12High = Temp0High * 2 + Temp0Low // 2147483648 Lane17Low = Temp2Low * 1024 + Temp2High // 4194304; Lane17High = Temp2High * 1024 + Temp2Low // 4194304 Lane22Low = Temp4Low * 4 + Temp4High // 1073741824; Lane22High = Temp4High * 4 + Temp4Low // 1073741824 DeltaLow = bit32.bxor(Column2Low, Column4Low * 2 + Column4High // 2147483648); DeltaHigh = bit32.bxor(Column2High, Column4High * 2 + Column4Low // 2147483648) Temp0Low = bit32.bxor(DeltaLow, Lane03Low); Temp0High = bit32.bxor(DeltaHigh, Lane03High) Temp1Low = bit32.bxor(DeltaLow, Lane08Low); Temp1High = bit32.bxor(DeltaHigh, Lane08High) Temp2Low = bit32.bxor(DeltaLow, Lane13Low); Temp2High = bit32.bxor(DeltaHigh, Lane13High) Temp3Low = bit32.bxor(DeltaLow, Lane18Low); Temp3High = bit32.bxor(DeltaHigh, Lane18High) Temp4Low = bit32.bxor(DeltaLow, Lane23Low); Temp4High = bit32.bxor(DeltaHigh, Lane23High) Lane03Low = Temp2Low // 2097152 + (Temp2High * 2048); Lane03High = Temp2High // 2097152 + (Temp2Low * 2048) Lane08Low = Temp4Low // 8 + bit32.bor(Temp4High * 536870912, 0); Lane08High = Temp4High // 8 + bit32.bor(Temp4Low * 536870912, 0) Lane13Low = Temp1Low * 64 + Temp1High // 67108864; Lane13High = Temp1High * 64 + Temp1Low // 67108864 Lane18Low = (Temp3Low * 32768) + Temp3High // 131072; Lane18High = (Temp3High * 32768) + Temp3Low // 131072 Lane23Low = Temp0Low // 4 + bit32.bor(Temp0High * 1073741824, 0); Lane23High = Temp0High // 4 + bit32.bor(Temp0Low * 1073741824, 0) DeltaLow = bit32.bxor(Column3Low, Column5Low * 2 + Column5High // 2147483648); DeltaHigh = bit32.bxor(Column3High, Column5High * 2 + Column5Low // 2147483648) Temp0Low = bit32.bxor(DeltaLow, Lane04Low); Temp0High = bit32.bxor(DeltaHigh, Lane04High) Temp1Low = bit32.bxor(DeltaLow, Lane09Low); Temp1High = bit32.bxor(DeltaHigh, Lane09High) Temp2Low = bit32.bxor(DeltaLow, Lane14Low); Temp2High = bit32.bxor(DeltaHigh, Lane14High) Temp3Low = bit32.bxor(DeltaLow, Lane19Low); Temp3High = bit32.bxor(DeltaHigh, Lane19High) Temp4Low = bit32.bxor(DeltaLow, Lane24Low); Temp4High = bit32.bxor(DeltaHigh, Lane24High) Lane04Low = bit32.bor(Temp3Low * 2097152, 0) + Temp3High // 2048; Lane04High = bit32.bor(Temp3High * 2097152, 0) + Temp3Low // 2048 Lane09Low = bit32.bor(Temp0Low * 268435456, 0) + Temp0High // 16; Lane09High = bit32.bor(Temp0High * 268435456, 0) + Temp0Low // 16 Lane14Low = bit32.bor(Temp2Low * 33554432, 0) + Temp2High // 128; Lane14High = bit32.bor(Temp2High * 33554432, 0) + Temp2Low // 128 Lane19Low = Temp4Low // 256 + bit32.bor(Temp4High * 16777216, 0); Lane19High = Temp4High // 256 + bit32.bor(Temp4Low * 16777216, 0) Lane24Low = Temp1Low // 512 + bit32.bor(Temp1High * 8388608, 0); Lane24High = Temp1High // 512 + bit32.bor(Temp1Low * 8388608, 0) DeltaLow = bit32.bxor(Column4Low, Column1Low * 2 + Column1High // 2147483648); DeltaHigh = bit32.bxor(Column4High, Column1High * 2 + Column1Low // 2147483648) Temp0Low = bit32.bxor(DeltaLow, Lane05Low); Temp0High = bit32.bxor(DeltaHigh, Lane05High) Temp1Low = bit32.bxor(DeltaLow, Lane10Low); Temp1High = bit32.bxor(DeltaHigh, Lane10High) Temp2Low = bit32.bxor(DeltaLow, Lane15Low); Temp2High = bit32.bxor(DeltaHigh, Lane15High) Temp3Low = bit32.bxor(DeltaLow, Lane20Low); Temp3High = bit32.bxor(DeltaHigh, Lane20High) Temp4Low = bit32.bxor(DeltaLow, Lane25Low); Temp4High = bit32.bxor(DeltaHigh, Lane25High) Lane05Low = (Temp4Low * 16384) + Temp4High // 262144; Lane05High = (Temp4High * 16384) + Temp4Low // 262144 Lane10Low = bit32.bor(Temp1Low * 1048576, 0) + Temp1High // 4096; Lane10High = bit32.bor(Temp1High * 1048576, 0) + Temp1Low // 4096 Lane15Low = Temp3Low * 256 + Temp3High // 16777216; Lane15High = Temp3High * 256 + Temp3Low // 16777216 Lane20Low = bit32.bor(Temp0Low * 134217728, 0) + Temp0High // 32; Lane20High = bit32.bor(Temp0High * 134217728, 0) + Temp0Low // 32 Lane25Low = Temp2Low // 33554432 + Temp2High * 128; Lane25High = Temp2High // 33554432 + Temp2Low * 128 DeltaLow = bit32.bxor(Column5Low, Column2Low * 2 + Column2High // 2147483648); DeltaHigh = bit32.bxor(Column5High, Column2High * 2 + Column2Low // 2147483648) Temp1Low = bit32.bxor(DeltaLow, Lane06Low); Temp1High = bit32.bxor(DeltaHigh, Lane06High) Temp2Low = bit32.bxor(DeltaLow, Lane11Low); Temp2High = bit32.bxor(DeltaHigh, Lane11High) Temp3Low = bit32.bxor(DeltaLow, Lane16Low); Temp3High = bit32.bxor(DeltaHigh, Lane16High) Temp4Low = bit32.bxor(DeltaLow, Lane21Low); Temp4High = bit32.bxor(DeltaHigh, Lane21High) Lane06Low = Temp2Low * 8 + Temp2High // 536870912; Lane06High = Temp2High * 8 + Temp2Low // 536870912 Lane11Low = (Temp4Low * 262144) + Temp4High // 16384; Lane11High = (Temp4High * 262144) + Temp4Low // 16384 Lane16Low = Temp1Low // 268435456 + Temp1High * 16; Lane16High = Temp1High // 268435456 + Temp1Low * 16 Lane21Low = Temp3Low // 8388608 + Temp3High * 512; Lane21High = Temp3High // 8388608 + Temp3Low * 512 Lane01Low = bit32.bxor(DeltaLow, Lane01Low); Lane01High = bit32.bxor(DeltaHigh, Lane01High) Lane01Low, Lane02Low, Lane03Low, Lane04Low, Lane05Low = bit32.bxor(Lane01Low, bit32.band(-1 - Lane02Low, Lane03Low)), bit32.bxor(Lane02Low, bit32.band(-1 - Lane03Low, Lane04Low)), bit32.bxor(Lane03Low, bit32.band(-1 - Lane04Low, Lane05Low)), bit32.bxor(Lane04Low, bit32.band(-1 - Lane05Low, Lane01Low)), bit32.bxor(Lane05Low, bit32.band(-1 - Lane01Low, Lane02Low)) :: number Lane01High, Lane02High, Lane03High, Lane04High, Lane05High = bit32.bxor(Lane01High, bit32.band(-1 - Lane02High, Lane03High)), bit32.bxor(Lane02High, bit32.band(-1 - Lane03High, Lane04High)), bit32.bxor(Lane03High, bit32.band(-1 - Lane04High, Lane05High)), bit32.bxor(Lane04High, bit32.band(-1 - Lane05High, Lane01High)), bit32.bxor(Lane05High, bit32.band(-1 - Lane01High, Lane02High)) :: number Lane06Low, Lane07Low, Lane08Low, Lane09Low, Lane10Low = bit32.bxor(Lane09Low, bit32.band(-1 - Lane10Low, Lane06Low)), bit32.bxor(Lane10Low, bit32.band(-1 - Lane06Low, Lane07Low)), bit32.bxor(Lane06Low, bit32.band(-1 - Lane07Low, Lane08Low)), bit32.bxor(Lane07Low, bit32.band(-1 - Lane08Low, Lane09Low)), bit32.bxor(Lane08Low, bit32.band(-1 - Lane09Low, Lane10Low)) :: number Lane06High, Lane07High, Lane08High, Lane09High, Lane10High = bit32.bxor(Lane09High, bit32.band(-1 - Lane10High, Lane06High)), bit32.bxor(Lane10High, bit32.band(-1 - Lane06High, Lane07High)), bit32.bxor(Lane06High, bit32.band(-1 - Lane07High, Lane08High)), bit32.bxor(Lane07High, bit32.band(-1 - Lane08High, Lane09High)), bit32.bxor(Lane08High, bit32.band(-1 - Lane09High, Lane10High)) :: number Lane11Low, Lane12Low, Lane13Low, Lane14Low, Lane15Low = bit32.bxor(Lane12Low, bit32.band(-1 - Lane13Low, Lane14Low)), bit32.bxor(Lane13Low, bit32.band(-1 - Lane14Low, Lane15Low)), bit32.bxor(Lane14Low, bit32.band(-1 - Lane15Low, Lane11Low)), bit32.bxor(Lane15Low, bit32.band(-1 - Lane11Low, Lane12Low)), bit32.bxor(Lane11Low, bit32.band(-1 - Lane12Low, Lane13Low)) :: number Lane11High, Lane12High, Lane13High, Lane14High, Lane15High = bit32.bxor(Lane12High, bit32.band(-1 - Lane13High, Lane14High)), bit32.bxor(Lane13High, bit32.band(-1 - Lane14High, Lane15High)), bit32.bxor(Lane14High, bit32.band(-1 - Lane15High, Lane11High)), bit32.bxor(Lane15High, bit32.band(-1 - Lane11High, Lane12High)), bit32.bxor(Lane11High, bit32.band(-1 - Lane12High, Lane13High)) :: number Lane16Low, Lane17Low, Lane18Low, Lane19Low, Lane20Low = bit32.bxor(Lane20Low, bit32.band(-1 - Lane16Low, Lane17Low)), bit32.bxor(Lane16Low, bit32.band(-1 - Lane17Low, Lane18Low)), bit32.bxor(Lane17Low, bit32.band(-1 - Lane18Low, Lane19Low)), bit32.bxor(Lane18Low, bit32.band(-1 - Lane19Low, Lane20Low)), bit32.bxor(Lane19Low, bit32.band(-1 - Lane20Low, Lane16Low)) :: number Lane16High, Lane17High, Lane18High, Lane19High, Lane20High = bit32.bxor(Lane20High, bit32.band(-1 - Lane16High, Lane17High)), bit32.bxor(Lane16High, bit32.band(-1 - Lane17High, Lane18High)), bit32.bxor(Lane17High, bit32.band(-1 - Lane18High, Lane19High)), bit32.bxor(Lane18High, bit32.band(-1 - Lane19High, Lane20High)), bit32.bxor(Lane19High, bit32.band(-1 - Lane20High, Lane16High)) :: number Lane21Low, Lane22Low, Lane23Low, Lane24Low, Lane25Low = bit32.bxor(Lane23Low, bit32.band(-1 - Lane24Low, Lane25Low)), bit32.bxor(Lane24Low, bit32.band(-1 - Lane25Low, Lane21Low)), bit32.bxor(Lane25Low, bit32.band(-1 - Lane21Low, Lane22Low)), bit32.bxor(Lane21Low, bit32.band(-1 - Lane22Low, Lane23Low)), bit32.bxor(Lane22Low, bit32.band(-1 - Lane23Low, Lane24Low)) :: number Lane21High, Lane22High, Lane23High, Lane24High, Lane25High = bit32.bxor(Lane23High, bit32.band(-1 - Lane24High, Lane25High)), bit32.bxor(Lane24High, bit32.band(-1 - Lane25High, Lane21High)), bit32.bxor(Lane25High, bit32.band(-1 - Lane21High, Lane22High)), bit32.bxor(Lane21High, bit32.band(-1 - Lane22High, Lane23High)), bit32.bxor(Lane22High, bit32.band(-1 - Lane23High, Lane24High)) :: number Lane01Low = bit32.bxor(Lane01Low, buffer.readu32(RCLow, RoundIndex)) Lane01High = bit32.bxor(Lane01High, buffer.readu32(RCHigh, RoundIndex)) end buffer.writeu32(LanesLow, 0, Lane01Low); buffer.writeu32(LanesHigh, 0, Lane01High) buffer.writeu32(LanesLow, 4, Lane02Low); buffer.writeu32(LanesHigh, 4, Lane02High) buffer.writeu32(LanesLow, 8, Lane03Low); buffer.writeu32(LanesHigh, 8, Lane03High) buffer.writeu32(LanesLow, 12, Lane04Low); buffer.writeu32(LanesHigh, 12, Lane04High) buffer.writeu32(LanesLow, 16, Lane05Low); buffer.writeu32(LanesHigh, 16, Lane05High) buffer.writeu32(LanesLow, 20, Lane06Low); buffer.writeu32(LanesHigh, 20, Lane06High) buffer.writeu32(LanesLow, 24, Lane07Low); buffer.writeu32(LanesHigh, 24, Lane07High) buffer.writeu32(LanesLow, 28, Lane08Low); buffer.writeu32(LanesHigh, 28, Lane08High) buffer.writeu32(LanesLow, 32, Lane09Low); buffer.writeu32(LanesHigh, 32, Lane09High) buffer.writeu32(LanesLow, 36, Lane10Low); buffer.writeu32(LanesHigh, 36, Lane10High) buffer.writeu32(LanesLow, 40, Lane11Low); buffer.writeu32(LanesHigh, 40, Lane11High) buffer.writeu32(LanesLow, 44, Lane12Low); buffer.writeu32(LanesHigh, 44, Lane12High) buffer.writeu32(LanesLow, 48, Lane13Low); buffer.writeu32(LanesHigh, 48, Lane13High) buffer.writeu32(LanesLow, 52, Lane14Low); buffer.writeu32(LanesHigh, 52, Lane14High) buffer.writeu32(LanesLow, 56, Lane15Low); buffer.writeu32(LanesHigh, 56, Lane15High) buffer.writeu32(LanesLow, 60, Lane16Low); buffer.writeu32(LanesHigh, 60, Lane16High) buffer.writeu32(LanesLow, 64, Lane17Low); buffer.writeu32(LanesHigh, 64, Lane17High) buffer.writeu32(LanesLow, 68, Lane18Low); buffer.writeu32(LanesHigh, 68, Lane18High) buffer.writeu32(LanesLow, 72, Lane19Low); buffer.writeu32(LanesHigh, 72, Lane19High) buffer.writeu32(LanesLow, 76, Lane20Low); buffer.writeu32(LanesHigh, 76, Lane20High) buffer.writeu32(LanesLow, 80, Lane21Low); buffer.writeu32(LanesHigh, 80, Lane21High) buffer.writeu32(LanesLow, 84, Lane22Low); buffer.writeu32(LanesHigh, 84, Lane22High) buffer.writeu32(LanesLow, 88, Lane23Low); buffer.writeu32(LanesHigh, 88, Lane23High) buffer.writeu32(LanesLow, 92, Lane24Low); buffer.writeu32(LanesHigh, 92, Lane24High) buffer.writeu32(LanesLow, 96, Lane25Low); buffer.writeu32(LanesHigh, 96, Lane25High) end end local function ProcessSponge(Message: buffer, CapacityBits: number, OutputBytes: number, DomainSeparator: number): buffer local RateBytes = (1600 - CapacityBits) // 8 buffer.fill(LANES_LOW, 0, 0, 100) buffer.fill(LANES_HIGH, 0, 0, 100) local LanesLow = LANES_LOW local LanesHigh = LANES_HIGH local MessageLength: number = buffer.len(Message) local PaddedLength: number = MessageLength + 1 local Remainder = PaddedLength % RateBytes if Remainder ~= 0 then PaddedLength += (RateBytes - Remainder) end local PaddedMessage = buffer.create(PaddedLength) if MessageLength > 0 then buffer.copy(PaddedMessage, 0, Message, 0, MessageLength) end if PaddedLength - MessageLength == 1 then buffer.writeu8(PaddedMessage, MessageLength, bit32.bor(DomainSeparator, 0x80)) else buffer.writeu8(PaddedMessage, MessageLength, DomainSeparator) if PaddedLength - MessageLength > 2 then buffer.fill(PaddedMessage, MessageLength + 1, 0, PaddedLength - MessageLength - 2) end buffer.writeu8(PaddedMessage, PaddedLength - 1, 0x80) end Keccak(LanesLow, LanesHigh, PaddedMessage, 0, PaddedLength, RateBytes) local Output = buffer.create(OutputBytes) local OutputOffset = 0 local ZeroBuffer = buffer.create(RateBytes) while OutputOffset < OutputBytes do local BytesThisRound = math.min(RateBytes, OutputBytes - OutputOffset) for ByteIndex = 0, BytesThisRound - 1 do local AbsoluteIndex = OutputOffset + ByteIndex if AbsoluteIndex < OutputBytes then local Lane = ByteIndex // 8 local ByteInLane = ByteIndex % 8 local LaneOffset = Lane * 4 local Value if ByteInLane < 4 then Value = bit32.extract(buffer.readu32(LanesLow, LaneOffset), ByteInLane * 8, 8) else Value = bit32.extract(buffer.readu32(LanesHigh, LaneOffset), (ByteInLane - 4) * 8, 8) end buffer.writeu8(Output, AbsoluteIndex, Value) end end OutputOffset += BytesThisRound if OutputOffset < OutputBytes then Keccak(LanesLow, LanesHigh, ZeroBuffer, 0, RateBytes, RateBytes) end end return Output end function SHA3.SHA3_256(Message: buffer): buffer return ProcessSponge(Message, 512, 32, 0x06) end function SHA3.SHA3_512(Message: buffer): buffer return ProcessSponge(Message, 1024, 64, 0x06) end function SHA3.SHAKE256(Message: buffer, OutputBytes: number): buffer return ProcessSponge(Message, 512, OutputBytes, 0x1F) end return SHA3
6,832
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/Sampling.luau
--[=[ ML-KEM Sampling Module Polynomial sampling operations for ML-KEM. Uniform sampling from Rq and centered binomial distribution sampling. Example usage: local Sampling = require(script.Sampling) local Rho = buffer.create(32) local Matrix = Sampling.GenerateMatrix(3, Rho, false) local Sigma = buffer.create(32) local Vector = Sampling.GenerateVector(3, 2, Sigma, 0) local PrfOutput = buffer.create(128) local NoisePoly = Sampling.SamplePolyCbd(PrfOutput, 2) --]=] --!strict --!optimize 2 --!native local PolyVec = require("./PolyVec") local MlKemParams = require("./Params") local SHA3 = require("./SHA3") local XOF = require("./XOF") local LOG2N = 8 local N = 2^LOG2N local POLY_SIZE = N * 2 local Q = 13 * 256 + 1 local SAMPLE_NTT_CHUNK = buffer.create(168) local SAMPLE_NTT_POLY = buffer.create(N * 2) local GEN_VECTOR_PRF_OUTPUT = buffer.create(192) local GEN_VECTOR_PRF_INPUT = buffer.create(33) local function SamplePolyCbd2(Prf: buffer, Poly: buffer, Offset: number?) local BaseOffset = Offset or 0 local Mask2 = 0x03 local Modulus = Q for I = 0, 127 do local PolyOffset = I * 2 local Word = buffer.readu8(Prf, I) local T0 = bit32.band(Word, 0x55) local T1 = bit32.band(bit32.rshift(Word, 1), 0x55) local T2 = T0 + T1 local A0 = bit32.band(T2, Mask2) local B0 = bit32.band(bit32.rshift(T2, 2), Mask2) local Diff0 = A0 - B0 local Coeff0 = if Diff0 < 0 then Diff0 + Modulus else Diff0 local A1 = bit32.band(bit32.rshift(T2, 4), Mask2) local B1 = bit32.band(bit32.rshift(T2, 6), Mask2) local Diff1 = A1 - B1 local Coeff1 = if Diff1 < 0 then Diff1 + Modulus else Diff1 buffer.writeu16(Poly, BaseOffset + PolyOffset * 2, Coeff0) buffer.writeu16(Poly, BaseOffset + (PolyOffset + 1) * 2, Coeff1) end end local function SamplePolyCbd3(Prf: buffer, Poly: buffer, Offset: number?) local BaseOffset = Offset or 0 local Mask24 = 0x249249 local Mask3 = 0x07 local Modulus = Q for I = 0, 63 do local ByteOffset = I * 3 local PolyOffset = I * 4 local B0 = buffer.readu8(Prf, ByteOffset) local B1 = buffer.readu8(Prf, ByteOffset + 1) local B2 = buffer.readu8(Prf, ByteOffset + 2) local Word = bit32.bor(B0, bit32.lshift(B1, 8), bit32.lshift(B2, 16)) local T0 = bit32.band(Word, Mask24) local T1 = bit32.band(bit32.rshift(Word, 1), Mask24) local T2 = bit32.band(bit32.rshift(Word, 2), Mask24) local T3 = T0 + T1 + T2 for J = 0, 3 do local JOffset = J * 6 local A = bit32.band(bit32.rshift(T3, JOffset), Mask3) local B = bit32.band(bit32.rshift(T3, JOffset + 3), Mask3) local Diff = A - B local Coeff = if Diff < 0 then Diff + Modulus else Diff buffer.writeu16(Poly, BaseOffset + (PolyOffset + J) * 2, Coeff) end end end local function SampleNtt(XofInput: buffer, Poly: buffer) local CoeffIndex = 0 local Chunk = SAMPLE_NTT_CHUNK XOF.Reset128() XOF.Absorb128(XofInput) while CoeffIndex < N do XOF.Squeeze128Into(Chunk, 168, 0) local Offset = 0 while Offset + 2 < 168 and CoeffIndex < N do local B0 = buffer.readu8(Chunk, Offset) local B1 = buffer.readu8(Chunk, Offset + 1) local B2 = buffer.readu8(Chunk, Offset + 2) local D1 = bit32.bor(B0, bit32.lshift(bit32.band(B1, 0x0F), 8)) local D2 = bit32.bor(bit32.rshift(B1, 4), bit32.lshift(B2, 4)) if D1 < Q then buffer.writeu16(Poly, CoeffIndex * 2, D1) CoeffIndex += 1 end if D2 < Q and CoeffIndex < N then buffer.writeu16(Poly, CoeffIndex * 2, D2) CoeffIndex += 1 end Offset += 3 end end end local Sampling = {} function Sampling.GenerateMatrix(K: number, Rho: buffer, Transpose: boolean): buffer local Matrix = PolyVec.MatCreate(K, K) local XofInput = buffer.create(34) buffer.copy(XofInput, 0, Rho, 0, 32) local PolySize = POLY_SIZE local Poly = SAMPLE_NTT_POLY local Sample = SampleNtt for I = 0, K - 1 do for J = 0, K - 1 do if Transpose then buffer.writeu8(XofInput, 32, I) buffer.writeu8(XofInput, 33, J) else buffer.writeu8(XofInput, 32, J) buffer.writeu8(XofInput, 33, I) end Sample(XofInput, Poly) local Index = (I * K + J) * PolySize buffer.copy(Matrix, Index, Poly, 0, PolySize) end end return Matrix end function Sampling.SamplePolyCbd(Prf: buffer, Eta: number): buffer local Poly = buffer.create(N * 2) if Eta == 2 then SamplePolyCbd2(Prf, Poly, 0) else SamplePolyCbd3(Prf, Poly, 0) end return Poly end function Sampling.GenerateVector(K: number, Eta: number, Sigma: buffer, Nonce: number): buffer local Vec = PolyVec.VecCreate(K) local PrfInput = GEN_VECTOR_PRF_INPUT local PrfOutput = GEN_VECTOR_PRF_OUTPUT buffer.copy(PrfInput, 0, Sigma, 0, 32) local PolySize = POLY_SIZE local PrfLen = 64 * Eta for I = 0, K - 1 do buffer.writeu8(PrfInput, 32, Nonce + I) XOF.Reset256() XOF.Absorb256(PrfInput) XOF.Squeeze256Into(PrfOutput, PrfLen, 0) local Offset = I * PolySize if Eta == 2 then SamplePolyCbd2(PrfOutput, Vec, Offset) else SamplePolyCbd3(PrfOutput, Vec, Offset) end end return Vec end function Sampling.GenerateNoisePoly(Eta: number, Sigma: buffer, Nonce: number): buffer if not MlKemParams.CheckEta(Eta) then error("Invalid eta parameter") end if buffer.len(Sigma) ~= 32 then error("Sigma must be 32 bytes") end local PrfInput = buffer.create(33) buffer.copy(PrfInput, 0, Sigma, 0, 32) buffer.writeu8(PrfInput, 32, Nonce) local PrfOutput = SHA3.SHAKE256(PrfInput, 64 * Eta) return Sampling.SamplePolyCbd(PrfOutput, Eta) end return Sampling
1,932
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/Serialize.luau
--[=[ ML-KEM Serialization Module Polynomial encoding and decoding operations for ML-KEM. Converts polynomials to/from byte arrays with different bit lengths. Example usage: local Serialize = require(script.Serialize) local Poly = buffer.create(512) -- 256 coefficients local Encoded = Serialize.Encode(Poly, 12) local Decoded = Serialize.Decode(Encoded, 12) --]=] --!strict --!optimize 2 --!native local Params = require("./Params") local LOG2N = 8 local N = 2^LOG2N local Serialize = {} function Serialize.Encode(Poly: buffer, L: number): buffer if not Params.CheckL(L) then error("Invalid encoding parameter l") end local OutputSize = 32 * L local Output = buffer.create(OutputSize) if L == 1 then local IterCount = N / 8 for I = 0, IterCount - 1 do local Offset = I * 8 local Byte = 0 for J = 0, 7 do local Coeff = buffer.readu16(Poly, (Offset + J) * 2) local Bit = bit32.band(Coeff, 1) Byte = bit32.bor(Byte, bit32.lshift(Bit, J)) end buffer.writeu8(Output, I, Byte) end elseif L == 4 then local IterCount = N / 2 for I = 0, IterCount - 1 do local Offset = I * 2 local C0 = bit32.band(buffer.readu16(Poly, Offset * 2), 0xF) local C1 = bit32.band(buffer.readu16(Poly, (Offset + 1) * 2), 0xF) local Byte = bit32.bor(C0, bit32.lshift(C1, 4)) buffer.writeu8(Output, I, Byte) end elseif L == 5 then local IterCount = N / 8 for I = 0, IterCount - 1 do local PolyOffset = I * 8 local ByteOffset = I * 5 local T0 = buffer.readu16(Poly, (PolyOffset + 0) * 2) local T1 = buffer.readu16(Poly, (PolyOffset + 1) * 2) local T2 = buffer.readu16(Poly, (PolyOffset + 2) * 2) local T3 = buffer.readu16(Poly, (PolyOffset + 3) * 2) local T4 = buffer.readu16(Poly, (PolyOffset + 4) * 2) local T5 = buffer.readu16(Poly, (PolyOffset + 5) * 2) local T6 = buffer.readu16(Poly, (PolyOffset + 6) * 2) local T7 = buffer.readu16(Poly, (PolyOffset + 7) * 2) buffer.writeu8(Output, ByteOffset + 0, bit32.bor(bit32.band(T0, 0x1F), bit32.lshift(bit32.band(T1, 0x07), 5))) buffer.writeu8(Output, ByteOffset + 1, bit32.bor(bit32.rshift(T1, 3), bit32.lshift(bit32.band(T2, 0x1F), 2), bit32.lshift(bit32.band(T3, 0x01), 7))) buffer.writeu8(Output, ByteOffset + 2, bit32.bor(bit32.rshift(T3, 1), bit32.lshift(bit32.band(T4, 0x0F), 4))) buffer.writeu8(Output, ByteOffset + 3, bit32.bor(bit32.rshift(T4, 4), bit32.lshift(bit32.band(T5, 0x1F), 1), bit32.lshift(bit32.band(T6, 0x03), 6))) buffer.writeu8(Output, ByteOffset + 4, bit32.bor(bit32.rshift(T6, 2), bit32.lshift(bit32.band(T7, 0x1F), 3))) end elseif L == 10 then local IterCount = N / 4 for I = 0, IterCount - 1 do local PolyOffset = I * 4 local ByteOffset = I * 5 local T0 = buffer.readu16(Poly, (PolyOffset + 0) * 2) local T1 = buffer.readu16(Poly, (PolyOffset + 1) * 2) local T2 = buffer.readu16(Poly, (PolyOffset + 2) * 2) local T3 = buffer.readu16(Poly, (PolyOffset + 3) * 2) buffer.writeu8(Output, ByteOffset + 0, bit32.band(T0, 0xFF)) buffer.writeu8(Output, ByteOffset + 1, bit32.bor(bit32.rshift(T0, 8), bit32.lshift(bit32.band(T1, 0x3F), 2))) buffer.writeu8(Output, ByteOffset + 2, bit32.bor(bit32.rshift(T1, 6), bit32.lshift(bit32.band(T2, 0x0F), 4))) buffer.writeu8(Output, ByteOffset + 3, bit32.bor(bit32.rshift(T2, 4), bit32.lshift(bit32.band(T3, 0x03), 6))) buffer.writeu8(Output, ByteOffset + 4, bit32.rshift(T3, 2)) end elseif L == 11 then local IterCount = N / 8 for I = 0, IterCount - 1 do local PolyOffset = I * 8 local ByteOffset = I * 11 local T0 = buffer.readu16(Poly, (PolyOffset + 0) * 2) local T1 = buffer.readu16(Poly, (PolyOffset + 1) * 2) local T2 = buffer.readu16(Poly, (PolyOffset + 2) * 2) local T3 = buffer.readu16(Poly, (PolyOffset + 3) * 2) local T4 = buffer.readu16(Poly, (PolyOffset + 4) * 2) local T5 = buffer.readu16(Poly, (PolyOffset + 5) * 2) local T6 = buffer.readu16(Poly, (PolyOffset + 6) * 2) local T7 = buffer.readu16(Poly, (PolyOffset + 7) * 2) buffer.writeu8(Output, ByteOffset + 0, bit32.band(T0, 0xFF)) buffer.writeu8(Output, ByteOffset + 1, bit32.bor(bit32.rshift(T0, 8), bit32.lshift(bit32.band(T1, 0x1F), 3))) buffer.writeu8(Output, ByteOffset + 2, bit32.bor(bit32.rshift(T1, 5), bit32.lshift(bit32.band(T2, 0x03), 6))) buffer.writeu8(Output, ByteOffset + 3, bit32.rshift(T2, 2)) buffer.writeu8(Output, ByteOffset + 4, bit32.bor(bit32.rshift(T2, 10), bit32.lshift(bit32.band(T3, 0x7F), 1))) buffer.writeu8(Output, ByteOffset + 5, bit32.bor(bit32.rshift(T3, 7), bit32.lshift(bit32.band(T4, 0x0F), 4))) buffer.writeu8(Output, ByteOffset + 6, bit32.bor(bit32.rshift(T4, 4), bit32.lshift(bit32.band(T5, 0x01), 7))) buffer.writeu8(Output, ByteOffset + 7, bit32.rshift(T5, 1)) buffer.writeu8(Output, ByteOffset + 8, bit32.bor(bit32.rshift(T5, 9), bit32.lshift(bit32.band(T6, 0x3F), 2))) buffer.writeu8(Output, ByteOffset + 9, bit32.bor(bit32.rshift(T6, 6), bit32.lshift(bit32.band(T7, 0x07), 5))) buffer.writeu8(Output, ByteOffset + 10, bit32.rshift(T7, 3)) end else local IterCount = N / 2 for I = 0, IterCount - 1 do local PolyOffset = I * 2 local ByteOffset = I * 3 local T0 = buffer.readu16(Poly, (PolyOffset + 0) * 2) local T1 = buffer.readu16(Poly, (PolyOffset + 1) * 2) buffer.writeu8(Output, ByteOffset + 0, bit32.band(T0, 0xFF)) buffer.writeu8(Output, ByteOffset + 1, bit32.bor(bit32.rshift(T0, 8), bit32.lshift(bit32.band(T1, 0x0F), 4))) buffer.writeu8(Output, ByteOffset + 2, bit32.rshift(T1, 4)) end end return Output end function Serialize.EncodeAt(Poly: buffer, PolyOffset: number, Output: buffer, OutOffset: number, L: number) if L == 12 then for I = 0, 127 do local PolyIdx = PolyOffset + I * 4 local ByteIdx = OutOffset + I * 3 local T0 = buffer.readu16(Poly, PolyIdx) local T1 = buffer.readu16(Poly, PolyIdx + 2) buffer.writeu8(Output, ByteIdx, bit32.band(T0, 0xFF)) buffer.writeu8(Output, ByteIdx + 1, bit32.bor(bit32.rshift(T0, 8), bit32.lshift(bit32.band(T1, 0x0F), 4))) buffer.writeu8(Output, ByteIdx + 2, bit32.rshift(T1, 4)) end end end function Serialize.Decode(Data: buffer, L: number): buffer if not Params.CheckL(L) then error("Invalid encoding parameter l") end local Poly = buffer.create(N * 2) if L == 1 then local IterCount = N / 8 for I = 0, IterCount - 1 do local Byte = buffer.readu8(Data, I) local Offset = I * 8 for J = 0, 7 do local Bit = bit32.band(bit32.rshift(Byte, J), 1) buffer.writeu16(Poly, (Offset + J) * 2, Bit) end end elseif L == 4 then local IterCount = N / 2 for I = 0, IterCount - 1 do local Byte = buffer.readu8(Data, I) local Offset = I * 2 buffer.writeu16(Poly, (Offset + 0) * 2, bit32.band(Byte, 0x0F)) buffer.writeu16(Poly, (Offset + 1) * 2, bit32.rshift(Byte, 4)) end elseif L == 5 then local IterCount = N / 8 for I = 0, IterCount - 1 do local PolyOffset = I * 8 local ByteOffset = I * 5 local B0 = buffer.readu8(Data, ByteOffset + 0) local B1 = buffer.readu8(Data, ByteOffset + 1) local B2 = buffer.readu8(Data, ByteOffset + 2) local B3 = buffer.readu8(Data, ByteOffset + 3) local B4 = buffer.readu8(Data, ByteOffset + 4) local T0 = bit32.band(B0, 0x1F) local T1 = bit32.bor(bit32.rshift(B0, 5), bit32.lshift(bit32.band(B1, 0x03), 3)) local T2 = bit32.band(bit32.rshift(B1, 2), 0x1F) local T3 = bit32.bor(bit32.rshift(B1, 7), bit32.lshift(bit32.band(B2, 0x0F), 1)) local T4 = bit32.bor(bit32.rshift(B2, 4), bit32.lshift(bit32.band(B3, 0x01), 4)) local T5 = bit32.band(bit32.rshift(B3, 1), 0x1F) local T6 = bit32.bor(bit32.rshift(B3, 6), bit32.lshift(bit32.band(B4, 0x07), 2)) local T7 = bit32.rshift(B4, 3) buffer.writeu16(Poly, (PolyOffset + 0) * 2, T0) buffer.writeu16(Poly, (PolyOffset + 1) * 2, T1) buffer.writeu16(Poly, (PolyOffset + 2) * 2, T2) buffer.writeu16(Poly, (PolyOffset + 3) * 2, T3) buffer.writeu16(Poly, (PolyOffset + 4) * 2, T4) buffer.writeu16(Poly, (PolyOffset + 5) * 2, T5) buffer.writeu16(Poly, (PolyOffset + 6) * 2, T6) buffer.writeu16(Poly, (PolyOffset + 7) * 2, T7) end elseif L == 10 then local IterCount = N / 4 for I = 0, IterCount - 1 do local PolyOffset = I * 4 local ByteOffset = I * 5 local B0 = buffer.readu8(Data, ByteOffset + 0) local B1 = buffer.readu8(Data, ByteOffset + 1) local B2 = buffer.readu8(Data, ByteOffset + 2) local B3 = buffer.readu8(Data, ByteOffset + 3) local B4 = buffer.readu8(Data, ByteOffset + 4) local T0 = bit32.bor(B0, bit32.lshift(bit32.band(B1, 0x03), 8)) local T1 = bit32.bor(bit32.rshift(B1, 2), bit32.lshift(bit32.band(B2, 0x0F), 6)) local T2 = bit32.bor(bit32.rshift(B2, 4), bit32.lshift(bit32.band(B3, 0x3F), 4)) local T3 = bit32.bor(bit32.rshift(B3, 6), bit32.lshift(B4, 2)) buffer.writeu16(Poly, (PolyOffset + 0) * 2, T0) buffer.writeu16(Poly, (PolyOffset + 1) * 2, T1) buffer.writeu16(Poly, (PolyOffset + 2) * 2, T2) buffer.writeu16(Poly, (PolyOffset + 3) * 2, T3) end elseif L == 11 then local IterCount = N / 8 for I = 0, IterCount - 1 do local PolyOffset = I * 8 local ByteOffset = I * 11 local B0 = buffer.readu8(Data, ByteOffset + 0) local B1 = buffer.readu8(Data, ByteOffset + 1) local B2 = buffer.readu8(Data, ByteOffset + 2) local B3 = buffer.readu8(Data, ByteOffset + 3) local B4 = buffer.readu8(Data, ByteOffset + 4) local B5 = buffer.readu8(Data, ByteOffset + 5) local B6 = buffer.readu8(Data, ByteOffset + 6) local B7 = buffer.readu8(Data, ByteOffset + 7) local B8 = buffer.readu8(Data, ByteOffset + 8) local B9 = buffer.readu8(Data, ByteOffset + 9) local B10 = buffer.readu8(Data, ByteOffset + 10) local T0 = bit32.bor(B0, bit32.lshift(bit32.band(B1, 0x07), 8)) local T1 = bit32.bor(bit32.rshift(B1, 3), bit32.lshift(bit32.band(B2, 0x3F), 5)) local T2 = bit32.bor(bit32.rshift(B2, 6), bit32.lshift(B3, 2), bit32.lshift(bit32.band(B4, 0x01), 10)) local T3 = bit32.bor(bit32.rshift(B4, 1), bit32.lshift(bit32.band(B5, 0x0F), 7)) local T4 = bit32.bor(bit32.rshift(B5, 4), bit32.lshift(bit32.band(B6, 0x7F), 4)) local T5 = bit32.bor(bit32.rshift(B6, 7), bit32.lshift(B7, 1), bit32.lshift(bit32.band(B8, 0x03), 9)) local T6 = bit32.bor(bit32.rshift(B8, 2), bit32.lshift(bit32.band(B9, 0x1F), 6)) local T7 = bit32.bor(bit32.rshift(B9, 5), bit32.lshift(B10, 3)) buffer.writeu16(Poly, (PolyOffset + 0) * 2, T0) buffer.writeu16(Poly, (PolyOffset + 1) * 2, T1) buffer.writeu16(Poly, (PolyOffset + 2) * 2, T2) buffer.writeu16(Poly, (PolyOffset + 3) * 2, T3) buffer.writeu16(Poly, (PolyOffset + 4) * 2, T4) buffer.writeu16(Poly, (PolyOffset + 5) * 2, T5) buffer.writeu16(Poly, (PolyOffset + 6) * 2, T6) buffer.writeu16(Poly, (PolyOffset + 7) * 2, T7) end else local IterCount = N / 2 for I = 0, IterCount - 1 do local PolyOffset = I * 2 local ByteOffset = I * 3 local B0 = buffer.readu8(Data, ByteOffset + 0) local B1 = buffer.readu8(Data, ByteOffset + 1) local B2 = buffer.readu8(Data, ByteOffset + 2) local T0 = bit32.bor(B0, bit32.lshift(bit32.band(B1, 0x0F), 8)) local T1 = bit32.bor(bit32.rshift(B1, 4), bit32.lshift(B2, 4)) if T0 >= 3329 or T1 >= 3329 then error("Invalid polynomial coefficient encoding") end buffer.writeu16(Poly, (PolyOffset + 0) * 2, T0) buffer.writeu16(Poly, (PolyOffset + 1) * 2, T1) end end return Poly end function Serialize.DecodeAt(Data: buffer, DataOffset: number, Poly: buffer, PolyOffset: number, L: number) if L == 12 then for I = 0, 127 do local ByteIdx = DataOffset + I * 3 local PolyIdx = PolyOffset + I * 4 local B0 = buffer.readu8(Data, ByteIdx) local B1 = buffer.readu8(Data, ByteIdx + 1) local B2 = buffer.readu8(Data, ByteIdx + 2) local T0 = bit32.bor(B0, bit32.lshift(bit32.band(B1, 0x0F), 8)) local T1 = bit32.bor(bit32.rshift(B1, 4), bit32.lshift(B2, 4)) if T0 >= 3329 or T1 >= 3329 then error("Invalid polynomial coefficient encoding") end buffer.writeu16(Poly, PolyIdx, T0) buffer.writeu16(Poly, PolyIdx + 2, T1) end end end return Serialize
4,688
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/Utils.luau
--[=[ ML-KEM Utilities Module Utility functions for ML-KEM implementation Example usage: local Utils = require(script.Utils) local IsEqual = Utils.CtMemcmp(Buffer1, Buffer2) Utils.CtCondMemcpy(Condition, Dest, Src1, Src2) local PubKeySize = Utils.GetKemPublicKeyLen(4) -- 1568 bytes local SecKeySize = Utils.GetKemSecretKeyLen(4) -- 3168 bytes --]=] --!strict --!optimize 2 --!native local MlKemParams = require("./Params") local Utils = {} function Utils.CtMemcmp(Bytes0: buffer, Bytes1: buffer): number local Len0 = buffer.len(Bytes0) local Len1 = buffer.len(Bytes1) if Len0 ~= Len1 then return 0x00000000 end local Diff = 0 local Len4 = Len0 - (Len0 % 4) for Index = 0, Len4 - 4, 4 do local Word0 = buffer.readu32(Bytes0, Index) local Word1 = buffer.readu32(Bytes1, Index) Diff = bit32.bor(Diff, bit32.bxor(Word0, Word1)) end for Index = Len4, Len0 - 1 do local Byte0 = buffer.readu8(Bytes0, Index) local Byte1 = buffer.readu8(Bytes1, Index) Diff = bit32.bor(Diff, bit32.bxor(Byte0, Byte1)) end return if Diff == 0 then 0xFFFFFFFF else 0x00000000 end function Utils.CtCondMemcpy(Cond: number, Sink: buffer, Source0: buffer, Source1: buffer) local SinkLen = buffer.len(Sink) local Mask = bit32.band(Cond, 0xFFFFFFFF) local InvMask = bit32.bnot(Mask) local Len4 = SinkLen - (SinkLen % 4) for Index = 0, Len4 - 4, 4 do local Word0 = buffer.readu32(Source0, Index) local Word1 = buffer.readu32(Source1, Index) local Selected = bit32.bor(bit32.band(Word0, Mask), bit32.band(Word1, InvMask)) buffer.writeu32(Sink, Index, Selected) end for Index = Len4, SinkLen - 1 do local Byte0 = buffer.readu8(Source0, Index) local Byte1 = buffer.readu8(Source1, Index) local Selected = bit32.bor(bit32.band(Byte0, Mask), bit32.band(Byte1, InvMask)) buffer.writeu8(Sink, Index, Selected) end end function Utils.BitReverse(Value: number, BitWidth: number): number local Reversed = 0 for I = 0, BitWidth - 1 do local Bit = bit32.band(bit32.rshift(Value, I), 1) Reversed = bit32.bor(Reversed, bit32.lshift(Bit, BitWidth - 1 - I)) end return Reversed end function Utils.GetPkePublicKeyLen(K: number): number if not MlKemParams.CheckK(K) then error("Invalid K parameter") end return K * 12 * 32 + 32 end function Utils.GetPkeSecretKeyLen(K: number): number if not MlKemParams.CheckK(K) then error("Invalid K parameter") end return K * 12 * 32 end function Utils.GetPkeCipherTextLen(K: number, Du: number, Dv: number): number if not MlKemParams.CheckK(K) then error("Invalid K parameter") end if not MlKemParams.CheckD(Du) then error("Invalid Du parameter") end if not MlKemParams.CheckD(Dv) then error("Invalid Dv parameter") end return 32 * (K * Du + Dv) end function Utils.GetKemPublicKeyLen(K: number): number return Utils.GetPkePublicKeyLen(K) end function Utils.GetKemSecretKeyLen(K: number): number if not MlKemParams.CheckK(K) then error("Invalid K parameter") end return Utils.GetPkeSecretKeyLen(K) + Utils.GetPkePublicKeyLen(K) + 32 + 32 end function Utils.GetKemCipherTextLen(K: number, Du: number, Dv: number): number return Utils.GetPkeCipherTextLen(K, Du, Dv) end return Utils
1,023
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/MlKEM/init.luau
--[=[ ML-KEM Main Module (Key Encapsulation Mechanism) The complete ML-KEM post quantum key encapsulation. Key generation, encapsulation, and decapsulation operations with CCA security using the Fujisaki Okamoto transform. Example usage: local MlKem = require(script.MlKem) local CSPRNG = require(script.CSPRNG) local D = CSPRNG.RandomBytes(32) local Z = CSPRNG.RandomBytes(32) local PublicKey, SecretKey = MlKem.MLKEM_1024.KeyGen(D, Z) local Message = CSPRNG.RandomBytes(32) local Success, Ciphertext, SharedSecret = MlKem.MLKEM_1024.Encapsulate(Message, PublicKey) if Success then local RecoveredSecret = MlKem.MLKEM_1024.Decapsulate(Ciphertext, SecretKey) -- RecoveredSecret should equal SharedSecret end --]=] --!strict --!optimize 2 --!native local Pke = require("@self/PKE") local Polyvec = require("@self/PolyVec") local CSPRNG = require("@self/CSPRNG") local Params = require("@self/Params") local Utils = require("@self/Utils") local SHA3 = require("@self/SHA3") local DECAP_G_INPUT = buffer.create(64) local DECAP_K_PRIME = buffer.create(32) local DECAP_R_PRIME = buffer.create(32) local DECAP_J_OUTPUT = buffer.create(32) local ENCAP_G_INPUT = buffer.create(64) local ENCAP_R = buffer.create(32) local MlKem = { CSPRNG = CSPRNG } function MlKem.KeyGen(K: number, Eta1: number, D: buffer, Z: buffer): (buffer, buffer) if not Params.CheckKeygenParams(K, Eta1) then error("Invalid keygen parameters") end if buffer.len(D) ~= 32 then error("D must be 32 bytes") end if buffer.len(Z) ~= 32 then error("Z must be 32 bytes") end local KpkePublicKey, KpkeSecretKey = Pke.KeyGen(K, Eta1, D) local PublicKeyHash = SHA3.SHA3_256(KpkePublicKey) local SecretKeyLen = Utils.GetKemSecretKeyLen(K) local SecretKey = buffer.create(SecretKeyLen) local Offset = 0 local KpkeSecretKeyLen = buffer.len(KpkeSecretKey) buffer.copy(SecretKey, Offset, KpkeSecretKey, 0, KpkeSecretKeyLen) Offset = Offset + KpkeSecretKeyLen local KpkePublicKeyLen = buffer.len(KpkePublicKey) buffer.copy(SecretKey, Offset, KpkePublicKey, 0, KpkePublicKeyLen) Offset += KpkePublicKeyLen buffer.copy(SecretKey, Offset, PublicKeyHash, 0, 32) Offset += 32 buffer.copy(SecretKey, Offset, Z, 0, 32) return KpkePublicKey, SecretKey end function MlKem.Encapsulate(Message: buffer, K: number, Eta1: number, Eta2: number, Du: number, Dv: number, PublicKey: buffer): (buffer?, buffer?) if not Params.CheckEncapParams(K, Eta1, Eta2, Du, Dv) then error("Invalid encapsulation parameters") end if buffer.len(PublicKey) ~= Utils.GetKemPublicKeyLen(K) then error("Invalid public key length") end if buffer.len(Message) ~= 32 then error("Message must be 32 bytes") end local RhoOffset = K * 12 * 32 local EncodedTPrime = buffer.create(RhoOffset) buffer.copy(EncodedTPrime, 0, PublicKey, 0, RhoOffset) local TPrime = Polyvec.VecDecode(EncodedTPrime, K, 12) local ReEncodedTPrime = Polyvec.VecEncode(TPrime, K, 12) local IsValid = Utils.CtMemcmp(EncodedTPrime, ReEncodedTPrime) if IsValid ~= 0xFFFFFFFF then error("malformed public key encoding") end local PublicKeyHash = SHA3.SHA3_256(PublicKey) local GInput = ENCAP_G_INPUT buffer.copy(GInput, 0, Message, 0, 32) buffer.copy(GInput, 32, PublicKeyHash, 0, 32) local GOutput = SHA3.SHA3_512(GInput) local K_bytes = buffer.create(32) local R = ENCAP_R buffer.copy(K_bytes, 0, GOutput, 0, 32) buffer.copy(R, 0, GOutput, 32, 32) local Ciphertext = Pke.Encrypt(K, Eta1, Eta2, Du, Dv, PublicKey, Message, R) return Ciphertext, K_bytes end function MlKem.Decapsulate(Ciphertext: buffer, K: number, Eta1: number, Eta2: number, Du: number, Dv: number, SecretKey: buffer): buffer if not Params.CheckDecapParams(K, Eta1, Eta2, Du, Dv) then error("Invalid decapsulation parameters") end if buffer.len(SecretKey) ~= Utils.GetKemSecretKeyLen(K) then error("Invalid secret key length") end if buffer.len(Ciphertext) ~= Utils.GetKemCipherTextLen(K, Du, Dv) then error("Invalid ciphertext length") end local KpkeSecretKeyLen = Utils.GetPkeSecretKeyLen(K) local KpkePublicKeyLen = Utils.GetPkePublicKeyLen(K) local KpkeSecretKey = buffer.create(KpkeSecretKeyLen) local KpkePublicKey = buffer.create(KpkePublicKeyLen) local H = buffer.create(32) local Z = buffer.create(32) local Offset = 0 buffer.copy(KpkeSecretKey, 0, SecretKey, Offset, KpkeSecretKeyLen) Offset += KpkeSecretKeyLen buffer.copy(KpkePublicKey, 0, SecretKey, Offset, KpkePublicKeyLen) Offset += KpkePublicKeyLen buffer.copy(H, 0, SecretKey, Offset, 32) Offset += 32 buffer.copy(Z, 0, SecretKey, Offset, 32) local MPrime = Pke.Decrypt(K, Du, Dv, KpkeSecretKey, Ciphertext) local GInput = DECAP_G_INPUT buffer.copy(GInput, 0, MPrime, 0, 32) buffer.copy(GInput, 32, H, 0, 32) local GOutput = SHA3.SHA3_512(GInput) local KPrime = DECAP_K_PRIME local RPrime = DECAP_R_PRIME buffer.copy(KPrime, 0, GOutput, 0, 32) buffer.copy(RPrime, 0, GOutput, 32, 32) local JInput = buffer.create(32 + buffer.len(Ciphertext)) buffer.copy(JInput, 0, Z, 0, 32) buffer.copy(JInput, 32, Ciphertext, 0, buffer.len(Ciphertext)) local JOutputBuffer = SHA3.SHAKE256(JInput, 32) local JOutput = DECAP_J_OUTPUT buffer.copy(JOutput, 0, JOutputBuffer, 0, 32) local CiphertextPrime = Pke.Encrypt(K, Eta1, Eta2, Du, Dv, KpkePublicKey, MPrime, RPrime) local IsValid = Utils.CtMemcmp(Ciphertext, CiphertextPrime) local SharedSecret = buffer.create(32) Utils.CtCondMemcpy(IsValid, SharedSecret, KPrime, JOutput) return SharedSecret end function MlKem.SecretsEqual(Secret1: buffer, Secret2: buffer): boolean if buffer.len(Secret1) ~= 32 or buffer.len(Secret2) ~= 32 then return false end return Utils.CtMemcmp(Secret1, Secret2) == 0xFFFFFFFF end function MlKem.ValidateDecapsulationKey(K: number, SecretKey: buffer): boolean local KpkeSecretKeyLen = Utils.GetPkeSecretKeyLen(K) local KpkePublicKeyLen = Utils.GetPkePublicKeyLen(K) local EkOffset = KpkeSecretKeyLen local HOffset = KpkeSecretKeyLen + KpkePublicKeyLen local Ek = buffer.create(KpkePublicKeyLen) local StoredH = buffer.create(32) buffer.copy(Ek, 0, SecretKey, EkOffset, KpkePublicKeyLen) buffer.copy(StoredH, 0, SecretKey, HOffset, 32) local ComputedH = SHA3.SHA3_256(Ek) return Utils.CtMemcmp(StoredH, ComputedH) == 0xFFFFFFFF end MlKem.MLKEM_512 = { KeyGen = function(D: buffer, Z: buffer): (buffer, buffer) return MlKem.KeyGen(2, 3, D, Z) end, Encapsulate = function(Message: buffer, PublicKey: buffer): (buffer?, buffer?) return MlKem.Encapsulate(Message, 2, 3, 2, 10, 4, PublicKey) end, Decapsulate = function(Ciphertext: buffer, SecretKey: buffer): buffer return MlKem.Decapsulate(Ciphertext, 2, 3, 2, 10, 4, SecretKey) end, GenerateKeys = function(): (buffer, buffer) local D = CSPRNG.RandomBytes(32) local Z = CSPRNG.RandomBytes(32) return MlKem.MLKEM_512.KeyGen(D, Z) end, ValidateDecapsulationKey = function(SecretKey: buffer): boolean return MlKem.ValidateDecapsulationKey(2, SecretKey) end } MlKem.MLKEM_768 = { KeyGen = function(D: buffer, Z: buffer): (buffer, buffer) return MlKem.KeyGen(3, 2, D, Z) end, Encapsulate = function(Message: buffer, PublicKey: buffer): (buffer?, buffer?) return MlKem.Encapsulate(Message, 3, 2, 2, 10, 4, PublicKey) end, Decapsulate = function(Ciphertext: buffer, SecretKey: buffer): buffer return MlKem.Decapsulate(Ciphertext, 3, 2, 2, 10, 4, SecretKey) end, GenerateKeys = function(): (buffer, buffer) local D = CSPRNG.RandomBytes(32) local Z = CSPRNG.RandomBytes(32) return MlKem.MLKEM_768.KeyGen(D, Z) end, ValidateDecapsulationKey = function(SecretKey: buffer): boolean return MlKem.ValidateDecapsulationKey(3, SecretKey) end } MlKem.MLKEM_1024 = { KeyGen = function(D: buffer, Z: buffer): (buffer, buffer) return MlKem.KeyGen(4, 2, D, Z) end, Encapsulate = function(Message: buffer, PublicKey: buffer): (buffer?, buffer?) return MlKem.Encapsulate(Message, 4, 2, 2, 11, 5, PublicKey) end, Decapsulate = function(Ciphertext: buffer, SecretKey: buffer): buffer return MlKem.Decapsulate(Ciphertext, 4, 2, 2, 11, 5, SecretKey) end, GenerateKeys = function(): (buffer, buffer) local D = CSPRNG.RandomBytes(32) local Z = CSPRNG.RandomBytes(32) return MlKem.MLKEM_1024.KeyGen(D, Z) end, ValidateDecapsulationKey = function(SecretKey: buffer): boolean return MlKem.ValidateDecapsulationKey(4, SecretKey) end } return MlKem
2,691
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Verification/init.luau
--!strict local Algorithms = table.freeze({ EdDSA = require("@self/EdDSA"), MlDSA = require("@self/MlDSA"), MlKEM = require("@self/MlKEM"), }) return Algorithms
48
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/init.luau
--!strict local Cryptography = table.freeze({ Hashing = require("@self/Hashing"), Checksums = require("@self/Checksums"), Utilities = require("@self/Utilities"), Encryption = require("@self/Encryption"), Verification = require("@self/Verification") }) return Cryptography
64
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/client/HostExample.client.luau
--[=[ Host A sample script on how you would run a shader. ]=] --!native -- // Dependencies local Client = game.Players.LocalPlayer local RbxShader = require(game.ReplicatedStorage.RbxShader) -- // Configurations local CONFIGURATIONS = { InterlaceFactor = 2 , DualAxisInterlacing = true , ScreenDivision = 4 , IsBlurred = false } local CANVAS_SIZE = Vector2.new(180, 120) -- try (192, 108) too! local SHADER = script.Shaders.VoxelShader local SCREEN = Instance.new('ScreenGui') SCREEN.Parent = Client.PlayerGui SCREEN.IgnoreGuiInset = true SCREEN.ResetOnSpawn = false RbxShader.new( SHADER.Name, SHADER, CONFIGURATIONS, script, SCREEN, CANVAS_SIZE) RbxShader.run( SHADER.Name ) task.wait(5) RbxShader.pause( SHADER.Name ) task.wait(5) RbxShader.resume( SHADER.Name )
220
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/BasicVoxelTunnel.luau
--[=[ BasicVoxelTunnel Shader by @Miojo on https://www.shadertoy.com/view/mt2cWm Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) -- // Variables local res = .6 -- @ voxel size local max_iter = 80 -- @ raycast depth local distFade = 6 -- @ distance fade local speed = 2 -- @ travel speed local lightClamp = distFade / 2 -- // The white part of the tunnel local function path1 ( z : number ) return Vector3.new( g.sin(z * .2) * 3 , g.cos(z * .3) * 2 , z ) end -- // The yellow part of the tunnel local function path2 ( z : number ) return Vector3.new( g.sin(z * .2) * 1 , g.cos(z * .3) * 4 - 1 , z ) end -- // The blue part of the tunnel local function path3 ( z : number ) return Vector3.new( g.sin(z * .3) * 3 , g.cos(z * .2) - 1 , z ) end local cor : Vector3 local function map ( p : Vector3 ) local d1 = (p - path1(p.Z)).Magnitude local d2 = (p - path2(p.Z)).Magnitude local d3 = (p - path3(p.Z)).Magnitude local s = 1.5 local ret = s - g.min(d1, g.min(d2, d3)) cor = Vector3.xAxis if ret == s - d1 then cor = Vector3.one elseif ret == s - d2 then cor = Vector3.new(1,1,0) elseif ret == s - d3 then cor = Vector3.new(0,1,1) end return ret end -- // Fragment shader return { CONFIGURATION = { InterlaceFactor = 1 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 ) local uv = (fragCoords - 0.5 * iResolution) / iResolution.Y -- // path local t = speed * iTime local ro = path1(t) local rd = path1(t + 1) -- // camera local f = (rd - ro).Unit local u = Vector3.yAxis local s = u:Cross(f).Unit u = f:Cross(s).Unit rd = (uv.X * s + uv.Y * u + f).Unit -- /* -- * "Digital Differential Analysis" (DDA) -- */ local mask, i local grid = (ro / res):Floor() * res local dGrid = rd:Sign() * res local dCubo = 1 / rd:Abs() local cubo = ( rd:Sign() * (grid - ro) + (rd:Sign() * .5 + Vector3.one * .5) * res ) * dCubo for __ = 1, max_iter do i = __ if map(grid) < 0 then break end mask = g.step_v3(cubo, g.yzx(cubo)) * g.step_v3(cubo, g.zxy(cubo)) grid += dGrid * mask cubo += dCubo * mask * res end local col = cor if i < max_iter then local d = (cubo * dCubo * res):Dot(mask) local p = ro + d * rd local q = g.fract_v3(p/res) - Vector3.one * 0.5 -- // border q = q:Abs() local bd = 1 - g.smoothstep(.02, 0, .4 - .8 * g.yzx(q):Max(g.zxy(q)):Dot(mask)) col += cor:Lerp(cor/2, bd) --mix(cor, cor/2, bd) --[[ -- // sweeping line col *= g.cos(t/2) > uv.X and 2 or 1 -- // dots col += Vector3.one * (g.cos(t/2) > uv.X and -1 or 1 - q.Magnitude * 4) ]] -- // distance fade col *= distFade / (d * d) - .05 -- // lights? shadows? oclusion? end -- // gamma correction col = g.sqrt_v3(col/lightClamp) return g.v3_rgb(col) end, }
1,147
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/Cosmic.luau
--[=[ Cosmic Shader by @Xor on https://www.shadertoy.com/view/msjXRK Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec3 = Vector3.new local vec2 = Vector2.new --[[ /* "Cosmic" by @XorDev I love making these glowy shaders. This time I thought I'd try using discs instead. Tweet: twitter.com/XorDev/status/1601060422819680256 Twigl: t.co/IhRk3HX4Kt <300 chars playlist: shadertoy.com/playlist/fXlGDN */ ]] -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) -- // Clear fragcolor (hacky) fragColor *= 0; -- // Initialize resolution for scaling local r : Vector2 = iResolution; -- // Save centered pixel coordinates local p = (fragCoords-r*.6); p = vec2( (p.X) + (2*p.Y), (-p.X) + (2*p.Y) ); -- // Initialize loop iterator and arc angle local a : number = 0; for i = 1, 30 do -- // Add with ring attenuation fragCoords = p/(r+r-p).Y; a = g.atan2(fragCoords.Y, fragCoords.X)*g.ceil(i*.1)+iTime*g.sin(i*i)+i*i; fragColor += Vector3.one * .2 / (g.abs(fragCoords.Magnitude*8e1-i)+4e1/r.Y) * -- // Limit to arcs g.clamp(g.cos(a),.0,.6) * -- // Give them color (g.cos_v3(Vector3.one * (a-i) + vec3(0,1,2))+Vector3.one); end return g.v3_rgb(fragColor); end }
548
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/Currents.luau
--[=[ Currents Shader by @s23b on https://www.shadertoy.com/view/MsG3DK Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec3 = Vector3.new local vec2 = Vector2.new local uvec3 = Vector3.one local uvec2 = Vector2.one local smoothstep = g.smoothstep type float = number type vec2 = Vector2 type vec3 = Vector3 local SMOOTH = true local TAU = 6.28318530718 local function hash(uv: vec2): float return g.fract(math.cos(math.sin(uv:Dot(vec2(.009123898, .00231233))) * 48.512353) * 11111.5452313); end local function noise(uv: vec2): float local fuv = uv:Floor(); local c_x = hash(fuv + vec2(0, 0)) local c_y = hash(fuv + vec2(0, 1)) local c_z = hash(fuv + vec2(1, 0)) local c_w = hash(fuv + vec2(1, 1)) local a1 = if SMOOTH then smoothstep(0, 1, g.fract(uv.Y)) else g.fract(uv.Y); local a2 = if SMOOTH then smoothstep(0, 1, g.fract(uv.X)) else g.fract(uv.X); local axis = g.mix_v2(vec2(c_x, c_z), vec2(c_y, c_w), a1); return g.mix(axis.X, axis.Y, a2); end local function fbm(uv: vec2, iTime: float): float local f = 0.; local r = 1.; local lim = if SMOOTH then 3 else 8 for i = 0, lim-1, 1 do uv += vec2(-1, 1) * iTime / 16. local _r = r r *= 2. f += noise((uv)*_r) / r; end return f / (1. - 1. / r); end local function createBall(uv: vec2): vec3 local f = g.smoothstep(0.5, 1.4, (uv-vec2(-.1, .1)).Magnitude) * .5; f += smoothstep(.0, .9, 1.3- (uv-vec2(-.3, .3)).Magnitude) * .5; f += smoothstep(.1, .5, .5- (uv-vec2(-.4, .4)).Magnitude); f += smoothstep(.1, .5, .4- (uv-vec2(.2, .6)).Magnitude); f *= 1. - smoothstep(.95, 1., (uv-vec2(.0, .0)).Magnitude); return uvec3*f; end -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) local uv = fragCoords / iResolution * 2. - uvec2; uv = vec2(uv.X * iResolution.X / iResolution.Y, uv.Y); local ball = vec2(.2, -.4 + (math.sin(iTime * 4.) / 40.)); local r = .2; -- // create distorted version of the space local distuv = uv * vec2(150, 130) + vec2(0, 20); distuv *= (uv-vec2(1.5, -2)).Magnitude / 3.; -- vvv @temp; not from source code local dxa = distuv.X + smoothstep(1. - r * 1.5, 1., 1. - (uv-(ball - vec2(.1, 0))).Magnitude) * 15.; -- // add distortion for the ball distuv = vec2(dxa, distuv.Y) -- // calculate distortion level from distance to lower right corner local t = smoothstep(0., 1., 1. - ((uv * .5)-vec2(.4, -.85)).Magnitude); -- // add noise to distortion weighted by distortion level distuv += uvec2*(fbm(uv * 2., iTime) - .5) * t * 100.; -- // calculate stripes local f = math.sin(distuv.X + distuv.Y); -- // calculate distance from distorted diagonal local d = (distuv.X + distuv.Y) / TAU; if math.abs(uv.X) > 1. or math.abs(uv.Y) > 1. then -- // outside boundaries fragColor = Vector3.zero; elseif d < .5 and d > - 1. then -- // inside red line local grad = math.min(1., (.75 - math.abs(d + .25)) * 5.); fragColor = g.mix_v3(vec3(.92,.16,.20), vec3(.93, .64, .17), -uv.Y) * grad; else -- // lines local spot = math.clamp(3. - ((uv * vec2(1, 2))-vec2(-1, -1)).Magnitude, 0., 1.); fragColor = vec3(.8, .68, .82) * f * spot; end -- // create ball color local b = createBall((uv - ball) / r); -- // create ball mask local mask = 1. - smoothstep(r - .002, r + .01, (uv-ball).Magnitude); mask *= smoothstep(-1.2, -.9, d); -- // add ball fragColor = g.mix_v3(fragColor, b, mask); -- // add a noise fragColor -= uvec3*noise(uv * 300. + uvec2*(g.fract(iTime) * 10000.)) / 5.; return g.v3_rgb(fragColor); end }
1,461
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/GravitySucks.luau
--[=[ GravitySucks Shader by @mrange on https://www.shadertoy.com/view/4cyXWw Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) -- // CC0: Gravity sucks -- // Tinkering away.... local LAYERS = 5. local SCALE = 1. local PI = 3.141592654 local TAU = (2.0*PI) -- // License: Unknown, author: Unknown, found: don't remember local function hash( co : number ) : number return g.fract(g.sin(co*12.9898) * 13758.5453); end -- // License: MIT OR CC-BY-NC-4.0, author: mercury, found: https://mercury.sexy/hg_sdf/ -- /* `p` is `inout`, meaning that change to it is global(?) local function mod1( p : number, size : number ) : (number, number) local halfsize = size/2 local c = g.floor((p + halfsize)/size) p = ((p + halfsize) % size) - halfsize return c, p end -- // License: Unknown, author: Unknown, found: don't remember local function bounce( t : number, dy : number , dropOff : number ) : number local gr = 5 local p0 = 2*dy/gr t += p0/2 local ldo = g.log(dropOff); local yy = 1. - (1. - dropOff) * t / p0; if yy > 1e-4 then local n = g.floor(g.log(yy) / ldo); local dn = g.pow(dropOff, n); local yyy = dy * dn; t -= p0 * (1 - dn) / (1 - dropOff); return - 0.5*gr*t*t + yyy*t; else return 0 end end local function ball( iResolution : Vector2 , col : Vector3 , pp : Vector2 , p : Vector2 , r : number , pal : number ) : Vector3 local ro = Vector3.new(0,0,10) local difDir = Vector3.new(1, 1.5, 2).Unit local speDir = Vector3.new(1, 2, 1).Unit local p3 = Vector3.new(pp, 0) local rd = (p3-ro).Unit local bcol = Vector3.one*0.5+0.5*g.sin_v3(0.5*Vector3.new(0, 1, 2)+Vector3.one*TAU*pal) local aa = g.sqrt(8)/iResolution.Y local z2 = r*r-p:Dot(p) if z2 > 0 then local z = g.sqrt(z2) local cp = Vector3.new(p.X, p.Y, z) local cn = cp.Unit local cr = g.reflect(rd, cn) local cd = g.max(difDir:Dot(cn), 0.0) local cs = 1.008-cr:Dot(speDir) local ccol = g.mix(0.1, 1,cd*cd)*bcol+g.sqrt_v3(bcol)*(1e-2/cs) local d = p.Magnitude-r col = g.mix_v3(col, ccol, g.smoothstep(0, -aa, d)) end return col end local function effect( iResolution : Vector2 , iTime : number , p : Vector2 ) : Vector3 p += Vector2.new(0,.5); local sy = g.sign(p.Y); p = Vector2.new(p.X, g.abs(p.Y)); if sy < 0 then p *= Vector2.new(1,1.5); end local col = Vector3.zero; local aa = g.sqrt(4)/iResolution.Y; for i = 0, LAYERS do local h0 = hash(i+123.4); local h1 = g.fract(8667.0*h0); local h2 = g.fract(8707.0*h0); local h3 = g.fract(8887.0*h0); local tf = g.mix(.5, 1.5, h3); local it = tf*iTime; local cw = g.mix(0.25, 0.75, h0*h0)*SCALE; local per = g.mix(0.75, 1.5, h1*h1)*cw; local p0 = p; local nt = g.floor(it/per); p0 -= Vector2.new(cw*(it-nt*per)/per, 0); local n0, p0x = mod1(p0.X, cw) n0 -= nt; p0 = Vector2.new(p0x, p0.Y) if n0 > -7-i*3 then continue end local ct = it+n0*per; local ch0 = hash(h0+n0); local ch1 = g.fract(8667.0*ch0); local ch2 = g.fract(8707.0*ch0); local ch3 = g.fract(8887.0*ch0); local ch4 = g.fract(9011.0*ch0); local radii = cw*g.mix(.25, .5, ch0*ch0); local dy = g.mix(3., 2., ch3); local bf = g.mix(.6, .9, ch2); local b = bounce(ct/tf+ch4, dy, bf); p0 -= Vector2.new(0, b+radii); col = ball(iResolution, col, p, p0, radii, ch1); end if sy < 0 then col *= g.mix_v3(g.sqrt_v3(Vector3.new(.05, .1, .2)), Vector3.new(.05, .1, .2), p.Y); col += .1*Vector3.zAxis*g.max(p.Y*p.Y, 0); end col = g.sqrt_v3(col); return col; end -- // Fragment shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 ) local p : Vector2 = (-iResolution+2*fragCoords)/iResolution.Y local col : Vector3 = effect(iResolution, iTime, p); return g.v3_rgb(col) end, }
1,541
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/GregsSecret.luau
--[=[ GregsSecret Shader by @GregRostami found on his literal user description Ported to Luau — ran by my engine — `RbxShader`. ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec2 = Vector2.new local vec3 = Vector3.new -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2, iDate : {number} ) fragColor *= 0; local fa : number = 0; -- // frag alpha local b : Vector3 = Vector3.zero; while (b.X^b.Y^b.Z) % 99 > b.Z - 5 do -- // Update b and fragColor fa += 0.1; fragColor += Vector3.one * 0.1; b = vec3( iTime * vec2(1, 4) + 5 * (fragCoords / iResolution.Y - 0.7) * fa, fragColor.X, fragColor.Y ); end return g.c3_rgba(fragColor/74, fa/74); end }
339
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/MicroRayMarcher.luau
--[=[ MicroRayMarcher Shader by @iq on https://www.shadertoy.com/view/DlBcz1 Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec3 = Vector3.new local vec2 = Vector2.new -- // The MIT License -- // Copyright © 2023 Inigo Quilez -- // https://www.youtube.com/c/InigoQuilez -- // https://iquilezles.org/ -- // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- // A raymarching shader using no more than the two input variables -- // Original was 161 chars long. -1 by SnoopethDuckDuck. -4 chars by Xor. local FOV = .7; local NOISINESS = .01; local CONECTEDNESS = 4; local BRIGHTNESS = .1; -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) -- Set up camera local f = fragCoords / iResolution.Y; fragColor = vec3(f.X, f.Y, 1) - Vector3.one * FOV; while fragCoords.X > 0 do fragCoords = vec2(fragCoords.X - 1, fragCoords.Y); -- March forward fragColor *= .9 + .1 * g.cos_v3(.7 * fragColor.X * Vector3.one + vec3(fragColor.Z+iTime, fragColor.X, fragColor.Y)).Magnitude + NOISINESS * g.cos(CONECTEDNESS*fragColor.Y); end -- Final color calculation fragColor = (fragColor + Vector3.one * fragColor.Z) * BRIGHTNESS; return g.v3_rgb(fragColor); end }
672
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/NaiveRaycast.luau
--[=[ NaiveRaycast Pixelizes the game environment by naively raycasting. NOTE: - there is something very wrong with how I calculate material reflectance ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local Camera = workspace.CurrentCamera -- // #defines local SKY_COLOR = Color3.fromRGB(117, 202, 255) local ZOOM = 6 local CANVAS_SIZE = Vector2.new(180, 120) * ZOOM local Offset = (Camera.ViewportSize - CANVAS_SIZE) / 2 -- // Make screen size dynamically change Camera:GetPropertyChangedSignal('ViewportSize'):Connect( function() Offset = (Camera.ViewportSize - CANVAS_SIZE) / 2 end) -- // Fragment shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 , OriginOffset = Vector2.zero , CountDirection = Vector2.one }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 ) local Raycast = Camera:ScreenPointToRay( Offset.X + fragCoords.X * ZOOM , Offset.Y + fragCoords.Y * ZOOM ) local RaycastResult = workspace:Raycast( Raycast.Origin, Raycast.Direction * 500 ) if RaycastResult then if RaycastResult.Instance:IsA('Terrain') then fragColor = workspace.Terrain:GetMaterialColor( RaycastResult.Material ) else fragColor = RaycastResult.Instance.Color if RaycastResult.Material == Enum.Material.Glass or RaycastResult.Material == Enum.Material.Metal then local refColor = nil local Reflectance = RaycastResult.Instance.Reflectance local Direction = g.reflect(RaycastResult.Position, RaycastResult.Normal) local ReflectanceResult = workspace:Raycast(RaycastResult.Position, Direction * 500) if ReflectanceResult then if ReflectanceResult.Instance:IsA('Terrain') then refColor = workspace.Terrain:GetMaterialColor( ReflectanceResult.Material ) else refColor = ReflectanceResult.Instance.Color end else refColor = SKY_COLOR end -- /* Match reflectance property. */ fragColor = Color3.new(g.c3(fragColor)):Lerp( refColor, Reflectance ) end end -- /* Shadowing */ fragColor = fragColor:Lerp( Color3.fromRGB(33, 33, 33), 1 - ((RaycastResult.Normal.Y + 1) / 2) ) -- /* Motion blur */ else fragColor = SKY_COLOR end return g.c3_rgb(fragColor) end, }
661
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/Plasma.luau
--[=[ Plasma Shader by @Xor on https://www.shadertoy.com/view/WfS3Dd Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec3 = Vector3.new local vec2 = Vector2.new local uvec3 = Vector3.one local uvec2 = Vector2.one local abs = math.abs local function tanh_v3(v: Vector3): Vector3 return vec3(math.tanh(v.X), math.tanh(v.Y), math.tanh(v.Z)) end --[[ /* "Plasma" by @XorDev X Post: x.com/XorDev/status/1894123951401378051 */ ]] -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) local O = Vector3.zero local I = fragCoords -- //Resolution for scaling local r = iResolution -- //Centered, ratio corrected, coordinates local p = (I+I-r) / r.Y -- //Z depth local z = vec2(0) -- //Iterator (x=0) local i = vec2(0) -- //Fluid coordinates z += uvec2*4 local f = p*(z-uvec2*4*abs(.7-p:Dot(p))); -- //Clear frag color and loop 8 times while i.Y < 8 do i += Vector2.yAxis local s = (g.sin_v2(f)+uvec2) --@temp; not in source code -- //Set color waves and line brightness O += vec3(s.X, s.Y, s.Y) * abs(f.X-f.Y) -- //Add fluid waves f += g.cos_v2(g.yx(f)*i.Y+i+(uvec2*iTime))/i.Y+uvec2*.7; end -- //Tonemap, fade edges and color gradient O = tanh_v3(7.*g.exp_v3(uvec3*(z.X-4.)-p.Y*vec3(-1,1,2))/O); return g.v3_rgb(O); end }
596
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/ShaderArt.luau
--[=[ ShaderArt Shader by @kishimisu on https://www.shadertoy.com/view/mtyGWy Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) --[=[ This animation is the material of my first youtube tutorial about creative coding, which is a video in which I try to introduce programmers to GLSL and to the wonderful world of shaders, while also trying to share my recent passion for this community. Video URL: https://youtu.be/f4s1h2YETNY ]=] -- // https://iquilezles.org/articles/palettes/ local function palette ( t : number ) local a = Vector3.one * 0.5 local b = Vector3.one * 0.5 local c = Vector3.one local d = Vector3.new(0.263, 0.416, 0.557) return a + b*g.cos_v3(6.28318*(c*t+d)) end -- // Fragment shader return { CONFIGURATION = { InterlaceFactor = 2 , DualAxisInterlacing = true , ScreenDivision = 16 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 ) local uv = (fragCoords * 2 - iResolution) / iResolution.Y local uv0 = uv local finalColor = Vector3.zero for i = 0, 3 do uv = g.fract_v2(uv * 1.5) - Vector2.one * 0.5 local d = uv.Magnitude * g.exp(-uv0.Magnitude) local col = palette(uv0.Magnitude + i * 0.4 + iTime * 0.4) d = g.sin(d * 8 + iTime) / 8 d = g.abs(d) d = g.pow(0.01 / d, 1.2) finalColor += col * d end return g.v3_rgb(finalColor) end, }
519
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/ShootingStars.luau
--[=[ Plasma Shader by @Xor on https://www.shadertoy.com/view/ctXGRn Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec3 = Vector3.new local vec2 = Vector2.new local uvec3 = Vector3.one local uvec2 = Vector2.one local cos = math.cos --[[ /* "Shooting Stars" by @XorDev I got hit with inspiration for the concept of shooting stars. This is what I came up with. Tweet: twitter.com/XorDev/status/1604218610737680385 Twigl: t.co/i7nkUWIpD8 <300 chars playlist: shadertoy.com/playlist/fXlGDN */ ]] -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) local I = fragCoords -- //Clear fragcolor local O = Vector3.zero -- //Line dimensions (box) and position relative to line local b, p = vec2(0,.2), Vector2.zero; -- //Rotation matrix local R_b, R_c, R_ad = 0, 0, 0; -- //Iterate 20 times for i = 0.9, 20, 1 do -- //Rotate for each iteration R_b = cos(i+33); R_c = cos(i+11); R_ad = cos(i); -- //Using rotated boxes local v1 = (I/iResolution.Y*i*.1+uvec2*iTime*b) -- @temp; local v2 = g.fract_v2(vec2( (R_c*v1.X)+(R_ad*v1.Y), (R_ad*v1.X)+(R_b*v1.Y) )) - uvec2*.5 -- @temp; p = vec2( (R_c*v2.X)+(R_ad*v2.Y), (R_ad*v2.X)+(R_b*v2.Y) ) -- //Add attenuation local glow = 1e-3/(b:Min((-b):Max(p))-p).Magnitude -- //My favorite color palette O += glow * (g.cos_v3((uvec3*p.Y/.1)+vec3(0,1,2))+uvec3) end return g.v3_rgba(O); end }
644
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/SmallestClock.luau
--[=[ SmallestClock Shader by @GregRostami on https://www.shadertoy.com/view/MsdXzH Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec3 = Vector3.new -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2, iDate : {number} ) -- Define N function as per the GLSL macro local function N( t : number ) : Vector3 fragCoords /= 0.8 return fragCoords.Magnitude < iResolution.Y and g.cos(iDate[4]/t-g.atan2(fragCoords.X, fragCoords.Y)) > 0.998 and vec3(1, 1, 1) or vec3(0, 0, 0); end -- Initialization of R and adjustment of u (fragCoords) fragCoords += fragCoords - iResolution; -- Accumulate the result into fragColor (interpreted as o) fragColor = N(1e9 - 12.0) + N(573.0) + N(9.55) + N(6875.0); return g.v3_rgb(fragColor); end }
379
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/Sun.luau
--[=[ Sun Shader by @invivel on https://www.shadertoy.com/view/NlfcW2 Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) iMouse = Vector2.new(iMouse.X, iMouse.Y); local uv : Vector2 = (fragCoords - iResolution) / iResolution.Y; local ms : Vector2 = (iMouse - iResolution) / iResolution.Y; local sun : number = 0.05 / (ms - uv).Magnitude + 0.02; return sun / 0.477, sun + 0.5, sun + 0.8 end }
265
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/UnknownPleasures.luau
--[=[ UnknownPleasures Shader by @smiarx on https://www.shadertoy.com/view/4sVyWR Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec2 = Vector2.new -- // #defines local LINEWIDTH = 3.2; local H = 35; local WAVEHEIGHT = 6.6; local WIDTH = 0.6; local CLOSENESS = 45; local OCTAVES = 3; -- // aux functions local function random(x : number) : number return g.fract(g.sin(x)*43758.5453123); end local function noise(x : number) : number local i : number = g.floor(x); local f : number = g.fract(x); local a : number = random(i); local b : number = random(i+1); local u : number = f * f * (3 - 2 * f); return g.mix(a, b, u); end local function fbm(x : number) : number local value : number = 0; local amplitude : number = .5; local frequency : number = 0; for i = 1, OCTAVES, 1 do value += amplitude * noise(x); x *= 2; amplitude *= .7; end return value; end -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2, iDate : {number} ) local st : Vector2 = (2*(iResolution - fragCoords) - iResolution) / iResolution.Y; st = vec2(st.X, st.Y * CLOSENESS); local linewidth : number = CLOSENESS * LINEWIDTH / iResolution.Y; local val : number = 0; if g.abs(st.X) < WIDTH then local env : number = g.pow(g.cos(st.X/WIDTH*3.14159/2), 4.9); local i : number = g.floor(st.Y); for n = g.max(-H, i-6), g.min(H, i), 1 do local f : number = st.Y - n; local y : number = f - 0.5; y -= WAVEHEIGHT * g.pow(fbm(st.X*10.504 +n*432.1 + 0.5*iTime), 3) * env + (fbm(st.X*25.+n*1292.21)-0.32)*2 * 0.15; local grid : number = g.abs(y); val += (1-g.smoothstep(0, linewidth, grid)); -- // val = grid; if y < 0 then break end; end end return val, val, val, val; end }
723
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/VoxelShader.luau
--[=[ VoxelShader Shader by @Xor on https://www.shadertoy.com/view/fstSRH Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local function map ( v : Vector3 , iTime : number ) return math.sqrt( (v.X % 18 - 9)^2 + (v.Y % 18 - 9)^2 + (v.Z % 18 - 9)^2 ) - 9.5 + g.sin( v.Z * 0.3 - iTime * 0.1 ) end -- // Fragment shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 16 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 ) local cam = Vector3.new( g.sin(iTime*0.2+iResolution.X), g.sin(iTime*0.2+iResolution.Y), iTime ) local pos = cam local ray = Vector3.new( fragCoords.X*2-iResolution.X, fragCoords.Y*2-iResolution.Y, iResolution.Y ).Unit local cell = Vector3.zero -- // Step up to 100 voxels. for i = 1, 100 do -- // Axis distance to nearest cell (with a small bias). local dist = g.fract_v3(-pos * ray:Sign()) + Vector3.one * 1e-4 -- // Alternative version (produces artifacts after a while) -- // vec3 dist = 1-g.fract_v3(pos * sign(ray)), -- // Raytraced distance to each axis. local leng = dist / ray:Abs() -- // Nearest axis' raytrace distance (as a vec3). local near = g.min( leng.X, g.min(leng.Y, leng.Z)) -- // Step to the nearest voxel cell. pos += ray * near -- // Get the cell position (center of the voxel). cell = pos:Ceil() - Vector3.one * 0.5; -- // Stop if we hit a voxel. if map(cell, iTime) < 0 then break end end -- // Rainbow color based off the voxel cell position. local color = g.sin_v3(Vector3.new(0,2,4) + Vector3.one * cell.Z) * 0.5 + (Vector3.one * 0.5) -- // Square for gamma encoding. color *= color; -- // Compute cheap ambient occlusion from the SDF. local ao = g.smoothstep(-1, 1, map(pos, iTime)) -- // Fade out to black ug.sing the distance. local fog = g.min(1, g.exp(1 - (pos-cam).Magnitude/8)) -- // Output final color with ao and fog (sqrt for gamma correction). fragColor = g.sqrt_v3(color * ao * fog) return g.v3_rgb(fragColor) end, }
764
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/ZippyZaps.luau
--[=[ ZippyZaps Shader by @SnoopethDuckDuck on https://www.shadertoy.com/view/XXyGzh Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec3 = Vector3.new local vec2 = Vector2.new local uvec3 = Vector3.one local uvec2 = Vector2.one local pow = math.pow local cos = math.cos local function tanh_v2(v: Vector2): Vector2 return vec2(math.tanh(v.X), math.tanh(v.Y)) end -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 3 , ScreenDivision = 4 , IsBlurred = true }; -- // Image buffer -- // -13 thanks to Nguyen2007 ⚡ mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2, iDate : {number} ) local v = iResolution; local u = fragCoords; u = .2*(u+u-v)/v.Y; local o = vec3(1, 2, 3); local z = o; local a = .5; local t = iTime; local i = 0.0; while true do i += 1 if i >= 19 then break end o += (uvec3 + g.cos_v3(z+uvec3*t)) / ( (1+i*v:Dot(v)) * g.sin_v2(1.5*u/(.5-u:Dot(u)) - 9*g.yx(u) + uvec2*t) ).Magnitude t += 1 a += .03 v = g.cos_v2(uvec2*t - 7*u*pow(a, i)) - 5*u local r1 = i + 0.02 * t local r2 = cos(r1) u = vec2( (r2 * u.X) + (cos(r1 - 11) * u.Y), (cos(r1 - 33) * u.X) + (r2 * u.Y) ) -- use stanh here if shader has black artifacts -- vvvv u += tanh_v2(40 * u:Dot(u) * g.cos_v2(1e2*g.yx(u)+uvec2*t)) / 2e2 + .2 * a * u + uvec2*(cos(4/math.exp(o:Dot(o)/1e2) + t) / 3e2) end o = 25.6 / (o:Min(uvec3*13) + uvec3*164 / o) - uvec3*u:Dot(u) / 250; fragColor = o return g.v3_rgb(fragColor); end }
713
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/expensive/BismuthCrystals.luau
--[=[ BismuthCrystals Shader by @jarble on https://www.shadertoy.com/view/NdsXzl Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec2 = Vector2.new local vec3 = Vector3.new -- // #defines local ITERS = 12 -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) fragColor = Vector3.zero; local col : Vector3 = Vector3.zero; local colPrev : Vector3 = Vector3.zero; local t : number = 0; local uv : Vector2 = (fragCoords*10 - iResolution) / iResolution.Y / 15; uv = vec2(uv.X, uv.Y + iTime / 25); for c = 1, ITERS do local scale : number = 2.1; local scale1 : number = 1.13; local s1 : number = scale1*scale; colPrev = col; for i = 1, ITERS do uv = g.fract_v2((-uv) - vec2( uv.X/scale - uv.Y/scale1, uv.Y/scale - uv.X/scale1 ) / scale) / scale1; uv = vec2(uv.X * scale1, uv.Y); uv = g.fract_v2(g.yx(-uv)/s1)*s1; uv = vec2(uv.X, uv.Y / -scale1); -- // scale1 += (uv.X*(.0005*g.fract(uv.X+iTime/4))); end col = vec3(col.X, g.abs(g.fract(uv.Y)-g.fract(uv.X)), col.Z); --// g.fract((uv.Y)-(uv.X)); col = (col+g.yzx(colPrev)) / 2.125; end return g.v3_rgb(col*3); end }
553
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/expensive/Clouds.luau
--[=[ Clouds Shader by @zxxuan1001 on https://www.shadertoy.com/view/tlB3zK Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) local vec2 = Vector2.new local vec3 = Vector3.new -- // noise function from iq: https://www.shadertoy.com/view/Msf3WH function hash( p : Vector2 ) : Vector2 p = vec2( p:Dot(vec2(127.1,311.7)), p:Dot(vec2(269.5,183.3)) ); return Vector2.one * -1.0 + 2.0*g.fract_v2(g.sin_v2(p)*43758.5453123); end function noise( inv : { p : Vector2 } ) : number local K1 = 0.366025404; -- // (sqrt(3)-1)/2; local K2 = 0.211324865; -- // (3-sqrt(3))/6; local i : Vector2 = ( inv.p + Vector2.one * (inv.p.X+inv.p.Y)*K1 ):Floor(); local a : Vector2 = inv.p - i + Vector2.one * (i.X+i.Y)*K2; local m : number = g.step(a.Y,a.X); local o : Vector2 = vec2(m,1.0-m); local b : Vector2 = a - o + Vector2.one * K2; local c : Vector2 = a - Vector2.one + Vector2.one * 2.0*K2; local h : Vector3 = (Vector3.one * 0.5 - vec3(a:Dot(a), b:Dot(b), c:Dot(c))):Max(Vector3.zero); -- might cause problems local n : Vector3 = h*h*h*h*vec3( a:Dot(hash(i)), b:Dot(hash(i+o)), c:Dot(hash(i+Vector2.one))); return n:Dot(vec3(70.0)); end local function applyMatrix( p : Vector2 ) : Vector2 return vec2( 1.6 * p.X + -1.2 * p.X, 1.2 * p.Y + 1.6 * p.Y ); end function fbm4( p : Vector2 ) : number local amp : number = 0.5; local h : number = 0; local inv = {p = p}; for i = 1, 4 do local n : number = noise(inv); h += amp * n; amp *= 0.5; inv.p = applyMatrix(inv.p); end return 0.5 + 0.5*h; end -- // Fragment shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) iMouse = vec2(iMouse.X, iMouse.Y); -- // Normalized pixel coordinates (from 0 to 1) local uv : Vector2 = fragCoords/iResolution; uv = vec2( (uv.X - 0.5) * iResolution.X/iResolution.Y, uv.Y - 0.5 ); local mo : Vector2 = iMouse/iResolution; local sky : Vector3 = vec3(0.5, 0.7, 0.8); local col : Vector3 = vec3(0.0); -- // speed local v : number = 0.001; -- // layer1 local cloudCol : Vector3 = Vector3.one; uv += mo * 10; local uv10 : Vector2 = uv * 10; local scale : Vector2 = uv * 2; local turbulence : Vector2 = 0.008 * vec2(noise({p=uv10}), noise({p=uv10})); scale += turbulence; local n1 : number = fbm4(vec2(scale.X - 20 * g.sin(iTime * v * 2), scale.Y - 50 * g.sin(iTime * v))); col = g.mix_v3( sky, cloudCol, g.smoothstep(0.5, 0.8, n1)); -- // layer2 scale = uv * 0.5; turbulence = 0.05 * vec2(noise({p=vec2(uv.X * 2.0, uv.Y * 2.1)}), noise({p=vec2(uv.X * 1.5, uv.Y * 1.2)})); scale += turbulence; local n2 : number = fbm4(scale + Vector2.one * 20.0 * g.sin(iTime * v)); col = g.mix_v3( col, cloudCol, g.smoothstep(0.2, 0.9, n2)); col = col:Min(Vector3.one); -- // Output to screen return g.v3_rgb(col) end }
1,214
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/expensive/ProceduralOcean.luau
--[=[ Procedural3DOcean Shader by @jarble and @afl_ext on https://www.shadertoy.com/view/4cyXWw Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) [ ⚠ NOT WORKING AS INTENDED ] ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) -- // #defines -- // Use your mouse to move the camera around! Press the Left Mouse Button on the image to look around! local DRAG_MULT = 0.38 -- // changes how much waves pull on the water local WATER_DEPTH = 1.0 -- // how deep is the water local CAMERA_HEIGHT = 1.5 -- // how high the camera should be local ITERATIONS_RAYMARCH = 12 -- // waves iterations of raymarching local ITERATIONS_NORMAL = 37 -- // waves iterations when calculating normals local function xz( v : Vector3 ) return Vector2.new(v.X, v.Z) end local function clamp_v3( v : Vector3 , min : number , max : number ) : Vector3 return Vector3.new( g.clamp(v.X, min, max), g.clamp(v.Y, min, max), g.clamp(v.Z, min, max) ) end -- // Helper function for multiplying two matrices local function matmul( A : {{number}} , B : {{number}} ) : {{number}} local result = {} for i = 1, 3 do result[i] = {} for j = 1, 3 do result[i][j] = 0 for k = 1, 3 do result[i][j] = result[i][j] + A[i][k] * B[k][j] end end end table.clear(A) table.clear(B) return result end -- // Helper function for multiplying a matrix and a vector local function mat_v3_mul( m : {{number}} , v : Vector3 ) : Vector3 local result = Vector3.new( m[1][1] * v.X + m[2][1] * v.X + m[3][1] * v.X, m[1][2] * v.Y + m[2][2] * v.Y + m[3][2] * v.Y, m[1][3] * v.Z + m[2][3] * v.Z + m[3][3] * v.Z ) table.clear(m) return result end -- // Calculates wave value and its derivative, -- // for the wave direction, position in space, wave frequency and time local function wavedx ( position : Vector2, direction : Vector2, speed : number , frequency : number, timeshift : number) : Vector2 local x = direction:Dot(position) * frequency + timeshift * speed; local wave = g.exp(g.sin(x) - 1); local dx = wave * g.cos(x); return Vector2.new(wave, -dx); end -- // Calculates waves by summing octaves of various waves with various parameters local function getWaves( iTime : number , position : Vector2 , iterations : number ) : number local iter = 0.0; -- // this will help generating well distributed wave directions local phase = 6.0; -- // frequency of the wave, this will change every iteration local speed = 2.0; -- // time multiplier for the wave, this will change every iteration local weight = 1.0; -- // weight in final sum for the wave, this will change every iteration local sumOfValues = 0.0; -- // will store final sum of values local sumOfWeights = 0.0; -- // will store final sum of weights for i = 0, iterations-1 do -- // generate some wave direction that looks kind of random local p : Vector2 = Vector2.new(g.sin(iter), g.cos(iter)); -- // calculate wave data local res : Vector2 = wavedx(position, p, speed, phase, iTime); -- // shift position around according to wave drag and derivative of the wave position += p * res.Y * weight * DRAG_MULT; -- // add the results to sums sumOfValues += res.X * weight; sumOfWeights += weight; -- // modify next octave ; weight = g.mix(weight, 0, 0.2); phase *= 1.18; speed *= 1.07; -- // add some kind of random value to make next wave look random too iter += 12.0; end -- // calculate and return return sumOfValues / sumOfWeights; end --// Raymarches the ray from top water layer boundary to low water layer boundary function rayMarchWater ( iTime : number , camera : Vector3, start : Vector3, ending : Vector3, depth : number ) : number local pos : Vector3 = start; local h = 0; local hupper = depth; local hlower = 0; local zer = Vector2.zero; local dir = (ending - start).Unit; local eps = 0.01; for i = 0, 317 do h = getWaves(iTime, xz(pos) * 0.1, ITERATIONS_RAYMARCH) * depth - depth; local dist_pos = (pos - camera).Magnitude; if h + eps*dist_pos > pos.Y then return dist_pos; end pos += dir * (pos.Y - h); -- // eps *= 1.01; end return -1; end -- // Calculate normal at point by calculating the height at the pos and 2 additional points very close to pos function getNormal( iTime : number , pos : Vector2 , e : number , depth : number ) : Vector3 local ex = Vector2.new(e, 0); local H = getWaves(iTime, pos, ITERATIONS_NORMAL) * depth; local a = Vector3.new(pos.X, H, pos.Y); return (a - Vector3.new(pos.X - e, getWaves(iTime, pos - ex, ITERATIONS_NORMAL) * depth, pos.Y)):Cross( a - Vector3.new(pos.X, getWaves(iTime, pos + g.yx(ex), ITERATIONS_NORMAL) * depth, pos.Y + e) ).Unit; end -- // Helper function generating a rotation matrix around the axis by the angle function rotmat( axis : Vector3, angle : number ) : {{number}} local s = g.sin(angle); local c = g.cos(angle); local oc = 1.0 - c; return { {oc * axis.X * axis.X + c, oc * axis.X * axis.Y - axis.Z * s, oc * axis.Z * axis.X + axis.Y * s}, {oc * axis.X * axis.Y + axis.Z * s, oc * axis.Y * axis.Y + c, oc * axis.Y * axis.Z - axis.X * s}, {oc * axis.Z * axis.X - axis.Y * s, oc * axis.Y * axis.Z + axis.X * s, oc * axis.Z * axis.Z + c} } end -- // Helper function that generates camera ray based on UV and mouse function getRay ( iResolution : Vector2, iMouse : Vector2, uv : Vector2 ) : Vector3 uv = (uv * 2 - Vector2.one) * Vector2.new(iResolution.X / iResolution.Y, 1); -- // for fisheye, uncomment following line and comment the next one -- // local proj : Vector3 = (Vector3.new(uv.X, uv.Y, 1) + (Vector3.new(uv.X, uv.Y, -1) * uv.Magnitude^2 * 0.05)).Unit; local proj : Vector3 = Vector3.new(uv.X, uv.Y, 1.5).Unit; if iResolution.X < 400 then return proj end return mat_v3_mul( matmul( rotmat(-1 * Vector3.yAxis, 3 * (iMouse.X * 2 - 1)), rotmat(Vector3.xAxis, 1.5 * (iMouse.Y * 2 - 1)) ), proj ); end -- // Ray-Plane intersection checker function intersectPlane ( origin : Vector3 , direction : Vector3 , point : Vector3 , normal : Vector3 ) : number return g.clamp((point - origin):Dot(normal) / direction:Dot(normal), -1, 9991999); end -- // Some very barebones but fast atmosphere approximation function extra_cheap_amosphere( raydir : Vector3 , sundir : Vector3 ) : Vector3 local special_trick = 1.0 / (raydir.Y * 1.0 + 0.1); local special_trick2 = 1.0 / (sundir.Y * 11.0 + 1.0); local raysundt = g.abs(sundir:Dot(raydir))^2; local sundt = g.max(0.0, sundir:Dot(raydir))^8; local mymie = sundt * special_trick * 0.2; local suncolor = g.mix_v3(Vector3.one, Vector3.new(0.7544642686843872, 0.4196428656578064, 0), special_trick2); local bluesky = Vector3.new(0.2455357164144516, 0.5803571343421936, 1) * suncolor; local bluesky2 = Vector3.zero:Max(bluesky - Vector3.new(5.5, 13, 22.4) * 0.002 * (special_trick + -6 * sundir.Y * sundir.Y)); bluesky2 *= special_trick * (0.24 + raysundt * 0.24); return bluesky2 * (1.0 + 1.0 * 1.0 - raydir.Y^3) + mymie * suncolor; end -- // Get atmosphere color for given direction function getAtmosphere( ray : Vector3 ) : Vector3 return extra_cheap_amosphere(ray, Vector3.one.Unit) * 0.5; end -- // Get sun color for given direction function getSun ( ray : Vector3 ) : number return g.max(0, ray:Dot(Vector3.one.Unit))^528 * 110; end -- // Great tonemapping function from my other shader: https://www.shadertoy.com/view/XsGfWV function aces_tonemap( color : Vector3 ) : Vector3 local m1 = { {0.59719, 0.07600, 0.02840}, {0.35458, 0.90834, 0.13383}, {0.04823, 0.01566, 0.83777} }; local m2 = { {1.60475, -0.10208, -0.00327}, {-0.53108, 1.10813, -0.07276}, {-0.07367, -0.00605, 1.07602} }; local v = mat_v3_mul(m1, color); local c = (v * (v + 0.0245786) - 0.000090537) / (v * (0.983729 * v + 0.4329510) + 0.238081); return g.pow_v3(clamp_v3(mat_v3_mul(m2, c), 0, 1), Vector3.one * 1 / 2.2); end -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) local uv = fragCoords / iResolution; local waterdepth = 2.1; local wfloor = Vector3.yAxis * -waterdepth; local wceil = Vector3.zero; local orig = Vector3.yAxis * 2; local ray = getRay(iResolution, iMouse, uv); local hihit = intersectPlane(orig, ray, wceil, Vector3.yAxis); if ray.Y >- -0.01 then local C = getAtmosphere(ray) * 2 + getSun(ray); -- // tonemapping C = aces_tonemap(C); return g.v3_rgb(C); end local lohit = intersectPlane(orig, ray, wfloor, Vector3.yAxis); local hipos = orig + ray * hihit; local lopos = orig + ray * lohit; local dist = rayMarchWater(iTime, orig, hipos, lopos, waterdepth); local pos = orig + ray * dist; local N = getNormal(iTime, xz(pos), 0.001, waterdepth); N = g.mix(Vector3.yAxis, N, 1 / (dist * dist * 0.01 + 1)); local R = g.reflect(ray, N); local fresnel = 0.04 + 0.96 * (1 - g.max(0, (-N):Dot(ray)))^5; local C = fresnel * getAtmosphere(R) * (2 + fresnel * getSun(R)); -- // tonemapping return g.v3_rgb(aces_tonemap(C)); end, }
3,083
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/expensive/SimpleOceanWaves.luau
--[=[ SimpleOceanWaves Shader by @jarble on https://www.shadertoy.com/view/ftS3zh Ported to Luau — ran by my engine — `RbxShader`. ( Original comments are preserved. ) [ ⚠ NOT WORKING AS INTENDED ] ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) -- // `in` value system -- * designed to consume less memory by reusing old `in`s (which are just tables) local in_bookkeep : {[number] : boolean} -- # maps a key to it's availability local in_map : {[number] : {}} = {} -- # maps a key to an `in` value -- # looks for any previous `in`s that can be reused and returns them local function alloc_in() local free_in : {} = nil -- # look for free unallocated `in`s for key : number, availability : boolean in in_bookkeep do if not availability then continue end free_in = in_map[key] in_bookkeep[key] = false end -- # make a new entry if everything before has been occupied if free_in == nil then free_in = {} local key = #in_map+1 in_map[key] = free_in in_bookkeep[key] = false end return free_in end -- # frees up the data stored in the `in`s to be garbage collected local function freeup_ins() for key : number, availability : boolean in in_bookkeep do in_bookkeep[key] = false table.clear(in_map[key]) end end -- // #defines local SC = 250 local OCTAVES = 4 local ITIME = 0 -- // aux functions local function xyy( v : Vector3 ) : Vector3 return Vector3.new( v.X, v.Y, v.Y ) end local function yyx( v : Vector3 ) : Vector3 return Vector3.new( v.Y, v.Y, v.X ) end type Matrix3 = {Vector3} local function mul_mat3vec3( m : Matrix3 , v : Vector3 ) : Vector3 return Vector3.new( m[1].X * v.X + m[2].X * v.X + m[3].X * v.X, m[1].Y * v.Y + m[2].Y * v.Y + m[3].Y * v.Y, m[1].Z * v.Z + m[2].Z * v.Z + m[3].Z * v.Z ) end -- // program functions -- # uv is an in-value function noise( uv : Vector2 ) : number return g.sin(uv.X - ITIME/2); end -- # uv is an in-value function fbm( uv : Vector2 ) : number local value = 0; local amplitude = 1; local freq = 0.8; for i = 0, OCTAVES-1 do -- // value += noise(uv * freq) * amplitude; -- // uv = Vector2.new(uv.X - ITIME/2, uv.Y); -- // From Dave_Hoskins https://www.shadertoy.com/user/Dave_Hoskins value += (.25 - g.abs(noise(uv * freq)-.3) * amplitude); amplitude *= .37; freq *= 3.+1. / 3.; uv += g.yx(uv) / 10.0; -- // uv = g.yx(uv); end return value; end function f ( p : Vector3 ) : number return fbm(g.xz(p)); end function getNormal ( p : Vector3 , t : number ) : Vector3 local eps = Vector3.xAxis * .001 * t; return Vector3.new( f(p - xyy(eps)) - f(p + xyy(eps)), 2 * eps.X, f(p - yyx(eps)) - f(p + yyx(eps)) ).Unit; end function rayMarching ( ro : Vector3 , rd : Vector3 , tMin : number , tMax : number ) : number local t = tMin; for _ = 1, 300 do local pos = ro + t * rd; local h = pos.Y - f(pos); if g.abs(h) < (0.0015 * t) or t > tMax then break end t += 0.4 * h; end return t; end function lighting ( p : Vector3 , normal : Vector3 , L : Vector3 , V : Vector3 ) : Vector3 local sunColor = Vector3.new(1, .956, .839); local albedo = 1; local diff = Vector3.one * g.max(normal:Dot(L) * albedo, 0); local refl = g.reflect(L, normal).Unit; local spec = g.max(refl:Dot(-(V.Unit)), 0); spec ^= 18; spec = g.clamp(spec, 0, 1); local sky = g.max(0, Vector3.yAxis:Dot(normal)); -- // local amb = 0.5 * g.smoothstep(0.0, 2.0, p.Y); local col = diff * sunColor; col += spec * sunColor; col += sky * Vector3.new(0, 0.6, 1) * .1; -- // col += amb * .2; return col; end function lookAt( origin : Vector3 , target : Vector3 , roll : number ) : Matrix3 local rr = Vector3.new(g.sin(roll), g.cos(roll), 0); local ww = (target - origin).Unit; local uu = ww:Cross(rr); local vv = uu:Cross(ww); return {uu, vv, ww}; end function camerapath ( t : number ) : Vector3 return Vector3.new( -13.0 + 3.5 * g.cos(t), 3.3, -1.1 + 2.4 * g.cos(2.4 * t + 2.0) ) end -- // Pixel shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) freeup_ins(); ITIME = iTime; local uv = (fragCoords - iResolution * 0.5) / iResolution.Y; local lightDir = Vector3.new(-.8, .15, -.3).Unit; local camStep = Vector3.new(lightDir.X, 0, lightDir.Z); local camPos = Vector3.new(8, 2, 5) + camStep; local camTarget = Vector3.new(1, 1, 4) + camStep; local mat = lookAt(camPos, camTarget, 0); local ro = camPos; local rd = mul_mat3vec3(mat, Vector3.new(uv.X, uv.Y, 1)).Unit; local tMin = .1; local tMax = 20; local t = rayMarching(ro, rd, tMin, tMax); local col = Vector3.zero; if t > tMax then -- // from iq's shader, https://www.shadertoy.com/view/MdX3Rr local sundot = g.clamp(rd:Dot(lightDir), 0.0, 1.0); col = Vector3.new(.3, .5, .85) - Vector3.one * rd.Y*rd.Y*0.5; col = g.mix_v3(col, 0.85 * Vector3.new(.7, .75, .85), (1 - g.max(rd.Y, 0))^4); -- // sun col += 0.25 * Vector3.new(1, .7, .4) * sundot^5; col += 0.25 * Vector3.new(1, .8, .6) * sundot^64; col += 0.2 * Vector3.new(1, .8, .6) * sundot^512; -- // clouds local sc = g.xz(ro) + g.xz(rd) * (SC*1000-ro.Y) / rd.Y; col = g.mix_v3(col, Vector3.new(1, .95, 1), 0.5 * g.smoothstep(0.5, 0.8, fbm(0.0005*sc/SC))); -- // horizon col = g.mix_v3(col, 0.68 * Vector3.new(.4, .65, 1), (1 - g.max(rd.Y, 0))^16); else local p = ro + rd * t; local normal = getNormal(p, t); local viewDir = (ro - p).Unit; -- // lighting terrain col = lighting(p, normal, lightDir, viewDir); -- // fog local fo = 1 - g.exp((30 * t / SC)^1.5); local fco = 0.65 * Vector3.new(.4, .65, 1); col = g.mix_v3(col, fco, fo); end -- // Gamma correction col = g.pow_v3(g.clamp_v3(col, 0, 1), Vector3.one * .45); return g.v3_rgb(col) end }
2,175
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/shaders/expensive/StarNest.luau
--[=[ StarNest Shader by @Kali on https://www.shadertoy.com/view/XlfGRj Ported to Luau — ran by my engine — `RbxShader`. NOTE: - very resource intensive, our goal is to be able to render this efficiently without changing this programs code ]=] --!native local g = require(game.ReplicatedStorage.RbxShader.GraphicsMathLib) -- // #define local iterations = 17 local formuparam = 0.53 local volsteps = 20 local stepsize = 0.1 local zoom = 0.800 local tile = 0.850 local speed = 0.010 local brightness = 0.0015 local darkmatter = 0.300 local distfading = 0.730 local saturation = 0.850 local Matrix2 = {} function Matrix2.new( a : number, b : number , c : number , d : number ) return {{a, b}, {c, d}} end -- // Fragment shader return { CONFIGURATION = { InterlaceFactor = 2 , ScreenDivision = 4 }; -- // Image buffer mainImage = function ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : Vector2 ) -- // get coords and direction local uv = Vector2.new( fragCoords.X/iResolution.X - .5, fragCoords.Y/iResolution.Y - .5 * iResolution.Y/iResolution.X ) * zoom local dir = Vector3.new(uv.X, uv.Y, 1) local time = iTime * speed + .25 -- // mouse rotation local a1 = 0.5 + iMouse.X / iResolution.X * 2 local a2 = 0.8 + iMouse.Y / iResolution.Y * 2 local rot1 = Matrix2.new(g.cos(a1), g.sin(a1), -g.sin(a1), g.cos(a1)) local rot2 = Matrix2.new(g.cos(a2), g.sin(a2), -g.sin(a2), g.cos(a2)) dir = Vector3.new(dir.X * rot1[1][1] + dir.Z * rot1[1][2], dir.Y, dir.X * rot1[2][1] + dir.Z * rot1[2][2]) dir = Vector3.new(dir.X, dir.Y * rot2[1][1] + dir.Z * rot2[1][2], dir.X * rot2[2][1] + dir.Y * rot2[2][2]) local from = Vector3.new(1, 0.5, 0.5) from += Vector3.new(time * 2, time, -2) from = Vector3.new(from.X * rot1[1][1] + from.Z * rot1[1][2], from.Y, from.X * rot1[2][1] + from.Z * rot1[2][2]) from = Vector3.new(from.X, from.Y * rot2[1][1] + from.Z * rot2[1][2], from.X * rot2[2][1] + from.Y * rot2[2][2]) -- // volumetric rendering local s, fade = 0.1, 1.0 local v = Vector3.zero for r = 1, volsteps do local p = from+s*dir*.5 p = Vector3.one * tile - g.mod_v3(p, Vector3.one * tile * 2) -- // tiling fold local pa, a = 0, 0 for i = 1, iterations do p = p:Abs() / p:Dot(p) - Vector3.one * formuparam -- // the magic formula a += g.abs((p.Magnitude-pa)) -- // absolute sum of average change pa = p.Magnitude end local dm = g.max(0, darkmatter-a*a*0.001) -- // dark matter a *= a*a -- // add contrast if r > 6 then fade *= 1 - dm end -- // dark matter, don't render near -- // v += Vector3.new(dm,dm*.5,0.) v += Vector3.one * fade v += Vector3.new(s, s^2, s^4)*a*brightness*fade -- // coloring based on distance fade *= distfading -- // distance fading s += stepsize end v = g.mix_v3(Vector3.one * v.Magnitude, v, saturation) -- // color adjust return g.v3_rgb(v*.01) end, }
1,099
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/src/Canvas.luau
--[=[ Canvas A simple EditableImage interface that mimics CanvasDraw's API design. Specifically built for RbxShader. NOTE: * RGBA values are normalized (between 0 and 1) ]=] --!native local Asset = game:GetService('AssetService') local Resampler = Enum.ResamplerMode local writeu8 = buffer.writeu8 local readu8 = buffer.readu8 local writeu16 = buffer.writeu16 local readu16 = buffer.readu16 -- * denormalizes a normalized number local uint8 = function(n: number) : number return math.clamp(math.ceil(n * 255), 0, 255) end local Canvas = {} Canvas.__index = Canvas type Parent = GuiObject | Decal | Texture | SurfaceAppearance | MeshPart export type Canvas = typeof(Canvas) & { Resolution: Vector2 , __Easel: ImageLabel , __Canvas: EditableImage , __ImageBuffer: buffer , __VPMBuffer: buffer } function Canvas.new(Parent: Parent, Resolution: Vector2, Blur: boolean?): (Canvas) Blur = Blur or false -- Build the necessary objects local Easel = Instance.new("ImageLabel") Easel.Name = "FastCanvas" Easel.BackgroundTransparency = 1 Easel.ClipsDescendants = true Easel.Size = UDim2.fromScale(1, 1) Easel.Position = UDim2.fromScale(0.5, 0.5) Easel.AnchorPoint = Vector2.new(0.5, 0.5) Easel.ResampleMode = not Blur and Resampler.Pixelated or Resampler.Default Easel.Parent = Parent local AspectRatio = Instance.new("UIAspectRatioConstraint") AspectRatio.AspectRatio = Resolution.X / Resolution.Y AspectRatio.Parent = Easel local InternalCanvas = Asset:CreateEditableImage({ Size = Resolution }) Easel.ImageContent = Content.fromObject(InternalCanvas) -- Build the 'Canvas' object local self = setmetatable({}, Canvas) self.Resolution = Resolution self.__Easel = Easel self.__Canvas = InternalCanvas self.__ImageBuffer = buffer.create(Resolution.X * Resolution.Y * 4) self.__VPMBuffer = buffer.create(Resolution.X * Resolution.Y * 4) -- ^^^ 'VPM' stands for 'virtual pixel mapping' -- * pure coincidence that the size of both buffers are the same return self end function Canvas:__GetIndex(X: number, Y: number): (number) return (Y - 1) * (self.Resolution.X * 4) + (X - 1) * 4 end function Canvas:SetRGBA(X: number, Y: number, R: number, G: number, B: number, A: number): () local Index = self:__GetIndex(X, Y) local ImgBuff = self.__ImageBuffer writeu8(ImgBuff, Index, uint8(R)) writeu8(ImgBuff, Index + 1, uint8(G)) writeu8(ImgBuff, Index + 2, uint8(B)) writeu8(ImgBuff, Index + 3, uint8(A or 1)) return nil end function Canvas:GetRGB(X: number, Y: number): (number, number, number) local Index = self:__GetIndex(X, Y) local ImgBuff = self.__ImageBuffer return readu8(ImgBuff, Index) / 255, readu8(ImgBuff, Index + 1) / 255, readu8(ImgBuff, Index + 2) / 255 end function Canvas:Fill(Color: Color3?, Alpha: number?): () Color = Color or Color3.new(1, 1, 1) Alpha = Alpha or 1 for X = 1, self.Resolution.X do for Y = 1, self.Resolution.Y do self:SetRGBA(X, Y, Color.R, Color.G, Color.B, Alpha) end end end function Canvas:RecalculateVirtualPixelMapping( VirtualOrigin: Vector2 , --> in pixels RelativeOffset: Vector2 , --> in pixels CountDirection: Vector2 --> sign vector ): () VirtualOrigin = VirtualOrigin:Floor() RelativeOffset = RelativeOffset:Floor() CountDirection = CountDirection:Sign() -- CountDirection sanitization if CountDirection.X == 0 then CountDirection += Vector2.xAxis end if CountDirection.Y == 0 then CountDirection += Vector2.yAxis end local VPMBuff = self.__VPMBuffer for X = 1, self.Resolution.X do for Y = 1, self.Resolution.Y do local Index = self:__GetIndex(X, Y) writeu16(VPMBuff, Index, VirtualOrigin.X + CountDirection.X * (X + RelativeOffset.X)) writeu16(VPMBuff, Index + 2, VirtualOrigin.Y + CountDirection.Y * (Y + RelativeOffset.Y)) end end end function Canvas:GetVirtualPosition(X: number, Y: number): (number, number) local Index = self:__GetIndex(X, Y) local VPMBuff = self.__VPMBuffer return readu16(VPMBuff, Index), readu16(VPMBuff, Index + 2) end function Canvas:Render(): () local Canvas : EditableImage = self.__Canvas Canvas:WritePixelsBuffer(Vector2.zero, Canvas.Size, self.__ImageBuffer) return nil end function Canvas:Destroy(): () self.__Canvas:Destroy() self.__Easel:Destroy() setmetatable(self, nil) table.clear(self) self = nil return nil end return Canvas
1,253
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/src/GraphicsMathLib.luau
--[=[ GraphicsMathLib Reimplementation of commonly used GLSL functions in Luau. NOTE: - Reimplementation is incomplete - Do not implement function swizzling just like what GLSL did, as Luau is not powerful enough to do that ]=] --!native local MathLib = {} function MathLib.fract_v3 ( v : Vector3 ) return Vector3.new( v.X - math.floor(v.X) , v.Y - math.floor(v.Y) , v.Z - math.floor(v.Z) ) end function MathLib.fract_v2 ( v : Vector2 ) return Vector2.new( v.X - math.floor(v.X) , v.Y - math.floor(v.Y) ) end function MathLib.fract ( x : number ) return x - math.floor(x) end function MathLib.smoothstep ( edge0 : number , edge1 : number , x : number ) local t = math.clamp((x - edge0) / (edge1 - edge0), 0, 1); return t * t * (3 - 2 * t); end function MathLib.clamp_v3 ( v : Vector3 , min : number , max : number ) return Vector3.new( math.clamp(v.X, min, max), math.clamp(v.Y, min, max), math.clamp(v.Z, min, max) ) end function MathLib.clamp_v2 ( v : Vector2 , min : number , max : number ) return Vector2.new( math.clamp(v.X, min, max), math.clamp(v.Y, min, max) ) end function MathLib.sqrt_v3 ( v : Vector3 ) return Vector3.new( math.sqrt(v.X) , math.sqrt(v.Y) , math.sqrt(v.Z) ) end function MathLib.sqrt_v2 ( v : Vector2 ) return Vector2.new( math.sqrt(v.X) , math.sqrt(v.Y) ) end function MathLib.sin_v3 ( v : Vector3 ) return Vector3.new( math.sin(v.X) , math.sin(v.Y) , math.sin(v.Z) ) end function MathLib.sin_v2 ( v : Vector2 ) return Vector2.new( math.sin(v.X) , math.sin(v.Y) ) end function MathLib.cos_v3 ( v : Vector3 ) return Vector3.new( math.cos(v.X) , math.cos(v.Y) , math.cos(v.Z) ) end function MathLib.cos_v2 ( v : Vector2 ) return Vector2.new( math.cos(v.X) , math.cos(v.Y) ) end function MathLib.yzx ( v : Vector3 ) return Vector3.new(v.Y, v.Z, v.X) end function MathLib.zxy ( v : Vector3 ) return Vector3.new(v.Z, v.X, v.Y) end function MathLib.xz ( v : Vector3 ) return Vector2.new(v.X, v.Z) end function MathLib.yx ( v : Vector2 | Vector3 ) return Vector2.new(v.Y, v.X) end function MathLib.step ( edge : number , x : number ) return x < edge and 0 or 1 end function MathLib.step_v3 ( edge : Vector3 , x : Vector3 ) return Vector3.new( MathLib.step( edge.X , x.X ) , MathLib.step( edge.Y , x.Y ) , MathLib.step( edge.Z , x.Z ) ) end function MathLib.step_v2 ( edge : Vector2 , x : Vector2 ) return Vector2.new( MathLib.step( edge.X , x.X ) , MathLib.step( edge.Y , x.Y ) ) end -- // Basically lerp function MathLib.mix_v3 ( x : Vector3 , y : Vector3 , a : number ) return x:Lerp(y,a) end function MathLib.mix_v2 ( x : Vector2 , y : Vector2 , a : number ) return x:Lerp(y,a) end function MathLib.mix ( x : number , y : number , a : number ) return x + (y - x) * a end function MathLib.mod_v3 ( x : Vector3 , y : Vector3 ) return Vector3.new( x.X % y.X , x.Y % y.Y , x.Z % y.Z ) end function MathLib.mod_v2 ( x : Vector2 , y : Vector2 ) return Vector2.new( x.X % y.X , x.Y % y.Y ) end function MathLib.reflect ( i : Vector3 , n : Vector3 ) return i - 2 * n:Dot(i) * n end function MathLib.exp_v3 ( v : Vector3 ) return Vector3.new( math.exp(v.X) , math.exp(v.Y) , math.exp(v.Z) ) end function MathLib.exp_v2 ( v : Vector2 ) return Vector2.new( math.exp(v.X) , math.exp(v.Y) ) end function MathLib.pow_v3 ( v : Vector3 , vp : Vector3 ) return Vector3.new( math.pow(v.X, vp.X) , math.pow(v.Y, vp.Y) , math.pow(v.Z, vp.Z) ) end function MathLib.pow_v2 ( v : Vector2 , vp : Vector3 ) return Vector2.new( math.pow(v.X, vp.X) , math.pow(v.Y, vp.Y) ) end --[=[======================= /* NON-GLSL FUNCTIONS */ --========================]=] function MathLib.v3_rgb ( v : Vector3 ) return v.X, v.Y, v.Z end function MathLib.c3_rgb ( c : Color3 ) return c.R, c.G, c.B end function MathLib.v3_rgba ( v : Vector3 , alpha : number? ) return v.X, v.Y, v.Z, alpha end function MathLib.c3_rgba ( c : Color3 , alpha : number? ) return c.R, c.G, c.B, alpha end function MathLib.c3 ( a : Color3 | Vector3 ) return typeof(a) == 'Color3' and a or Color3.new( a.X, a.Y, a.Z ) end for operation : string, func : () -> any in math do MathLib[operation] = func end MathLib.Vector4 = require(script.Parent.Vector4) return MathLib
1,455
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/src/Vector4.luau
--[=[ Vector4 Partial implementation of the `vec4` data type in GLSL. ]=] --!native local cos = math.cos local sin = math.sin local Vector4 = {} function Vector4.new( x : number , y : number , z : number , w : number ) local vec4 = { X = x , Y = y , Z = z , W = w } function vec4:Cos() return Vector4.new( cos(self.X) , cos(self.Y) , cos(self.Z) , cos(self.W) ) end function vec4:Sin() return Vector4.new( sin(self.X) , sin(self.Y) , sin(self.Z) , sin(self.W) ) end function vec4:Lerp( b : Vector4 , t : number ) return Vector4.new( self.X + ( b.X - self.X ) * t , self.Y + ( b.Y - self.Y ) * t , self.Z + ( b.Z - self.Z ) * t , self.W + ( b.W - self.W ) * t ) end local function IsAVector4( p : {} ) return type(p) == 'table' and p.X and p.Y and p.Z and p.W end setmetatable(vec4, { __add = function( a , b ) return Vector4.new( a.X + b.X , a.Y + b.Y , a.Z + b.Z , a.W + b.W ) end, __sub = function( a , b ) return Vector4.new( a.X - b.X , a.Y - b.Y , a.Z - b.Z , a.W - b.W ) end, __mul = function ( a , b ) if not IsAVector4(a) then a, b = b, a end if IsAVector4(b) then return Vector4.new( a.X * b.X , a.Y * b.Y , a.Z * b.Z , a.W * b.W ) else return Vector4.new( a.X * b , a.Y * b , a.Z * b , a.W * b ) end end, __div = function ( a , b ) if not IsAVector4(a) then a, b = b, a end if IsAVector4(b) then return Vector4.new( a.X / b.X , a.Y / b.Y , a.Z / b.Z , a.W / b.W ) else return Vector4.new( a.X / b , a.Y / b , a.Z / b , a.W / b ) end end, }) return vec4 end setmetatable(Vector4, { __index = function( self , index ) if index == 'one' then return Vector4.new(1, 1, 1, 1) elseif index == 'zero' then return Vector4.new(0, 0, 0, 0) end end, }) export type Vector4 = typeof(Vector4) return Vector4
742
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/src/utils/Argue.luau
--[=[ Basically an assertion with format. ]=] --!native --!strict local argue = setmetatable({}, { __call = function ( t : {} , cond : any , msg : string ) msg = msg or 'Assertion failed!' local location = t.at or debug.info(2, "n") if not cond then return error( `@RbxShader/{location}: {msg}` ) end end }) function argue:at( at : string ) if typeof(at) ~= "string" then return argue end return setmetatable({ at = at }, getmetatable(argue)) end return argue
139
AnotherSubatomo/RbxShader
AnotherSubatomo-RbxShader-6af4d49/src/utils/Common.luau
-- [=[ Common types found across the scripts. ]=] --!native export type ShaderBuffer = ( fragColor : Vector3 , fragCoords : Vector2 , iTime : number , iTimeDelta : number , iResolution : Vector2 , iMouse : SharedTable , iDate : {number} ) -> (number, number, number, number) -- a few buffer name examples export type BufferName = 'bufferA' | 'bufferB' | 'bufferC' | 'bufferD' | 'bufferE' export type Shader = { CONFIGURATION : EngineConfiguration , [BufferName] : ShaderBuffer , mainImage : ShaderBuffer } export type EngineConfiguration = { InterlaceFactor : number , DualAxisInterlacing : boolean , ScreenDivision : number , InitialColor : Color3? , InitialAlpha : number? , IsBlurred : boolean? , OriginOffset : Vector2 , CountDirection : Vector2 } return true
209
Shiawaseu/RBLX-Whitelist
Shiawaseu-RBLX-Whitelist-da315fe/.vscode/luraph.d.luau
-- Thanks Stefan type GenericFunction<T, U...> = (U...) -> T; declare function LPH_ENCFUNC<T, U...>(toEncrypt: GenericFunction<T, U...>, encKey: string, decKey: string): GenericFunction<T, U...> declare function LPH_ENCSTR(toEncrypt: string): string declare function LPH_ENCNUM(toEncrypt: number): number declare function LPH_CRASH(): never declare function LPH_JIT<T, U...>(toEnchance: GenericFunction<T, U...>): GenericFunction<T, U...> declare function LPH_NO_VIRTUALIZE<T, U...>(toDevirtualize: GenericFunction<T, U...>): GenericFunction<T, U...> declare function LPH_NO_UPVALUES<T, U...>(toFix: GenericFunction<T, U...>): GenericFunction<T, U...> declare LPH_OBFUSCATED: boolean?
195
Ultray-Studios/RBXConnectionManager
Ultray-Studios-RBXConnectionManager-18be690/RBXConnectionManager.luau
local Players = game:GetService("Players") local RunService = game:GetService("RunService") local RBXConnectionManager = {} RBXConnectionManager.__index = RBXConnectionManager -- Constructor -- function RBXConnectionManager.new(monitoring_checker_interval: number?, osdate_format: string?) local self = setmetatable({}, RBXConnectionManager) self._connections = {} :: { [string]: RBXScriptConnection } self._internal_connections = {} :: { RBXScriptConnection } self._monitoring = {} :: { [string]: any } self._osdate_format = osdate_format or "%Y-%m-%d %H:%M:%S" self._threads = { ["auto_disconnect"] = {} } -- Cleanup player-specific connections (server-side feature) if RunService:IsServer() then local globalPlayersRemovingConnection = Players.PlayerRemoving:Connect(function(playerObj: Player) self:DisconnectAllInGroup(tostring(playerObj.UserId)) end) table.insert(self._internal_connections, globalPlayersRemovingConnection) end self:_StartMonitoring(monitoring_checker_interval) return self end -- Methods to change settings -- function RBXConnectionManager:ChangeMonitoringCheckInterval(new_interval: number) self:_StartMonitoring(new_interval) end function RBXConnectionManager:ChangeOsDateFormat(new_osdate_format: string) self._osdate_format = new_osdate_format end function RBXConnectionManager:AddAutoDisconnect(group_name: string, event: RBXScriptSignal) self._threads["auto_disconnect"][group_name] = {} table.insert( self._threads["auto_disconnect"][group_name], event:Connect(function() self:DisconnectAllInGroup(group_name) end) ) end -- Action Methods -- -- Add a connection function RBXConnectionManager:Connect( name: string, event: RBXScriptSignal, callback, monitoring: boolean? ): RBXScriptConnection if self._connections[name] then -- Disconnect and replace the existing connection self:Disconnect(name) self._connections[name] = nil end -- Enable monitoring if specified if monitoring == true then self._monitoring[name] = {} local original_callback = callback callback = function(...) -- Log the data with date time format table.insert(self._monitoring[name], { date_time = os.date(self._osdate_format), arguments = { ... }, }) -- Execute the original callback original_callback(...) end end -- Create the connection local connection = event:Connect(callback) self._connections[name] = connection return connection end -- Disconnect connection by name function RBXConnectionManager:Disconnect(name: string) local connection = self._connections[name] if connection and connection.Connected then connection:Disconnect() self._connections[name] = nil end end -- Disconnect all connections within a specific group function RBXConnectionManager:DisconnectAllInGroup(group: string) for name, connection in pairs(self._connections) do if string.find(name, group) then if connection.Connected then connection:Disconnect() end self._connections[name] = nil end end end -- Disconnect all connections function RBXConnectionManager:DisconnectAll() for _, connection in pairs(self._connections) do if connection.Connected then connection:Disconnect() end end self._connections = {} end -- Self-destruct function RBXConnectionManager:Destroy() -- Disconnect the module's internal connections for _, connection in pairs(self._internal_connections) do if connection.Connected then connection:Disconnect() end end self._internal_connections = {} self:DisconnectAll() setmetatable(self, nil) end -- Get monitoring results gathered until now function RBXConnectionManager:GetAllMonitoringData() for connection_name, monitoring_data in self._monitoring do if not monitoring_data or type(monitoring_data) ~= "table" then warn("Monitoring disabled for " .. connection_name) else local total_logs = #monitoring_data for i, log in ipairs(monitoring_data) do warn( "Monitoring log for " .. connection_name .. ": #" .. tostring(i) .. "/" .. tostring(total_logs), log ) end end end end -- Will show up new monitoring results when collected function RBXConnectionManager:_StartMonitoring(checker_interval: number?) if self._threads["monitoring"] ~= nil then task.cancel(self._threads["monitoring"]) end self._threads["monitoring"] = task.spawn(function() -- Store latest known logs for each connection local last_log_counts = {} while true do for connection_name, monitoring_data in pairs(self._monitoring) do -- Check if monitoring is enabled for this connection if type(monitoring_data) == "table" then local previous_count = last_log_counts[connection_name] or 0 local current_count = #monitoring_data -- If there are new logs, show them if current_count > previous_count then for i = previous_count + 1, current_count do local log = monitoring_data[i] warn( "Monitoring log for " .. connection_name .. ": #" .. tostring(i) .. "/" .. tostring(current_count), log ) end -- Update latest known log count last_log_counts[connection_name] = current_count end end end task.wait(checker_interval or 1) end end) end return RBXConnectionManager
1,232
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Admin/announce.luau
return { Name = "announce", Aliases = { "m" }, Description = "Makes a server-wide announcement.", Group = "DefaultAdmin", Args = { { Type = "string", Name = "text", Description = "The announcement text.", }, }, }
64
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Admin/gotoPlace.luau
return { Name = "goto-place", Aliases = {}, Description = "Teleport to a Roblox place", Group = "DefaultAdmin", AutoExec = { 'alias "follow-player|Join a player in another server" goto-place $1{players|Players} ${{get-player-place-instance $2{playerId|Target}}}', 'alias "rejoin|Rejoin this place. You might end up in a different server." goto-place $1{players|Players} ${get-player-place-instance ${me} PlaceId}', }, Args = { { Type = "players", Name = "Players", Description = "The players you want to teleport", }, { Type = "positiveInteger", Name = "Place ID", Description = "The Place ID you want to teleport to", }, { Type = "string", Name = "JobId", Description = "The specific JobId you want to teleport to", Optional = true, }, }, }
225
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Admin/kick.luau
return { Name = "kick", Aliases = { "boot" }, Description = "Kicks a player or set of players.", Group = "DefaultAdmin", Args = { { Type = "players", Name = "players", Description = "The players to kick.", }, }, }
68
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Admin/kickServer.luau
return function(_, players) for _, player in pairs(players) do player:Kick("Kicked by admin.") end return ("Kicked %d players."):format(#players) end
41
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Admin/kill.luau
return { Name = "kill", Aliases = { "slay" }, Description = "Kills a player or set of players.", Group = "DefaultAdmin", Args = { { Type = "players", Name = "victims", Description = "The players to kill.", }, }, }
71
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Admin/killServer.luau
return function(_, players) for _, player in pairs(players) do if player.Character then player.Character:BreakJoints() end end return ("Killed %d players."):format(#players) end
48
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Admin/teleport.luau
return { Name = "teleport", Aliases = { "tp" }, Description = "Teleports a player or set of players to one target.", Group = "DefaultAdmin", AutoExec = { 'alias "bring|Brings a player or set of players to you." teleport $1{players|players|The players to bring} ${me}', 'alias "to|Teleports you to another player or location." teleport ${me} $1{player @ vector3|Destination|The player or location to teleport to}', }, Args = { { Type = "players", Name = "From", Description = "The players to teleport", }, { Type = "player @ vector3", Name = "Destination", Description = "The player to teleport to", }, }, }
182
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Admin/teleportServer.luau
return function(_, fromPlayers, destination) local cframe if typeof(destination) == "Instance" then if destination.Character and destination.Character:FindFirstChild("HumanoidRootPart") then cframe = destination.Character.HumanoidRootPart.CFrame else return "Target player has no character." end elseif typeof(destination) == "Vector3" then cframe = CFrame.new(destination) end for _, player in ipairs(fromPlayers) do if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then if player.Character.Humanoid.Sit then player.Character.Humanoid.Jump = true end player.Character.HumanoidRootPart.CFrame = cframe end end return ("Teleported %d players."):format(#fromPlayers) end
179
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Debug/fetch.luau
return { Name = "fetch", Aliases = {}, Description = "Fetch a value from the Internet", Group = "DefaultDebug", Args = { { Type = "url", Name = "URL", Description = "The URL to fetch.", }, }, }
62
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Debug/fetchServer.luau
local HttpService = game:GetService("HttpService") return function(_, url) return HttpService:GetAsync(url) end
25
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Debug/getPlayerPlaceInstance.luau
return { Name = "get-player-place-instance", Aliases = {}, Description = "Returns the target player's Place ID and the JobId separated by a space. Returns 0 if the player is offline or something else goes wrong.", Group = "DefaultDebug", Args = { { Type = "playerId", Name = "Player", Description = "Get the place instance of this player", }, function(context) return { Type = context.Cmdr.Util.MakeEnumType("PlaceInstance Format", { "PlaceIdJobId", "PlaceId", "JobId" }), Name = "Format", Description = "What data to return. PlaceIdJobId returns both separated by a space.", Default = "PlaceIdJobId", } end, }, }
171
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Debug/getPlayerPlaceInstanceServer.luau
local TeleportService = game:GetService("TeleportService") return function(_, playerId, format) format = format or "PlaceIdJobId" local ok, _, errorText, placeId, jobId = pcall(function() return TeleportService:GetPlayerPlaceInstanceAsync(playerId) end) if not ok or (errorText and #errorText > 0) then if format == "PlaceIdJobId" then return "0" .. " -" elseif format == "PlaceId" then return "0" elseif format == "JobId" then return "-" end end if format == "PlaceIdJobId" then return placeId .. " " .. jobId elseif format == "PlaceId" then return tostring(placeId) elseif format == "JobId" then return tostring(jobId) end end
187
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Debug/position.luau
local Players = game:GetService("Players") return { Name = "position", Aliases = { "pos" }, Description = "Returns Vector3 position of you or other players. Empty string is the player has no character.", Group = "DefaultDebug", Args = { { Type = "player", Name = "Player", Description = "The player to report the position of. Omit for your own position.", Default = Players.LocalPlayer, }, }, ClientRun = function(_, player) local character = player.Character if not character or not character:FindFirstChild("HumanoidRootPart") then return "" end return tostring(character.HumanoidRootPart.Position):gsub("%s", "") end, }
160
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Debug/uptime.luau
return { Name = "uptime", Aliases = {}, Description = "Returns the amount of time the server has been running.", Group = "DefaultDebug", Args = {}, }
37
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Debug/uptimeServer.luau
local startTime = os.time() return function() local uptime = os.time() - startTime return ("%dd %dh %dm %ds"):format( math.floor(uptime / (60 * 60 * 24)), math.floor(uptime / (60 * 60)) % 24, math.floor(uptime / 60) % 60, math.floor(uptime) % 60 ) end
92
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Debug/version.luau
local version = "v1.12.0" return { Name = "version", Args = {}, Description = "Shows the current version of Cmdr", Group = "DefaultDebug", ClientRun = function() return ("Cmdr Version %s"):format(version) end, }
60
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/alias.luau
return { Name = "alias", Aliases = {}, Description = "Creates a new, single command out of a command and given arguments.", Group = "DefaultUtil", Args = { { Type = "string", Name = "Alias name", Description = "The key or input type you'd like to bind the command to.", }, { Type = "string", Name = "Command string", Description = 'The command text you want to run. Separate multiple commands with "&&". Accept arguments with $1, $2, $3, etc.', }, }, ClientRun = function(context, name, commandString) context.Cmdr.Registry:RegisterCommandObject(context.Cmdr.Util.MakeAliasCommand(name, commandString), true) return ("Created alias %q"):format(name) end, }
177
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/bind.luau
local UserInputService = game:GetService("UserInputService") local TextChatService = game:GetService("TextChatService") return { Name = "bind", Aliases = {}, Description = "Binds a command string to a key or mouse input.", Group = "DefaultUtil", Args = { { Type = "userInput ! bindableResource @ player", Name = "Input", Description = "The key or input type you'd like to bind the command to.", }, { Type = "command", Name = "Command", Description = "The command you want to run on this input", }, { Type = "string", Name = "Arguments", Description = "The arguments for the command", Default = "", }, }, ClientRun = function(context, bind, command, arguments) local binds = context:GetStore("CMDR_Binds") command = command .. " " .. arguments if binds[bind] then binds[bind]:Disconnect() end local bindType = context:GetArgument(1).Type.Name if bindType == "userInput" then binds[bind] = UserInputService.InputBegan:Connect(function(input, gameProcessed) if gameProcessed then return end if input.UserInputType == bind or input.KeyCode == bind then context:Reply( context.Dispatcher:EvaluateAndRun( context.Cmdr.Util.RunEmbeddedCommands(context.Dispatcher, command) ) ) end end) elseif bindType == "bindableResource" then return "Unimplemented..." elseif bindType == "player" then local function RunCommand(message) local args = { message } local chatCommand = context.Cmdr.Util.RunEmbeddedCommands( context.Dispatcher, context.Cmdr.Util.SubstituteArgs(command, args) ) context:Reply( ("%s $ %s : %s"):format(bind.Name, chatCommand, context.Dispatcher:EvaluateAndRun(chatCommand)), Color3.fromRGB(244, 92, 66) ) end if TextChatService.ChatVersion == Enum.ChatVersion.LegacyChatService then binds[bind] = bind.Chatted:Connect(RunCommand) else binds[bind] = TextChatService.SendingMessage:Connect(function(message) RunCommand(message.Text) end) end end return "Bound command to input." end, }
543
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/clear.luau
local Players = game:GetService("Players") return { Name = "clear", Aliases = {}, Description = "Clear all lines above the entry line of the Cmdr window.", Group = "DefaultUtil", Args = {}, ClientRun = function() local player = Players.LocalPlayer local gui = player:WaitForChild("PlayerGui"):WaitForChild("Cmdr") local frame = gui:WaitForChild("Frame") if gui and frame then for _, child in pairs(frame:GetChildren()) do if child.Name == "Line" and child:IsA("TextBox") then child:Destroy() end end end return "" end, }
148
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/convertTimestamp.luau
return { Name = "convertTimestamp", Aliases = { "date" }, Description = "Convert a timestamp to a human-readable format.", Group = "DefaultUtil", Args = { { Type = "number", Name = "timestamp", Description = "A numerical representation of a specific moment in time.", Optional = true, }, }, ClientRun = function(_, timestamp) timestamp = timestamp or os.time() return `{os.date("%x", timestamp)} {os.date("%X", timestamp)}` end, }
116
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/echo.luau
return { Name = "echo", Aliases = { "=" }, Description = "Echoes your text back to you.", Group = "DefaultUtil", Args = { { Type = "string", Name = "Text", Description = "The text.", }, }, ClientRun = function(_, text) return text end, }
76
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/edit.luau
local Players = game:GetService("Players") local TEXT_BOX_PROPERTIES = { AnchorPoint = Vector2.new(0.5, 0.5), BackgroundColor3 = Color3.fromRGB(17, 17, 17), BackgroundTransparency = 0.05, BorderColor3 = Color3.fromRGB(17, 17, 17), BorderSizePixel = 20, ClearTextOnFocus = false, MultiLine = true, Position = UDim2.new(0.5, 0, 0.5, 0), Size = UDim2.new(0.5, 0, 0.4, 0), Font = Enum.Font.Code, TextColor3 = Color3.fromRGB(241, 241, 241), TextWrapped = true, TextSize = 18, TextXAlignment = "Left", TextYAlignment = "Top", AutoLocalize = false, PlaceholderText = "Right click to exit", } local lock return { Name = "edit", Aliases = {}, Description = "Edit text in a TextBox", Group = "DefaultUtil", Args = { { Type = "string", Name = "Input text", Description = "The text you wish to edit", Default = "", }, { Type = "string", Name = "Delimiter", Description = "The character that separates each line", Default = ",", }, }, ClientRun = function(context, text, delimeter) lock = lock or context.Cmdr.Util.Mutex() local unlock = lock() context:Reply("Right-click on the text area to exit.", Color3.fromRGB(158, 158, 158)) local screenGui = Instance.new("ScreenGui") screenGui.Name = "CmdrEditBox" screenGui.ResetOnSpawn = false local textBox = Instance.new("TextBox") for key, value in pairs(TEXT_BOX_PROPERTIES) do textBox[key] = value end textBox.Text = text:gsub(delimeter, "\n") textBox.Parent = screenGui screenGui.Parent = Players.LocalPlayer:WaitForChild("PlayerGui") local thread = coroutine.running() textBox.InputBegan:Connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton2 then coroutine.resume(thread, textBox.Text:gsub("\n", delimeter)) screenGui:Destroy() unlock() end end) return coroutine.yield() end, }
546
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/history.luau
return { Name = "history", Aliases = {}, AutoExec = { 'alias "!|Displays previous command from history." run ${history $1{number|Line Number}}', 'alias "^|Runs the previous command, replacing all occurrences of A with B." run ${run replace ${history -1} $1{string|A} $2{string|B}}', 'alias "!!|Reruns the last command." ! -1', }, Description = "Displays previous commands from history.", Group = "DefaultUtil", Args = { { Type = "integer", Name = "Line Number", Description = "Command line number (can be negative to go from end)", }, }, ClientRun = function(context, line) local history = context.Dispatcher:GetHistory() if line <= 0 then line = #history + line end return history[line] or "" end, }
206
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/hover.luau
local Players = game:GetService("Players") return { Name = "hover", Description = "Returns the name of the player you are hovering over.", Group = "DefaultUtil", Args = {}, ClientRun = function() local mouse = Players.LocalPlayer:GetMouse() local target = mouse.Target if not target then return "" end local p = Players:GetPlayerFromCharacter(target:FindFirstAncestorOfClass("Model")) return p and p.Name or "" end, }
106
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/jsonArrayDecode.luau
return { Name = "json-array-decode", Aliases = {}, Description = "Decodes a JSON Array into a comma-separated list", Group = "DefaultUtil", Args = { { Type = "json", Name = "JSON", Description = "The JSON array.", }, }, ClientRun = function(_, value) if type(value) ~= "table" then value = { value } end return table.concat(value, ",") end, }
105
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/jsonArrayEncode.luau
local HttpService = game:GetService("HttpService") return { Name = "json-array-encode", Aliases = {}, Description = "Encodes a comma-separated list into a JSON array", Group = "DefaultUtil", Args = { { Type = "string", Name = "CSV", Description = "The comma-separated list", }, }, ClientRun = function(_, text) return HttpService:JSONEncode(text:split(",")) end, }
101
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/len.luau
return { Name = "len", Aliases = {}, Description = "Returns the length of a comma-separated list", Group = "DefaultUtil", Args = { { Type = "string", Name = "CSV", Description = "The comma-separated list", }, }, ClientRun = function(_, list) return #(list:split(",")) end, }
81
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/math.luau
return { Name = "math", Aliases = {}, Description = "Perform a math operation on 2 values.", Group = "DefaultUtil", AutoExec = { 'alias "+|Perform an addition." math + $1{number|Number} $2{number|Number}', 'alias "-|Perform a subtraction." math - $1{number|Number} $2{number|Number}', 'alias "*|Perform a multiplication." math * $1{number|Number} $2{number|Number}', 'alias "/|Perform a division." math / $1{number|Number} $2{number|Number}', 'alias "**|Perform an exponentiation." math ** $1{number|Number} $2{number|Number}', 'alias "%|Perform a modulus." math % $1{number|Number} $2{number|Number}', }, Args = { { Type = "mathOperator", Name = "Operation", Description = "A math operation.", }, { Type = "number", Name = "Value", Description = "A number value.", }, { Type = "number", Name = "Value", Description = "A number value.", }, }, ClientRun = function(_, operation, a, b) return operation.Perform(a, b) end, }
301
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/pick.luau
return { Name = "pick", Aliases = {}, Description = "Picks a value out of a comma-separated list.", Group = "DefaultUtil", Args = { { Type = "positiveInteger", Name = "Index to pick", Description = "The index of the item you want to pick", }, { Type = "string", Name = "CSV", Description = "The comma-separated list", }, }, ClientRun = function(_, index, list) return list:split(",")[index] or "" end, }
123
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/rand.luau
local generator = Random.new() return { Name = "rand", Aliases = {}, Description = "Returns a random number between min and max", Group = "DefaultUtil", Args = { { Type = "integer", Name = "First number", Description = "If second number is nil, random number is between 1 and this value. If second number is provided, number is between this number and the second number.", }, { Type = "integer", Name = "Second number", Description = "The upper bound.", Optional = true, }, }, ClientRun = function(_, firstNumber, secondNumber) return tostring( if secondNumber then generator:NextInteger(firstNumber, secondNumber) else generator:NextInteger(1, firstNumber) ) end, }
179
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/replace.luau
return { Name = "replace", Aliases = { "gsub", "//" }, Description = "Replaces text A with text B", Group = "DefaultUtil", AutoExec = { 'alias "map|Maps a CSV into another CSV" replace $1{string|CSV} ([^,]+) "$2{string|mapped value|Use %1 to insert the element}"', 'alias "join|Joins a CSV with a specified delimiter" replace $1{string|CSV} , $2{string|Delimiter}', }, Args = { { Type = "string", Name = "Haystack", Description = "The source string upon which to perform replacement.", }, { Type = "string", Name = "Needle", Description = "The string pattern search for.", }, { Type = "string", Name = "Replacement", Description = "The string to replace matches (%1 to insert matches).", Default = "", }, }, ClientRun = function(_, haystack, needle, replacement) return haystack:gsub(needle, replacement) end, }
247
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/resolve.luau
return { Name = "resolve", Aliases = {}, Description = "Resolves Argument Value Operators into lists. E.g., resolve players * gives you a list of all players.", Group = "DefaultUtil", AutoExec = { 'alias "me|Displays your username" resolve players .', }, Args = { { Type = "type", Name = "Type", Description = "The type for which to resolve", }, function(context) if context:GetArgument(1):Validate() == false then return end return { Type = context:GetArgument(1):GetValue(), Name = "Argument Value Operator", Description = "The value operator to resolve. One of: * ** . ? ?N", Optional = true, } end, }, ClientRun = function(context) return table.concat(context:GetArgument(2).RawSegments, ",") end, }
201
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/run.luau
return { Name = "run", Aliases = { ">" }, AutoExec = { 'alias "discard|Run a command and discard the output." replace ${run $1} .* \\"\\"', }, Description = "Runs a given command string (replacing embedded commands).", Group = "DefaultUtil", Args = { { Type = "string", Name = "Command", Description = "The command string to run", }, }, ClientRun = function(context, commandString) return context.Cmdr.Util.RunCommandString(context.Dispatcher, commandString) end, }
129
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/runLines.luau
return { Name = "run-lines", Aliases = {}, Description = "Splits input by newlines and runs each line as its own command. This is used by the init-run command.", Group = "DefaultUtil", Args = { { Type = "string", Name = "Script", Description = "The script to parse.", Default = "", }, }, ClientRun = function(context, text) if #text == 0 then return "" end local shouldPrintOutput = context.Dispatcher:Run("var", "INIT_PRINT_OUTPUT") ~= "" local commands = text:gsub("\n+", "\n"):split("\n") for _, command in ipairs(commands) do if command:sub(1, 1) == "#" then continue end local output = context.Dispatcher:EvaluateAndRun(command) if shouldPrintOutput then context:Reply(output) end end return "" end, }
211
evaera/Cmdr
evaera-Cmdr-030e1a6/Cmdr/BuiltInCommands/Utility/runif.luau
local conditions = { startsWith = function(text, arg) if text:sub(1, #arg) == arg then return text:sub(#arg + 1) end end, } return { Name = "runif", Aliases = {}, Description = "Runs a given command string if a certain condition is met.", Group = "DefaultUtil", Args = { { Type = "conditionFunction", Name = "Condition", Description = "The condition function", }, { Type = "string", Name = "Argument", Description = "The argument to the condition function", }, { Type = "string", Name = "Test against", Description = "The text to test against.", }, { Type = "string", Name = "Command", Description = "The command string to run if requirements are met. If omitted, return value from condition function is used.", Optional = true, }, }, ClientRun = function(context, condition, arg, testAgainst, command) local conditionFunc = conditions[condition] if not conditionFunc then return ("Condition %q is not valid."):format(condition) end local text = conditionFunc(testAgainst, arg) if text then return context.Dispatcher:EvaluateAndRun( context.Cmdr.Util.RunEmbeddedCommands(context.Dispatcher, command or text) ) end return "" end, }
317