repo
stringclasses
245 values
file_path
stringlengths
29
241
code
stringlengths
100
233k
tokens
int64
14
69.4k
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/CatalogSearchParams.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) -- TODO: This can be supported, it just has a lot of properties... return DataTypeDefinition.unimplemented("CatalogSearchParams")
51
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Color3.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Color3", { read = function(stream) return Color3.fromRGB(stream:readu8(), stream:readu8(), stream:readu8()) end, write = function(stream, color) local rHex, gHex, bHex = color:ToHex():match("(..)(..)(..)") stream:writeu8(tonumber(rHex, 16) :: number) stream:writeu8(tonumber(gHex, 16) :: number) stream:writeu8(tonumber(bHex, 16) :: number) end, })
154
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/ColorSequence.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("ColorSequence", { read = function(stream) local keypoints = {} local nKeypoints = stream:readu32() for i = 1, nKeypoints do local t = stream:readf32() local color = Color3.fromRGB(stream:readu8(), stream:readu8(), stream:readu8()) keypoints[i] = ColorSequenceKeypoint.new(t, color) end return ColorSequence.new(keypoints) end, write = function(stream, sequence) local keypoints = sequence.Keypoints stream:writeu32(#keypoints) for _, kp in keypoints do local rHex, gHex, bHex = kp.Value:ToHex():match("(..)(..)(..)") stream:writef32(kp.Time) stream:writeu8(tonumber(rHex, 16) :: number) stream:writeu8(tonumber(gHex, 16) :: number) stream:writeu8(tonumber(bHex, 16) :: number) end end, })
266
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/ColorSequenceKeypoint.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("ColorSequenceKeypoint", { read = function(stream) local t = stream:readf32() local color = Color3.fromRGB(stream:readu8(), stream:readu8(), stream:readu8()) return ColorSequenceKeypoint.new(t, color) end, write = function(stream, kp) local rHex, gHex, bHex = kp.Value:ToHex():match("(..)(..)(..)") stream:writef32(kp.Time) stream:writeu8(tonumber(rHex, 16) :: number) stream:writeu8(tonumber(gHex, 16) :: number) stream:writeu8(tonumber(bHex, 16) :: number) end, })
192
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Content.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("Content")
34
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/DockWidgetPluginGuiInfo.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("DockWidgetPluginGuiInfo")
38
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Enum.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Enum", { read = function(stream) local enumTypeName = stream:readString(stream:readu8()) return (Enum :: any)[enumTypeName] :: Enum end, write = function(stream, enumType) local enumTypeName = tostring(enumType) local length = #enumTypeName stream:writeu8(length) stream:writeString(enumTypeName, length) end, })
115
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/EnumItem.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("EnumItem", { read = function(stream) local enumName = stream:readString(stream:readu8()) local enumType = (Enum :: any)[enumName] :: Enum return enumType:FromValue(stream:readu16()) :: EnumItem end, write = function(stream, enumItem) local enumTypeName = tostring(enumItem.EnumType) local length = #enumTypeName stream:writeu8(length) stream:writeString(enumTypeName, length) stream:writeu16(enumItem.Value) end, })
148
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Enums.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Enums", { read = function(_stream) return Enum end, write = function(_stream) end, })
55
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Faces.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local FACE_NAME_ORDER = { "Front", "Bottom", "Left", "Back", "Top", "Right" } return DataTypeDefinition.new("Faces", { read = function(stream) local index = stream:readu8() local enums: { Enum.NormalId } = {} for i, faceName in FACE_NAME_ORDER do if bit32.band(index, bit32.lshift(1, (i - 1))) > 0 then table.insert(enums, (Enum.NormalId :: any)[faceName]) end end return Faces.new(table.unpack(enums)) end, write = function(stream, faces) local index = 0 for i, faceName in FACE_NAME_ORDER do if (faces :: any)[faceName] then index = bit32.bor(index, bit32.lshift(1, (i - 1))) end end stream:writeu8(index) end, })
232
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/FloatCurveKey.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local function readTangent(stream: DataTypeDefinition.BufferStream, tangentId: number): number? local prevCursor = stream.cursor if stream:readu8() == tangentId then return stream:readf32() end stream.cursor = prevCursor return nil end return DataTypeDefinition.new("FloatCurveKey", { read = function(stream) local t = stream:readf32() local v = stream:readf32() local interpolation = Enum.KeyInterpolationMode:FromValue(stream:readu16()) :: Enum.KeyInterpolationMode local ck = FloatCurveKey.new(t, v, interpolation) -- tangent props are typed as number, but they should be number? ck.LeftTangent = readTangent(stream, 1) :: number ck.RightTangent = readTangent(stream, 2) :: number return ck end, write = function(stream, ck) stream:writef32(ck.Time) stream:writef32(ck.Value) stream:writeu16(ck.Interpolation.Value) if ck.LeftTangent then stream:writeu8(1) stream:writef32(ck.LeftTangent) else stream:writeu8(0) end if ck.RightTangent then stream:writeu8(2) stream:writef32(ck.RightTangent) else stream:writeu8(0) end end, })
347
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Font.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Font", { read = function(stream) local weight = Enum.FontWeight:FromValue(stream:readu16()) :: Enum.FontWeight local style = Enum.FontStyle:FromValue(stream:readu16()) :: Enum.FontStyle local length = stream:readu8() if length == 0 then -- font id case local fontId = stream:readu32() return Font.fromId(fontId, weight, style) else -- family name case local familyName = stream:readString(length - 1) if familyName == "" then -- Enum.Font.Arial is the first font and maps to Arimo familyName = "Arimo" end return Font.fromName(familyName, weight, style) end end, write = function(stream, font) local family = font.Family local fontId = family:match("%d+$") stream:writeu16(font.Weight.Value) stream:writeu16(font.Style.Value) if fontId then stream:writeu8(0) stream:writeu32(tonumber(fontId) :: number) else local familyName = family:match("/(%w+).json$") or "" local length = #familyName -- we store the length as length + 1 since we're using this byte both for -- the length of the string, but also to identify if it's storing a font id or not assert(length <= 254, `Family name cannot exceed 254 characters: '{familyName}'`) stream:writeu8(length + 1) stream:writeString(familyName, length) end end, })
406
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Instance.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.unimplemented("Instance")
34
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/NumberRange.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("NumberRange", { read = function(stream) return NumberRange.new(stream:readf32(), stream:readf32()) end, write = function(stream, range) stream:writef32(range.Min) stream:writef32(range.Max) end, })
87
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/NumberSequence.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("NumberSequence", { read = function(stream) local keypoints = {} local nKeypoints = stream:readu32() for i = 1, nKeypoints do keypoints[i] = NumberSequenceKeypoint.new(stream:readf32(), stream:readf32(), stream:readf32()) end return NumberSequence.new(keypoints) end, write = function(stream, sequence) local keypoints = sequence.Keypoints stream:writeu32(#keypoints) for _, kp in keypoints do stream:writef32(kp.Time) stream:writef32(kp.Value) stream:writef32(kp.Envelope) end end, })
186
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/NumberSequenceKeypoint.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("NumberSequenceKeypoint", { read = function(stream) return NumberSequenceKeypoint.new(stream:readf32(), stream:readf32(), stream:readf32()) end, write = function(stream, kp) stream:writef32(kp.Time) stream:writef32(kp.Value) stream:writef32(kp.Envelope) end, })
112
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/OverlapParams.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("OverlapParams")
35
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Path2DControlPoint.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Path2DControlPoint", { read = function(stream) local pos = UDim2.new(stream:readf32(), stream:readi32(), stream:readf32(), stream:readi32()) local left = UDim2.new(stream:readf32(), stream:readi32(), stream:readf32(), stream:readi32()) local right = UDim2.new(stream:readf32(), stream:readi32(), stream:readf32(), stream:readi32()) return Path2DControlPoint.new(pos, left, right) end, write = function(stream, ctrlP) local pos = ctrlP.Position stream:writef32(pos.X.Scale) stream:writei32(pos.X.Offset) stream:writef32(pos.Y.Scale) stream:writei32(pos.Y.Offset) local left = ctrlP.LeftTangent stream:writef32(left.X.Scale) stream:writei32(left.X.Offset) stream:writef32(left.Y.Scale) stream:writei32(left.Y.Offset) local right = ctrlP.RightTangent stream:writef32(right.X.Scale) stream:writei32(right.X.Offset) stream:writef32(right.Y.Scale) stream:writei32(right.Y.Offset) end, })
314
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/PathWaypoint.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local label_u8 = 1 local label_u16 = 2 local label_u32 = 3 local labelReader = DataTypeDefinition.createReader({ [label_u8] = function(stream) return stream:readString(stream:readu8()) end, [label_u16] = function(stream) return stream:readString(stream:readu8()) end, [label_u32] = function(stream) return stream:readString(stream:readu8()) end, }) return DataTypeDefinition.new("PathWaypoint", { read = function(stream) local position = Vector3.new(stream:readf32(), stream:readf32(), stream:readf32()) local action = Enum.PathWaypointAction:FromValue(stream:readu16()) :: Enum.PathWaypointAction local label = labelReader(stream) return PathWaypoint.new(position, action, label) end, write = function(stream, wp) stream:writef32(wp.Position.X) stream:writef32(wp.Position.Y) stream:writef32(wp.Position.Z) stream:writeu16(wp.Action.Value) local label = wp.Label local length = #label if length <= 0xFF then stream:writeu8(label_u8) stream:writeu8(length) elseif length <= 0xFFFF then stream:writeu8(label_u16) stream:writeu16(length) else stream:writeu8(label_u32) stream:writeu32(length) end stream:writeString(label, length) end, })
367
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/PhysicalProperties.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) -- lsp doesn't seem to like acoustic absorption, but it does exist! local newPhysicalProps = PhysicalProperties.new :: (...number) -> PhysicalProperties return DataTypeDefinition.new("PhysicalProperties", { read = function(stream) return newPhysicalProps( stream:readf32(), stream:readf32(), stream:readf32(), stream:readf32(), stream:readf32(), stream:readf32() ) end, write = function(stream, phys) stream:writef32(phys.Density) stream:writef32(phys.Friction) stream:writef32(phys.Elasticity) stream:writef32(phys.FrictionWeight) stream:writef32(phys.ElasticityWeight) stream:writef32((phys :: any).AcousticAbsorption :: number) end, })
213
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/RBXScriptConnection.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("RBXScriptConnection")
37
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/RBXScriptSignal.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("RBXScriptSignal")
37
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Random.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("Random")
34
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Ray.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Ray", { read = function(stream) return Ray.new( Vector3.new(stream:readf32(), stream:readf32(), stream:readf32()), Vector3.new(stream:readf32(), stream:readf32(), stream:readf32()) ) end, write = function(stream, ray) stream:writef32(ray.Origin.X) stream:writef32(ray.Origin.Y) stream:writef32(ray.Origin.Z) stream:writef32(ray.Direction.X) stream:writef32(ray.Direction.Y) stream:writef32(ray.Direction.Z) end, })
166
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/RaycastParams.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("RaycastParams")
36
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/RaycastResult.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("RaycastResult")
36
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Rect.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Rect", { read = function(stream) return Rect.new(stream:readf32(), stream:readf32(), stream:readf32(), stream:readf32()) end, write = function(stream, rect) stream:writef32(rect.Min.X) stream:writef32(rect.Min.Y) stream:writef32(rect.Max.X) stream:writef32(rect.Max.Y) end, })
119
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Region3.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Region3", { read = function(stream) local vMin = Vector3.new(stream:readf32(), stream:readf32(), stream:readf32()) local vMax = Vector3.new(stream:readf32(), stream:readf32(), stream:readf32()) return Region3.new(vMin, vMax) end, write = function(stream, r3) local sx, sy, sz = r3.Size.X / 2, r3.Size.Y / 2, r3.Size.Z / 2 local vMin = r3.CFrame * Vector3.new(-sx, -sy, -sz) local vMax = r3.CFrame * Vector3.new(sx, sy, sz) stream:writef32(math.min(vMin.X, vMax.X)) stream:writef32(math.min(vMin.Y, vMax.Y)) stream:writef32(math.min(vMin.Z, vMax.Z)) stream:writef32(math.max(vMin.X, vMax.X)) stream:writef32(math.max(vMin.Y, vMax.Y)) stream:writef32(math.max(vMin.Z, vMax.Z)) end, })
286
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Region3int16.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Region3int16", { read = function(stream) local vMin = Vector3int16.new(stream:readi16(), stream:readi16(), stream:readi16()) local vMax = Vector3int16.new(stream:readi16(), stream:readi16(), stream:readi16()) return Region3int16.new(vMin, vMax) end, write = function(stream, r3int16) local r3Min = r3int16.Min local r3Max = r3int16.Max stream:writei16(r3Min.X) stream:writei16(r3Min.Y) stream:writei16(r3Min.Z) stream:writei16(r3Max.X) stream:writei16(r3Max.Y) stream:writei16(r3Max.Z) end, })
216
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/RotationCurveKey.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local CFrameStream = require(dataTypesRoot.Helpers.CFrameStream) local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("RotationCurveKey", { read = function(stream) local t = stream:readf32() local value = CFrameStream.read(stream) local interpolation = Enum.KeyInterpolationMode:FromValue(stream:readu16()) :: Enum.KeyInterpolationMode return RotationCurveKey.new(t, value, interpolation) end, write = function(stream, rck) stream:writef32(rck.Time) CFrameStream.write(stream, rck.Value) stream:writeu16(rck.Interpolation.Value) end, })
158
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Secret.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("Secret")
34
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/SharedTable.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) -- technically we could use a modified version of the table type, but that would require this to also be dependant return DataTypeDefinition.unimplemented("SharedTable")
59
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/TweenInfo.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("TweenInfo", { read = function(stream) local t = stream:readf32() local easingStyle = Enum.EasingStyle:FromValue(stream:readu16()) :: Enum.EasingStyle local easingDirection = Enum.EasingDirection:FromValue(stream:readu16()) :: Enum.EasingDirection local repeatCount = stream:readu32() - 1 local reverses = stream:readu8() == 1 local delayTime = stream:readf32() return TweenInfo.new(t, easingStyle, easingDirection, repeatCount, reverses, delayTime) end, write = function(stream, info) stream:writef32(info.Time) stream:writeu16(info.EasingStyle.Value) stream:writeu16(info.EasingDirection.Value) stream:writeu32(math.max(-1, info.RepeatCount) + 1) -- not sure abt this? stream:writeu8(if info.Reverses then 1 else 0) stream:writef32(info.DelayTime) end, })
262
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/UDim.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("UDim", { read = function(stream) return UDim.new(stream:readf32(), stream:readi32()) end, write = function(stream, udim) stream:writef32(udim.Scale) stream:writei32(udim.Offset) end, })
92
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/UDim2.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("UDim2", { read = function(stream) return UDim2.new(stream:readf32(), stream:readi32(), stream:readf32(), stream:readi32()) end, write = function(stream, udim2) stream:writef32(udim2.X.Scale) stream:writei32(udim2.X.Offset) stream:writef32(udim2.Y.Scale) stream:writei32(udim2.Y.Offset) end, })
137
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/ValueCurveKey.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("ValueCurveKey")
36
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Vector2.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Vector2", { read = function(stream) local x = stream:readf32() local y = stream:readf32() return Vector2.new(x, y) end, write = function(stream, vec) stream:writef32(vec.X) stream:writef32(vec.Y) end, })
99
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Vector2int16.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Vector2int16", { read = function(stream) local x = stream:readi16() local y = stream:readi16() return Vector2int16.new(x, y) end, write = function(stream, vec) stream:writei16(vec.X) stream:writei16(vec.Y) end, })
103
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Vector3.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Vector3", { read = function(stream) local x = stream:readf32() local y = stream:readf32() local z = stream:readf32() return Vector3.new(x, y, z) end, write = function(stream, vec) stream:writef32(vec.X) stream:writef32(vec.Y) stream:writef32(vec.Z) end, })
120
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Vector3int16.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("Vector3int16", { read = function(stream) local x = stream:readi16() local y = stream:readi16() local z = stream:readi16() return Vector3int16.new(x, y, z) end, write = function(stream, vec) stream:writei16(vec.X) stream:writei16(vec.Y) stream:writei16(vec.Z) end, })
124
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/vector.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("vector", { read = function(stream) local x = stream:readf32() local y = stream:readf32() local z = stream:readf32() return vector.create(x, y, z) end, write = function(stream, vec) stream:writef32(vec.x) stream:writef32(vec.y) stream:writef32(vec.z) end, })
118
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Userdata/Definitions/DeduplicationPointer.luau
local userdataRoot = script:FindFirstAncestor("Userdata") local UserdataDefinition = require(userdataRoot.UserdataDefinition) return UserdataDefinition.new("deduplication-pointer", function(index: number) return { index = index } end)
51
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Userdata/Definitions/InstancePointer.luau
local userdataRoot = script:FindFirstAncestor("Userdata") local UserdataDefinition = require(userdataRoot.UserdataDefinition) return UserdataDefinition.new("instance-pointer", function(index: number) return { index = index } end)
49
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Userdata/Definitions/Userdefined.luau
local userdataRoot = script:FindFirstAncestor("Userdata") local UserdataDefinition = require(userdataRoot.UserdataDefinition) return UserdataDefinition.new("userdefined", function(kind: string, b: buffer) return { kind = kind, b = b, } end)
62
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Userdata/Definitions/init.luau
return { Userdefined = require(script.Userdefined), InstancePointer = require(script.InstancePointer), DeduplicationPointer = require(script.DeduplicationPointer), }
34
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Userdata/Types/DeduplicationPointer.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local userdataRoot = script:FindFirstAncestor("Userdata") local UserdataDefinitions = require(userdataRoot.Definitions) local userdataDefinition = UserdataDefinitions.DeduplicationPointer local pointer_u8 = 1 local pointer_u16 = 2 local pointer_u32 = 3 local pointer_f64 = 4 return DataTypeDefinition.new(userdataDefinition.typeOf, { read = DataTypeDefinition.createReader({ [pointer_u8] = function(stream) return userdataDefinition:create(stream:readu8()) end, [pointer_u16] = function(stream) return userdataDefinition:create(stream:readu16()) end, [pointer_u32] = function(stream) return userdataDefinition:create(stream:readu32()) end, [pointer_f64] = function(stream) return userdataDefinition:create(stream:readf64()) end, }), write = function(stream, userdata) local pointer = userdataDefinition:read(userdata) local pointerIndex = pointer.index if pointerIndex <= 0xFF then stream:writeu8(pointer_u8) stream:writeu8(pointerIndex) elseif pointerIndex <= 0xFFFF then stream:writeu8(pointer_u16) stream:writeu16(pointerIndex) elseif pointerIndex <= 0xFFFFFFFF then stream:writeu8(pointer_u32) stream:writeu32(pointerIndex) else stream:writeu8(pointer_f64) stream:writef64(pointerIndex) end end, })
359
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Userdata/Types/InstancePointer.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local userdataRoot = script:FindFirstAncestor("Userdata") local UserdataDefinitions = require(userdataRoot.Definitions) local userdataDefinition = UserdataDefinitions.InstancePointer local pointer_u8 = 1 local pointer_u16 = 2 local pointer_u32 = 3 local pointer_f64 = 4 return DataTypeDefinition.new(userdataDefinition.typeOf, { read = DataTypeDefinition.createReader({ [pointer_u8] = function(stream) return userdataDefinition:create(stream:readu8()) end, [pointer_u16] = function(stream) return userdataDefinition:create(stream:readu16()) end, [pointer_u32] = function(stream) return userdataDefinition:create(stream:readu32()) end, [pointer_f64] = function(stream) return userdataDefinition:create(stream:readf64()) end, }), write = function(stream, userdata) local pointer = userdataDefinition:read(userdata) local pointerIndex = pointer.index if pointerIndex <= 0xFF then stream:writeu8(pointer_u8) stream:writeu8(pointerIndex) elseif pointerIndex <= 0xFFFF then stream:writeu8(pointer_u16) stream:writeu16(pointerIndex) elseif pointerIndex <= 0xFFFFFFFF then stream:writeu8(pointer_u32) stream:writeu32(pointerIndex) else stream:writeu8(pointer_f64) stream:writef64(pointerIndex) end end, })
356
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Userdata/Types/Userdefined.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local userdataRoot = script:FindFirstAncestor("Userdata") local UserdataDefinitions = require(userdataRoot.Definitions) local userdataDefinition = UserdataDefinitions.Userdefined local kind_u8 = 1 local kind_u16 = 2 local kind_u32 = 3 local readKind = DataTypeDefinition.createReader({ [kind_u8] = function(stream) return stream:readString(stream:readu8()) end, [kind_u16] = function(stream) return stream:readString(stream:readu16()) end, [kind_u32] = function(stream) return stream:readString(stream:readu32()) end, }) local buffer_u8 = 4 local buffer_u16 = 5 local buffer_u32 = 6 local readBuffer = DataTypeDefinition.createReader({ [buffer_u8] = function(stream) return stream:readBuffer(stream:readu8()) end, [buffer_u16] = function(stream) return stream:readBuffer(stream:readu16()) end, [buffer_u32] = function(stream) return stream:readBuffer(stream:readu32()) end, }) return DataTypeDefinition.new(userdataDefinition.typeOf, { read = function(stream) local kind = readKind(stream) local b = readBuffer(stream) return userdataDefinition:create(kind, b) end, write = function(stream, userdata) local userdefined = userdataDefinition:read(userdata) local kindLength = #userdefined.kind local bufferLength = buffer.len(userdefined.b) if kindLength <= 0xFF then stream:writeu8(kind_u8) stream:writeu8(kindLength) elseif kindLength <= 0xFFFF then stream:writeu8(kind_u16) stream:writeu16(kindLength) else stream:writeu8(kind_u32) stream:writeu32(kindLength) end stream:writeString(userdefined.kind) if bufferLength <= 0xFF then stream:writeu8(buffer_u8) stream:writeu8(bufferLength) elseif bufferLength <= 0xFFFF then stream:writeu8(buffer_u16) stream:writeu16(bufferLength) else stream:writeu8(buffer_u32) stream:writeu32(bufferLength) end stream:writeBuffer(userdefined.b, 0, bufferLength) end, })
551
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Userdata/UserdataDefinition.luau
local SUB_TYPE_OF_KEY = "_$_$_bufferize_typeof" local UserdataDefinitionStatic = {} local UserdataDefinitionClass = {} UserdataDefinitionClass.__index = UserdataDefinitionClass UserdataDefinitionClass.ClassName = "UserdataDefinition" type userdata<T> = { ["_$_$_bufferize_typeof"]: string, value: T, } type Options<T> = { write: () -> T, read: (userdata<T>) -> T, } export type UserdataDefinition<T, U...> = typeof(setmetatable( {} :: { subTypeOf: string, typeOf: string, write: (U...) -> T, }, UserdataDefinitionClass )) function UserdataDefinitionStatic.new<T, U...>(subTypeOf: string, write: (U...) -> T) local self = setmetatable({}, UserdataDefinitionClass) :: UserdataDefinition<T, U...> self.subTypeOf = subTypeOf self.typeOf = "userdata:" .. subTypeOf self.write = write return self end function UserdataDefinitionStatic.subTypeOf(userdata: any): string? local mt = typeof(userdata) == "userdata" and getmetatable(userdata) local mtIndex = typeof(mt) == "table" and rawget(mt, "__index") return typeof(mtIndex) == "table" and rawget(mtIndex :: any, SUB_TYPE_OF_KEY) or nil end function UserdataDefinitionClass.isTypeOf<T, U...>(self: UserdataDefinition<T, U...>, userdata: any) return UserdataDefinitionStatic.subTypeOf(userdata) == self.subTypeOf end function UserdataDefinitionClass.read<T, U...>(self: UserdataDefinition<T, U...>, userdata: userdata<T>) assert(typeof(userdata) == "userdata", "Cannot read non-userdata.") local subTypeOf = UserdataDefinitionStatic.subTypeOf(userdata) assert( subTypeOf == self.subTypeOf, `Attempt to read userdata typeof '{subTypeOf}' with typeof '{self.subTypeOf}' reader.` ) return userdata.value :: T end function UserdataDefinitionClass.create<T, U...>(self: UserdataDefinition<T, U...>, ...: U...) local userdata = newproxy(true) :: userdata<T> getmetatable(userdata :: any).__index = { [SUB_TYPE_OF_KEY] = self.subTypeOf, value = self.write(...), } return userdata end return UserdataDefinitionStatic
526
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/TypeIds.luau
local bufferizeRoot = script.Parent.Parent local CargoSemver = require(bufferizeRoot.Parent.CargoSemver) local TypeIds = {} local registeredArr = {} local function increment(semver: string) local registered = { index = #registeredArr + 1, semver = semver, } table.insert(registeredArr, registered) return registered end local REGISTERED_BY_TYPEOF: { [string]: typeof(increment("")) } = { ["nil"] = increment("2.0.0"), ["boolean"] = increment("2.0.0"), ["function"] = increment("2.0.0"), ["number"] = increment("2.0.0"), ["string"] = increment("2.0.0"), ["buffer"] = increment("2.0.0"), ["table"] = increment("2.0.0"), ["userdata"] = increment("2.0.0"), ["userdata:userdefined"] = increment("2.0.0"), ["userdata:instance-pointer"] = increment("2.0.0"), ["userdata:deduplication-pointer"] = increment("2.0.0"), ["Axes"] = increment("2.0.0"), ["BrickColor"] = increment("2.0.0"), ["CatalogSearchParams"] = increment("2.0.0"), ["CFrame"] = increment("2.0.0"), ["Color3"] = increment("2.0.0"), ["ColorSequence"] = increment("2.0.0"), ["ColorSequenceKeypoint"] = increment("2.0.0"), ["Content"] = increment("2.0.0"), ["DockWidgetPluginGuiInfo"] = increment("2.0.0"), ["Enum"] = increment("2.0.0"), ["EnumItem"] = increment("2.0.0"), ["Enums"] = increment("2.0.0"), ["Faces"] = increment("2.0.0"), ["FloatCurveKey"] = increment("2.0.0"), ["Font"] = increment("2.0.0"), ["Instance"] = increment("2.0.0"), ["NumberRange"] = increment("2.0.0"), ["NumberSequence"] = increment("2.0.0"), ["NumberSequenceKeypoint"] = increment("2.0.0"), ["OverlapParams"] = increment("2.0.0"), ["Path2DControlPoint"] = increment("2.0.0"), ["PathWaypoint"] = increment("2.0.0"), ["PhysicalProperties"] = increment("2.0.0"), ["Random"] = increment("2.0.0"), ["Ray"] = increment("2.0.0"), ["RaycastParams"] = increment("2.0.0"), ["RaycastResult"] = increment("2.0.0"), ["RBXScriptConnection"] = increment("2.0.0"), ["RBXScriptSignal"] = increment("2.0.0"), ["Rect"] = increment("2.0.0"), ["Region3"] = increment("2.0.0"), ["Region3int16"] = increment("2.0.0"), ["RotationCurveKey"] = increment("2.0.0"), ["Secret"] = increment("2.0.0"), ["SharedTable"] = increment("2.0.0"), ["TweenInfo"] = increment("2.0.0"), ["UDim"] = increment("2.0.0"), ["UDim2"] = increment("2.0.0"), ["ValueCurveKey"] = increment("2.0.0"), ["vector"] = increment("2.0.0"), ["Vector2"] = increment("2.0.0"), ["Vector2int16"] = increment("2.0.0"), ["Vector3"] = increment("2.0.0"), ["Vector3int16"] = increment("2.0.0"), } table.sort(registeredArr, function(a, b) local aVer = CargoSemver.Version.parse(a.semver) local bVer = CargoSemver.Version.parse(b.semver) if aVer ~= bVer then return aVer < bVer end return a.index < b.index end) for i, registered in registeredArr do registered.index = i end local typeIdMax = -1 local typeIdByTypeof = {} for typeOf, registered in REGISTERED_BY_TYPEOF do local typeId = registered.index - 1 typeIdByTypeof[typeOf] = typeId typeIdMax = math.max(typeIdMax, typeId) end function TypeIds.assert(name: string) return assert(typeIdByTypeof[name], `No TypeId registered for name '{name}'`) end assert(typeIdMax <= 255, "Registered TypeIds exceed u8 limits.") return TypeIds
1,077
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/TypeUnions.luau
export type Supported = nil | boolean | number | string | buffer | { any } | { [any]: any } | Axes | BrickColor | CFrame | Color3 | ColorSequence | ColorSequenceKeypoint | Enum | EnumItem | Enums | Faces | FloatCurveKey | Font | NumberRange | NumberSequence | NumberSequenceKeypoint | Path2DControlPoint | PathWaypoint | PhysicalProperties | Ray | Rect | Region3 | Region3int16 | RotationCurveKey | TweenInfo | UDim | UDim2 | vector | Vector2 | Vector2int16 | Vector3 | Vector3int16 export type Overridable = nil | boolean | number | string | buffer | Axes | BrickColor | CFrame | Color3 | ColorSequence | ColorSequenceKeypoint | Enum | EnumItem | Enums | Faces | FloatCurveKey | Font | NumberRange | NumberSequence | NumberSequenceKeypoint | Path2DControlPoint | PathWaypoint | PhysicalProperties | Ray | Rect | Region3 | Region3int16 | RotationCurveKey | TweenInfo | UDim | UDim2 | vector | Vector2 | Vector2int16 | Vector3 | Vector3int16 return {}
393
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/init.luau
local TypeUnions = require(script.TypeUnions) local DataTypePacker = require(script.DataTypePacker) local UserdataDefinitions = require(script.Standalone.Userdata.Definitions) export type Supported = TypeUnions.Supported export type Overridable = TypeUnions.Overridable return { Userdata = UserdataDefinitions, Encoder = DataTypePacker.new({ require(script.Standalone), require(script.Dependant), }), }
94
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/Encoder.luau
local packagesRoot = script.Parent.Parent local CargoSemver = require(packagesRoot.CargoSemver) local Wally = require(script.Parent.Wally) local DataTypes = require(script.Parent.DataTypes) local BufferStream = require(script.Parent.BufferStream) export type Supported = DataTypes.Supported export type Overridable = DataTypes.Overridable type CopyStackEntry<T> = { original: T, copy: T, } type CustomEncoder<T> = { read: (buffer) -> T, write: (T) -> buffer, } local function getWallySemVer() local parsed = CargoSemver.Version.parse(Wally.package.version) local ver = CargoSemver.Version.new( parsed.major, parsed.minor, parsed.patch, CargoSemver.Prerelease.EMPTY, CargoSemver.BuildMetadata.EMPTY ) local majorVer = CargoSemver.Version.new(parsed.major, 0, 0, CargoSemver.Prerelease.EMPTY, CargoSemver.BuildMetadata.EMPTY) local nextMajorVer = CargoSemver.Version.new( parsed.major + 1, parsed.minor, parsed.patch, CargoSemver.Prerelease.EMPTY, CargoSemver.BuildMetadata.EMPTY ) local length = #tostring(ver) assert(length <= 255, "Wally version cannot exceed 255 characters.") local stream = BufferStream.new(buffer.create(0)) stream:writeu8(length) stream:writeString(tostring(ver), length) return { ver = ver, majorVer = majorVer, nextMajorVer = nextMajorVer, header = stream.b, } end local WALLY_SEMVER = getWallySemVer() local function encodeInternal(rootTbl: { [any]: any }, encoders: { [string]: CustomEncoder<any> }) if next(encoders) then local stack = {} :: { CopyStackEntry<any> } local pointerCount = 0 local pointersByOriginal = {} local copiesByPointerIndex = {} local function stackCopyTbl(tbl: { [any]: any }) local copy: { [any]: any } = {} pointerCount = pointerCount + 1 pointersByOriginal[tbl] = pointerCount copiesByPointerIndex[pointerCount] = copy table.insert(stack, { original = tbl, copy = copy, }) return copy end local rootTblCopy = stackCopyTbl(rootTbl) while #stack > 0 do local popped = table.remove(stack) :: CopyStackEntry<any> for key, value in popped.original do local newKey = key local typeofKey = typeof(key) if typeofKey == "table" then local pointerIndex = pointersByOriginal[key] newKey = copiesByPointerIndex[pointerIndex] or stackCopyTbl(key) else local encoder = encoders[typeofKey] if encoder then newKey = DataTypes.Userdata.Userdefined:create(typeofKey, encoder.write(key)) end end local newValue = value local typeofValue = typeof(value) if typeofValue == "table" then local pointerIndex = pointersByOriginal[value] newValue = copiesByPointerIndex[pointerIndex] or stackCopyTbl(value) else local encoder = encoders[typeofValue] if encoder then newValue = DataTypes.Userdata.Userdefined:create(typeofValue, encoder.write(value)) end end popped.copy[newKey] = newValue end end rootTbl = rootTblCopy end local stream = BufferStream.new(buffer.create(0)) stream:writeBuffer(WALLY_SEMVER.header) DataTypes.Encoder:writeStream(stream, rootTbl) return stream.b end local function decodeInternal(b: buffer, encoders: { [string]: CustomEncoder<any> }) local stream = BufferStream.new(b) local length = stream:readu8() local wallyVersion = stream:readString(length) local headerVer = assert(CargoSemver.Version.parse(wallyVersion), "Failed to read header version.") assert( headerVer >= WALLY_SEMVER.majorVer and headerVer < WALLY_SEMVER.nextMajorVer, `Attempted to decode a buffer encoded with a different major version '{headerVer}'.` ) assert( headerVer <= WALLY_SEMVER.ver, `Attempted to decode a buffer encoded with a newer version of Bufferize '{headerVer}'.` ) -- also don't want the version to be greater than WALLY_SEMVER.ver local rootTbl = DataTypes.Encoder:readStream(stream) if next(encoders) then local stack = { rootTbl } while #stack > 0 do local popped = table.remove(stack) :: { [any]: any } for key, value in popped do local newKey = key if typeof(key) == "table" then table.insert(stack, key) elseif DataTypes.Userdata.Userdefined:isTypeOf(key) then local userdefined = DataTypes.Userdata.Userdefined:read(key) local encoder = encoders[userdefined.kind] if encoder then newKey = encoder.read(userdefined.b) end end local newValue = value if typeof(value) == "table" then table.insert(stack, value) elseif DataTypes.Userdata.Userdefined:isTypeOf(value) then local userdefined = DataTypes.Userdata.Userdefined:read(value) local encoder = encoders[userdefined.kind] if encoder then newValue = encoder.read(userdefined.b) end end popped[key] = nil popped[newKey] = newValue end end end return rootTbl end -- Class local EncoderStatic = {} EncoderStatic.VERSION = tostring(WALLY_SEMVER.ver) local EncoderClass = {} EncoderClass.__index = EncoderClass EncoderClass.ClassName = "Encoder" export type Encoder = typeof(setmetatable( {} :: { encoders: { [string]: CustomEncoder<any> }, }, EncoderClass )) function EncoderStatic.new() local self = setmetatable({}, EncoderClass) :: Encoder self.encoders = {} return self end function EncoderStatic.readVersion(b: buffer) local stream = BufferStream.new(b) local length = stream:readu8() local wallyVersion = stream:readString(length) local ver = CargoSemver.Version.parse(wallyVersion) return if ver then tostring(ver) else nil end function EncoderClass.override<T>(self: Encoder, typeOf: string, encoder: CustomEncoder<T>) local definition = DataTypes.Encoder.definitionsByTypeOf[typeOf] if definition then assert(definition:isOverridable(), `Cannot override encoding for the '{typeOf}' type.`) end self.encoders[typeOf] = encoder end function EncoderClass.encode(self: Encoder, ...: Supported) -- we always wrap our inputs in a table b/c it will ensure -- pointers are being used for duplicated tables local packed = table.pack(...) local hasGap = false for i = 1, packed.n do if packed[i] == nil then hasGap = true break end end if not hasGap then local packedAny = packed :: any packedAny.n = nil end return encodeInternal(packed, self.encoders) end function EncoderClass.decode(self: Encoder, b: buffer) local packed = decodeInternal(b, self.encoders) local packedN = packed.n or #packed return table.unpack(packed, 1, packedN) end -- return EncoderStatic
1,665
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/Serializers/Deduplicator.luau
local bufferizeRoot = script.Parent.Parent local DataTypes = require(bufferizeRoot.DataTypes) local TableHelper = require(bufferizeRoot.DataTypes.Helpers.TableHelper) local pointerUserdata = DataTypes.Userdata.DeduplicationPointer local Deduplicator = {} function Deduplicator.serialize(supportedSet: { [any]: boolean }, rootTbl: { [any]: any }): { { [any]: any } } if not next(supportedSet) then return { {}, rootTbl } end local pointerByKV = {} local deduplicatedArr = {} local deduplicatedCount = 0 for kv, _ in supportedSet do deduplicatedCount = deduplicatedCount + 1 deduplicatedArr[deduplicatedCount] = kv pointerByKV[kv] = pointerUserdata:create(deduplicatedCount) end local rootTblCopy = TableHelper.copyDeep(rootTbl, function(kv) return pointerByKV[kv] or kv end) return { deduplicatedArr, rootTblCopy } end function Deduplicator.serializeTypeof(typeOfsSet: { [string]: boolean }, rootTbl: { [any]: any }): { { [any]: any } } if not next(typeOfsSet) then return Deduplicator.serialize({}, rootTbl) end local countByKV = {} TableHelper.replaceKV(rootTbl, function(kv) countByKV[kv] = (countByKV[kv] or 0) + 1 return kv end) local supportedSet = {} for kv, count in countByKV do if typeOfsSet[typeof(kv)] and count > 1 then supportedSet[kv] = true end end return Deduplicator.serialize(supportedSet, rootTbl) end function Deduplicator.deserialize(compressed: { { [any]: any } }) local deduplicatedArr = compressed[1] return TableHelper.copyDeep(compressed[2], function(kv) if pointerUserdata:isTypeOf(kv) then return deduplicatedArr[pointerUserdata:read(kv).index] end return kv end) end return Deduplicator
464
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/Serializers/InstanceSerializer.luau
local ReflectionService = game:GetService("ReflectionService") :: ReflectionService local DataTypes = require(script.Parent.Parent.DataTypes) local pointerUserdata = DataTypes.Userdata.InstancePointer local InstanceSerializer = {} local function shouldSerializeProperty(property: { [string]: any }) return property.Permits and property.Permits.Read and property.Permits.Write and property.Display and not property.Display.DeprecationMessage end function InstanceSerializer.serialize(rootInstance: Instance) local serializedArr = {} local pointerCount = 0 local pointerByInstance = {} local nilPointer = pointerUserdata:create(0) local function assignPointer(instance: Instance) pointerCount = pointerCount + 1 pointerByInstance[instance] = pointerUserdata:create(pointerCount) end assignPointer(rootInstance) for _, descendant in rootInstance:GetDescendants() do assignPointer(descendant) end for instance, pointer in pointerByInstance do local className = instance.ClassName local instanceAny = instance :: any local defaultInstance = Instance.new(className) local defaultInstanceAny = defaultInstance :: any -- technically not a true array b/c mismatched types, but this will encode more efficiently local serialized: { any } = { className } local properties = ReflectionService:GetPropertiesOfClass(className, { Security = SecurityCapabilities.fromCurrent(), ExcludeInherited = false, ExcludeDisplay = false, }) local j = 2 for _, property in properties do local shouldSerialize = shouldSerializeProperty(property) if shouldSerialize and not (instance == rootInstance and property.Name == "Parent") then local success, err = pcall(function() local value = instanceAny[property.Name] local defaultValue = defaultInstanceAny[property.Name] if value ~= defaultValue then if typeof(value) == "Instance" then value = pointerByInstance[value] or nilPointer elseif value == nil then value = nilPointer end serialized[j + 1] = property.Name serialized[j + 2] = value j = j + 2 end end) if not success then warn(err) end end end for attributeName, attributeValue in instance:GetAttributes() do serialized[j + 1] = "$" .. attributeName -- use dollar sign to identify attribute keys serialized[j + 2] = attributeValue j = j + 2 end local k = 0 for _, tagName in instance:GetTags() do k = k + 1 serialized[j + 1 + k] = tagName end defaultInstance:Destroy() serialized[j + 1] = if k > 0 then k else nil serialized[2] = (j - 2) // 2 serializedArr[pointer.value.index] = serialized end return serializedArr end function InstanceSerializer.deserialize(serializedArr: { any }) local instances = {} for i, serialized in serializedArr do local className = serialized[1] local keyValueCount = serialized[2] * 2 local tagCount = serialized[3 + keyValueCount] or 0 local instance = Instance.new(className) local instanceAny = instance :: any local isAttribute = false for j = 1, keyValueCount, 2 do local key = serialized[j + 2] local value = serialized[j + 3] if pointerUserdata:isTypeOf(value) then local pointer = pointerUserdata:read(value) value = instances[pointer.index] end if isAttribute or (typeof(key) == "string" and key:sub(1, 1) == "$") then isAttribute = true instance:SetAttribute(key:sub(2), value) else instanceAny[key] = value end end for j = 1, tagCount do local tagName = serialized[3 + keyValueCount + j] instance:AddTag(tagName) end instances[i] = instance end return instances[1] end return InstanceSerializer
924
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/init.luau
local Encoder = require(script.Encoder) local BufferStream = require(script.BufferStream) local Deduplicator = require(script.Serializers.Deduplicator) local InstanceSerializer = require(script.Serializers.InstanceSerializer) export type Encoder = Encoder.Encoder export type BufferStream = BufferStream.BufferStream export type Supported = Encoder.Supported export type Overridable = Encoder.Overridable local Bufferize = {} local defaultEncoder = Encoder.new() Bufferize.VERSION = Encoder.VERSION Bufferize.readVersion = Encoder.readVersion Bufferize.custom = Encoder.new Bufferize.stream = BufferStream.new Bufferize.deduplicateTypeof = Deduplicator.serializeTypeof Bufferize.deduplicate = Deduplicator.serialize Bufferize.reduplicate = Deduplicator.deserialize Bufferize.serializeInstance = InstanceSerializer.serialize Bufferize.deserializeInstance = InstanceSerializer.deserialize function Bufferize.encode(...: Supported) return defaultEncoder:encode(...) end function Bufferize.decode(b: buffer) return defaultEncoder:decode(b) end return Bufferize
214
imezx/Warp
imezx-Warp-80646ee/src/Client/init.luau
--!optimize 2 --!strict --@EternityDev local Client = {} local RunService = game:GetService("RunService") local Thread = require("./Util/Thread") local Buffer = require("./Util/Buffer") local Replication = require("./Replication") local Event: RemoteEvent = script.Parent:WaitForChild("Event") local UnreliableEvent: UnreliableRemoteEvent = script.Parent:WaitForChild("UnreliableEvent") local deltaT: number, cycle: number = 0, 1 / 61 local writer: Buffer.Writer = Buffer.createWriter() type Connection = { Connected: boolean, Disconnect: (self: Connection) -> (), } type Event = { i: number, c: (Player, ...any?) -> ...any?, } local queueEvent: { { any } } = {} local queueUnreliableEvent: { { any } } = {} local eventListeners: { Event } = {} local eventSchemas: { [number]: Buffer.SchemaType } = {} local pendingInvokes: { [string]: thread } = {} local invokeId = 0 --@optional -- Yields the current thread until the client has successfully initialized and synchronized with the server's replication data (identifier). Its optionally, but highly recommended to call this before firing or connecting to any events to ensure the network is fully ready. Client.awaitReady = Replication.wait_for_ready --@remoteName string --@schema Buffer.SchemaType -- Define a schema for strict data packing on a specific event. Client.useSchema = function(remoteName: string, schema: Buffer.SchemaType) local id = Replication.get_id[remoteName] if not id then warn(`[Warp]: ".useSchema"::"{remoteName}" does not exist, likely its not registered on the server yet.`) return end eventSchemas[id] = schema end --@remoteName string --@fn function -- Connect to an event to receive incoming data from the server. Client.Connect = function(remoteName: string, fn: (Player, ...any?) -> ...any?): Connection local id = Replication.get_id[remoteName] if not id then warn(`[Warp]: ".Connect"::"{remoteName}" does not exist, likely its not registered on the server yet.`) return { Connected = false, Disconnect = function() return end } :: Connection end local detail = { i = id, c = fn, } table.insert(eventListeners, detail) return { Connected = true, Disconnect = function(self: Connection) if not self.Connected then return end self.Connected = false local idx = table.find(eventListeners, detail) if idx then table.remove(eventListeners, idx) end end, } :: Connection end --@remoteName string --@fn function -- Similar to :Connect but automatically disconnects after the first firing. Client.Once = function(remoteName: string, fn: (...any?) -> ()): Connection local connection connection = Client.Connect(remoteName, function(...: any?) if connection then connection:Disconnect() end fn(...) end) return connection end --@remoteName string -- Wait for an event to be triggered. Yields the current thread. Client.Wait = function(remoteName: string): (number, ...any?) local thread, t = coroutine.running(), os.clock() Client.Once(remoteName, function(...: any?) task.spawn(thread, os.clock() - t, ...) end) return coroutine.yield() end --@remoteName string -- Disconnect all connections for a specific event. Client.DisconnectAll = function(remoteName: string) local id = Replication.get_id[remoteName] if not id then return end for idx = #eventListeners, 1, -1 do if eventListeners[idx].i == id then table.remove(eventListeners, idx) end end end --@remoteName string -- Disconnect all connections and remove the event. Client.Destroy = Client.DisconnectAll --@remoteName string --@reliable boolean -- Fire an event to the server. Client.Fire = function(remoteName: string, reliable: boolean, ...: any?) local id = Replication.get_id[remoteName] if id then table.insert(reliable and queueEvent or queueUnreliableEvent, { Replication.get_id[remoteName], { ... } :: any, }) end end --@remoteName string --@timeout number? -- Invoke the server with timeout support. Yields the current thread. Returns nil if timeout occurs. Client.Invoke = function(remoteName: string, timeout: number?, ...: any?): ...any? local id = Replication.get_id[remoteName] if not id then return nil end invokeId += 1 local reqid, thread = `{invokeId}`, coroutine.running() pendingInvokes[reqid] = thread task.delay(timeout or 2, function() local pending = pendingInvokes[reqid] if not pending then return end task.spawn(pending, nil) pendingInvokes[reqid] = nil end) table.insert(queueEvent, { 0, { id, reqid :: any, { ... } :: any } :: any, }) return coroutine.yield() end if RunService:IsClient() then local function processIncoming(b: buffer, ref: { Instance }?, handleInvokes: boolean) if type(b) ~= "buffer" then return end local contents = Buffer.readEvents(b, ref, eventSchemas) for _, content in contents do local remote = content[1] local content = content[2] if handleInvokes then if remote == 0 then local id = content[1] local results = content[2] local pending = pendingInvokes[id] if pending then task.spawn(pending :: any, table.unpack(results)) pendingInvokes[id] = nil end continue end if remote == 1 then if #eventListeners == 0 then continue end local remoteName = content[1] local id = content[2] local args = content[3] for _, connection in eventListeners do if connection.i == remoteName then Thread(function() local results = { connection.c(table.unpack(args)) } table.insert(queueEvent, { 1, { id, results } :: any, }) end) break end end continue end end if #eventListeners == 0 then continue end for _, connection in eventListeners do if connection.i ~= remote then continue end Thread(connection.c, table.unpack(content)) end end end Event.OnClientEvent:Connect(function(b: buffer, ref: { Instance }?) processIncoming(b, ref, true) end) UnreliableEvent.OnClientEvent:Connect(function(b: buffer, ref: { Instance }?) processIncoming(b, ref, false) end) RunService.PostSimulation:Connect(function(d: number) deltaT += d if deltaT < cycle then return end deltaT = 0 -- reliable if #queueEvent > 0 then Buffer.writeEvents(writer, queueEvent, eventSchemas) do local buf, ref = Buffer.buildWithRefs(writer) Buffer.reset(writer) if not ref or #ref == 0 then Event:FireServer(buf) else Event:FireServer(buf, ref) end end table.clear(queueEvent) end -- unreliable if #queueUnreliableEvent > 0 then Buffer.writeEvents(writer, queueUnreliableEvent, eventSchemas) do local buf, ref = Buffer.buildWithRefs(writer) Buffer.reset(writer) if not ref or #ref == 0 then UnreliableEvent:FireServer(buf) else UnreliableEvent:FireServer(buf, ref) end end table.clear(queueUnreliableEvent) end end) end --[[ @class Client @schema define a schema for your data and use a strict packing ]] Client.Schema = Buffer.Schema return Client :: typeof(Client)
1,859
imezx/Warp
imezx-Warp-80646ee/src/Replication/init.luau
--!optimize 2 --!strict local Replication = {} local RunService = game:GetService("RunService") local _repl: RemoteEvent = script.Parent:WaitForChild("_repl") local Buffer = require("./Util/Buffer") local Identifier = require("./Util/Identifier") local identifiers_schema = Buffer.Schema.string local warp_identifier_registry = shared.__warp_identifier_registry if RunService:IsClient() or RunService:IsRunMode() then local pending_id_yields, pending_name_yields, ready_yields = {}, {}, {} local is_ready = false if RunService:IsClient() then _repl.OnClientEvent:Connect(function(b: buffer) if type(b) ~= "buffer" then return end local contents = Buffer.readRepl(b, identifiers_schema) if #contents == 0 then return end for _, content in contents do local id: number, remote: string = content[1], content[2] warp_identifier_registry.cache[remote] = id warp_identifier_registry.name[id] = remote if pending_id_yields[remote] then for _, thread in pending_id_yields[remote] do task.spawn(thread, id) end pending_id_yields[remote] = nil end if pending_name_yields[id] then for _, thread in pending_name_yields[id] do task.spawn(thread, remote) end pending_name_yields[id] = nil end end if not is_ready then is_ready = true for _, thread in ready_yields do task.spawn(thread :: thread) end table.clear(ready_yields) end end) _repl:FireServer() end --@yield -- wait for the identifiers to be replicated from the server Replication.wait_for_ready = function() if is_ready then return end local thread = coroutine.running() table.insert(ready_yields, thread) coroutine.yield() end Replication.get_id = warp_identifier_registry.cache Replication.get_name = warp_identifier_registry.name else local replication_ready: { Player }, pending_replications = {}, {} local writer: Buffer.Writer = Buffer.createWriter() local replication_id: number = Identifier.get_id("id_replication") or 1 local is_scheduled = false if not Identifier.has_name("id_replication") or not replication_id then replication_id = Identifier.get_id("id_replication") or 1 end local function replicateToAll(content: any, id: number?) if #replication_ready == 0 then return end if type(content) == "string" and id then pending_replications[content] = id else for k, v in content :: any do pending_replications[k] = v end end if not is_scheduled then is_scheduled = true task.defer(function() is_scheduled = false local count = 0 for _ in pending_replications do count += 1 end if count == 0 then return end Buffer.writeRepl(writer, pending_replications, count, identifiers_schema) local buf = Buffer.build(writer) Buffer.reset(writer) for _, player: Player in replication_ready do _repl:FireClient(player, buf) end table.clear(pending_replications) end) end end local function replicateTo(player: Player) Buffer.writeRepl(writer, warp_identifier_registry.cache, warp_identifier_registry.counter, identifiers_schema) do local buf = Buffer.build(writer) Buffer.reset(writer) _repl:FireClient(player, buf) end end Identifier.on_added(replicateToAll) _repl.OnServerEvent:Connect(function(player: Player) if table.find(replication_ready, player) then return end table.insert(replication_ready, player) replicateTo(player) end) Replication.remove = function(player: Player) table.remove(replication_ready, table.find(replication_ready, player)) end end return Replication :: typeof(Replication)
917
imezx/Warp
imezx-Warp-80646ee/src/Util/Identifier.luau
--!optimize 2 --!strict --@EternityDev local BITS: number = 8 local MAX_VALUE: number = bit32.lshift(1, BITS) - 1 local hook_fn: (string, number) -> () if not shared.__warp_identifier_registry then shared.__warp_identifier_registry = { cache = {} :: { [string]: number }, name = {} :: { [number]: string }, counter = 0, } end local registry = shared.__warp_identifier_registry local function fastAssert(condition: boolean, ...: any) if not condition then error(...) end end local Identifier = {} Identifier.on_added = function(fn: (string, number) -> ()) assert(hook_fn == nil, ".on_added can only be called once.") hook_fn = fn end Identifier.has_name = function(name: string): boolean return registry.cache[name] ~= nil end Identifier.has_id = function(id: number): boolean return registry.name[id] ~= nil end Identifier.get_id = function(name: string): number local cached = registry.cache[name] if cached then return cached end local id = registry.counter + 1 fastAssert(id <= MAX_VALUE, `Identifier overflow: exceeded {MAX_VALUE + 1} unique names.`) registry.counter = id registry.cache[name] = id registry.name[id] = name if hook_fn then task.defer(hook_fn, name, id) end return id end Identifier.get_name = function(id: number): string return registry.name[id] end return Identifier :: typeof(Identifier)
355
imezx/Warp
imezx-Warp-80646ee/src/Util/Thread.luau
--!strict --!optimize 2 --@EternityDev local thread: thread? local function passer<T...>(func: (T...) -> (), ...: T...): () local HoldThread: thread = thread :: thread thread = nil func(...) thread = HoldThread end local function newThread(): () thread = coroutine.running() while true do passer(coroutine.yield()) end end return function<T...>(func: (T...) -> (), ...: T...): () if not thread then task.spawn(newThread) end task.spawn(thread :: thread, func, ...) end
128
imezx/Warp
imezx-Warp-80646ee/src/init.luau
--!strict --@EternityDev local Remote = {} if game.RunService:IsServer() then if not script:FindFirstChild("_repl") then Instance.new("RemoteEvent", script).Name = "_repl" end if not script:FindFirstChild("Event") then Instance.new("RemoteEvent", script).Name = "Event" end if not script:FindFirstChild("UnreliableEvent") then Instance.new("UnreliableRemoteEvent", script).Name = "UnreliableEvent" end if not script:FindFirstChild("Function") then Instance.new("RemoteFunction", script).Name = "Function" end end local Client = require("@self/Client") local Server = require("@self/Server") local Buffer = require("@self/Util/Buffer") --[[ @class Remote @client ]] Remote.Client = function() return Client end --[[ @class Remote @server ]] Remote.Server = function() return Server end --[[ @class Remote @schema define a schema for your data and use a strict packing ]] Remote.Buffer = Buffer return Remote :: typeof(Remote)
256
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/examples/AES.luau
--[[ Cryptography library: Advanced Encryption Standard (Galois/Counter Mode) Security Limitations: Personally don't really like AES-GCM as it has a 96-bit nonce which creates birthday bound issues after 2^32 encryptions with the same key, collision probability reaches 2^-32 (NIST's "soft" birthday bound). Which is why I prefer ChaCha20-Poly1305 but you could rotate keys often. AES-GCM is also not key committing meaning the same ciphertext can decrypt to different plaintexts under different keys with valid authentication tags. This is the "Invisible Salamander" attack, where an attacker has a message that appears normal to moderators but evil to recievers, or vice versa. Affects group messaging, and any scenario with multiple valid keys. The S-box lookup tables are vulnerable to cache timing attacks in theory, but constant time implementations would kill performance. And it's not really possible in Roblox in the first place. https://bearssl.org/constanttime.html IV Handling: - Store IV alongside ciphertext (IVs are not secret) - You can send IV with encrypted data - Never reuse IV with same key (this breaks the security) - Consider key rotation after 2^32 operations to avoid birthday attacks --]] --!strict local ReplicatedStorage = game:GetService("ReplicatedStorage") -- Get the libraries local Cryptography = require(ReplicatedStorage:WaitForChild("Cryptography")) local AES = Cryptography.Encryption.AES local CSPRNG = Cryptography.Utilities.CSPRNG local Key = CSPRNG.RandomBytes(32) local IV = CSPRNG.RandomBytes(12) local Message = "This is a secret message" local Plaintext = buffer.fromstring(Message) -- Optional: Additional Authenticated Data (authenticated but not encrypted) local AAD = buffer.fromstring("user:john,timestamp:456745683") local Ciphertext, Tag = AES.Encrypt(Plaintext, Key, IV, AAD) print("Encryption successful!") print("Ciphertext length:", buffer.len(Ciphertext)) print("Tag length:", buffer.len(Tag)) -- Decrypt and verify (returns false on failure, true and buffer on success) local Success, DecryptedData = AES.Decrypt(Ciphertext, Key, IV, Tag, AAD) if Success and DecryptedData then local DecryptedMessage = buffer.tostring(DecryptedData) print("Decryption successful!") print("Original message:", Message) print("Decrypted message:", DecryptedMessage) print("Messages match:", Message == DecryptedMessage) else warn("Decryption failed, data was messed with!") end
597
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/examples/Batch.luau
--[=[ Cryptography library: EdDSA Batch Verification Efficient Verification of Multiple Signatures This example shows how u can batch verification of multiple Ed25519 signatures. Batch verification is more efficient than verifying signatures individually when you need to validate many signatures at once. --]=] --!strict local ReplicatedStorage = game:GetService("ReplicatedStorage") local Cryptography = require(ReplicatedStorage:WaitForChild("Cryptography")) local EdDSA = Cryptography.Verification.EdDSA local CSPRNG = Cryptography.Utilities.CSPRNG -- Generate multiple keypairs (different signers) local Signer1Private = CSPRNG.Ed25519Random() local Signer1Public = EdDSA.PublicKey(Signer1Private) local Signer2Private = CSPRNG.Ed25519Random() local Signer2Public = EdDSA.PublicKey(Signer2Private) local Signer3Private = CSPRNG.Ed25519Random() local Signer3Public = EdDSA.PublicKey(Signer3Private) -- Create messages and sign them local Message1 = buffer.fromstring("Transaction: Alice sends 100 to Bob") local Message2 = buffer.fromstring("Transaction: Bob sends 50 to Charlie") local Message3 = buffer.fromstring("Transaction: Charlie sends 25 to Dave") local Signature1 = EdDSA.Sign(Message1, Signer1Private, Signer1Public) local Signature2 = EdDSA.Sign(Message2, Signer2Private, Signer2Public) local Signature3 = EdDSA.Sign(Message3, Signer3Private, Signer3Public) -- Batch verification: verify all signatures at once local Entries = { { Message = Message1, PublicKey = Signer1Public, Signature = Signature1 }, { Message = Message2, PublicKey = Signer2Public, Signature = Signature2 }, { Message = Message3, PublicKey = Signer3Public,Signature = Signature3 }, } -- One of the drawbacks is that you do not know which sgnature failed and have to throw out the whole batch local AllValid = EdDSA.VerifyBatch(Entries) if AllValid then print("All signatures verified successfully") else print("Batch verification failed at least one signature is invalid") end -- Show that batch fails if any signature is tampered local TamperedSignature = buffer.create(64) buffer.copy(TamperedSignature, 0, Signature3, 0, 64) buffer.writeu8(TamperedSignature, 0, bit32.bxor(buffer.readu8(TamperedSignature, 0), 0x01)) local TamperedEntries = { { Message = Message1, PublicKey = Signer1Public, Signature = Signature1 }, { Message = Message2, PublicKey = Signer2Public, Signature = Signature2 }, { Message = Message3, PublicKey = Signer3Public, Signature = TamperedSignature }, } local TamperedValid = EdDSA.VerifyBatch(TamperedEntries) assert(TamperedValid == false, "Tampered batch should fail verification") print("Batch verification completed")
644
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/examples/CSPRNG.luau
--[[ Cryptography library: CSPRNG Example ]]-- --!strict local ReplicatedStorage = game:GetService("ReplicatedStorage") -- Get the library local Cryptography = require(ReplicatedStorage:WaitForChild("Cryptography")) local CSPRNG = Cryptography.Utilities.CSPRNG -- Also accessible through EdDSA, MLKEM andMLDSA: Verification.EdDSA/MLKEM/MLDSA.CSPRNG --[[ CSPRNG stands for: Cryptographically Secure Pseudo Random Number Generator CSPRNG works by creating entropy out of various factors then using the entropy as the internal state of the RNG To generate random numbers, CSPRNG creates a 64 byte block of random data and takes however many bytes is needed for the output data i.e 8 bytes for a float/integer, 20 bytes for a 20 character long string. Once all 64 bytes are used up, an another block is generated which may slow down the call. The generated block can be extended to an arbitrary length with Blake3 by enabling CSPRNG.BlockExpansion Developers can renew the state and add their own entropy by passing it as a buffer in CSRNG.Reseed/CSPRNG.AddEntropyProvider CSPRNG will also automatically renew the state after a certain amount of calls controlled by CSRNG.RekeyAfter (by default 1024, so 64 * 1024 bytes without block expansion) --]] -- Generate a random number between 0 and 1 print(CSPRNG.Random()) -- Generate a random number between 10 and 100 print(CSPRNG.RandomNumber(10, 100)) -- Generate a random number between 0 and 100 print(CSPRNG.RandomNumber(100)) -- Generate a random key for EdDSA local PrivateKey = CSPRNG.Ed25519Random() --[[ Reseed the CSPRNG instance with custom entropy for extra security You can pass any buffer as long as it's 1024 bytes or less, althought not all of it may be used as the normal entropy is added first, custom has last priority You can also use CSPRNG.AddEntropyProvider to add a function that returns a buffer AddEntropyProvider will only be called once its used up all the entropy from init So you need to do `CSPRNG.Reseed(CustomEntropy())` if you want it from the gecko ]] local LastPlayerWeaponUse = 12317127.123 local AmountOfRemoteCalls = 1282 local CustomEntropy = buffer.create(8 + 4) buffer.writef64(CustomEntropy, 0, LastPlayerWeaponUse) -- 8 bytes buffer.writeu32(CustomEntropy, 8, AmountOfRemoteCalls) -- 4 bytes local Provider = function() return CustomEntropy end CSPRNG.AddEntropyProvider(Provider) CSPRNG.RemoveEntropyProvider(Provider) CSPRNG.Reseed(CustomEntropy)
645
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/examples/ForwardSecrecy.luau
--[=[ Cryptography library: Ephemeral X25519 Key Exchange Forward Secrecy - Client to Server Key Exchange with Ephemeral Keys This example shows how to do proper ephemeral key exchange that provides forward secrecy. Fresh private keys are generated each session and destroyed after use. Even if long-term keys are compromised, past communications remain secure. --]=] --!strict local ReplicatedStorage = game:GetService("ReplicatedStorage") -- Get the library local Cryptography = require(ReplicatedStorage:WaitForChild("Cryptography")) -- Create variables for easy access local Blake3 = Cryptography.Hashing.Blake3 local FromHex = Cryptography.Utilities.Conversions.FromHex local EdDSA = Cryptography.Verification.EdDSA local AEAD = Cryptography.Encryption.AEAD local CSPRNG = Cryptography.Utilities.CSPRNG -- Long-term identity keys (persistent across sessions) local ClientIdentityPrivate = CSPRNG.Ed25519Random() local ClientIdentityPublic = EdDSA.PublicKey(ClientIdentityPrivate) local ServerIdentityPrivate = CSPRNG.Ed25519Random() local _ServerIdentityPublic = EdDSA.PublicKey(ServerIdentityPrivate) -- *Client and server exchange identity public keys* local function GetSessionKey(EphemeralSharedSecret: buffer, ClientPublic: buffer, ServerPublic: buffer): buffer local CombinedInput = buffer.create(96) buffer.copy(CombinedInput, 0, EphemeralSharedSecret, 0, 32) buffer.copy(CombinedInput, 32, ClientPublic, 0, 32) buffer.copy(CombinedInput, 64, ServerPublic, 0, 32) local KeyMaterial = Blake3.Digest(CombinedInput, 32) return FromHex(KeyMaterial) end -- SESSION 1: Generate fresh ephemeral keys local ClientEphemeralPrivate1 = CSPRNG.Ed25519Random() local ClientEphemeralPublic1 = EdDSA.PublicKey(ClientEphemeralPrivate1) local ServerEphemeralPrivate1 = CSPRNG.Ed25519Random() local ServerEphemeralPublic1 = EdDSA.PublicKey(ServerEphemeralPrivate1) -- *Ephemeral public keys are exchanged* -- Both sides derive the same session key from ephemeral exchange -- Note: In real implementation, use proper X25519.Exchange(ClientEphemeralPrivate1, ServerEphemeralPublic1) local SharedSecret1 = CSPRNG.RandomBytes(32) -- Simulated shared secret local SessionKey1 = GetSessionKey(SharedSecret1, ClientEphemeralPublic1, ServerEphemeralPublic1) -- Encrypt with ephemeral session key local Message1 = buffer.fromstring("Session 1 data") local Nonce1 = buffer.fromstring("nonce1234567") local Encrypted1, Tag1 = AEAD.Encrypt(Message1, SessionKey1, Nonce1) -- Overwrite ephemeral private keys (the actual forward secrecy) ClientEphemeralPrivate1 = buffer.create(0) ServerEphemeralPrivate1 = buffer.create(0) -- SESSION 2: Generate completely new ephemeral keys local ClientEphemeralPrivate2 = CSPRNG.Ed25519Random() local ClientEphemeralPublic2 = EdDSA.PublicKey(ClientEphemeralPrivate2) local ServerEphemeralPrivate2 = CSPRNG.Ed25519Random() local ServerEphemeralPublic2 = EdDSA.PublicKey(ServerEphemeralPrivate2) -- Derive different session key for session 2 local SharedSecret2 = CSPRNG.RandomBytes(32) -- Different shared secret local SessionKey2 = GetSessionKey(SharedSecret2, ClientEphemeralPublic2, ServerEphemeralPublic2) -- Encrypt new message local Message2 = buffer.fromstring("Session 2 data") local Nonce2 = buffer.fromstring("nonce7654321") local Encrypted2, Tag2 = AEAD.Encrypt(Message2, SessionKey2, Nonce2) -- Destroy second session ephemeral keys ClientEphemeralPrivate2 = buffer.create(0) ServerEphemeralPrivate2 = buffer.create(0) -- Authentication: Sign ephemeral public keys with long-term identity keys local EphemeralSignature = EdDSA.Sign(ClientEphemeralPublic2, ClientIdentityPrivate, ClientIdentityPublic) local SignatureValid = EdDSA.Verify(ClientEphemeralPublic2, ClientIdentityPublic, EphemeralSignature) -- Verify decryption works local Decrypted1 = AEAD.Decrypt(Encrypted1, SessionKey1, Nonce1, Tag1) local Decrypted2 = AEAD.Decrypt(Encrypted2, SessionKey2, Nonce2, Tag2) assert(Decrypted1 and buffer.tostring(Decrypted1) == "Session 1 data") assert(Decrypted2 and buffer.tostring(Decrypted2) == "Session 2 data") assert(SignatureValid) print("Forward secrecy key exchange completed")
1,040
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/examples/MlDSA.luau
--!strict local ReplicatedStorage = game:GetService("ReplicatedStorage") -- Get the library local Cryptography = require(ReplicatedStorage:WaitForChild("Cryptography")) local MLDSA = Cryptography.Verification.MlDSA local CSPRNG = Cryptography.Utilities.CSPRNG --[[ ML-DSA stands for: Module-Lattice-based Digital Signature Algorithm ML-DSA is a post-quantum digital signature scheme standardized in NIST FIPS 204. It provides three security levels and supports both deterministic and hedged (randomized) signing. Hedged signing uses 32 bytes of randomness for enhanced security. Context can be used for domain separation (max 255 bytes). --]] -- Generate key pair local PubKey, SecKey = MLDSA.ML_DSA_44.GenerateKeys() -- Sign message with hedged signing (recommended) local Message = buffer.fromstring("Hello, post-quantum world!") local Context = buffer.create(0) -- Empty context local Randomness = CSPRNG.RandomBytes(32) local Signature = buffer.create(MLDSA.ML_DSA_44.SigByteLen) local SignSuccess = MLDSA.ML_DSA_44.Sign(Message, Randomness, SecKey, Context, Signature) if not SignSuccess then error("Signing failed") end -- Verify signature local Valid = MLDSA.ML_DSA_44.Verify(Message, PubKey, Context, Signature) print("Signature valid:", Valid) -- Deterministic signing (zero randomness) local DetRandom = buffer.create(32) local DetSig = buffer.create(MLDSA.ML_DSA_44.SigByteLen) MLDSA.ML_DSA_44.Sign(Message, DetRandom, SecKey, Context, DetSig) -- Context example local ContextData = buffer.fromstring("game-session") local CtxSig = buffer.create(MLDSA.ML_DSA_44.SigByteLen) MLDSA.ML_DSA_44.Sign(Message, CSPRNG.RandomBytes(32), SecKey, ContextData, CtxSig) local CtxValid = MLDSA.ML_DSA_44.Verify(Message, PubKey, ContextData, CtxSig) print("Context signature valid:", CtxValid) -- Different security levels local Pub65, Sec65 = MLDSA.ML_DSA_65.GenerateKeys() local Pub87, Sec87 = MLDSA.ML_DSA_87.GenerateKeys() -- Key and signature sizes print("ML-DSA-44 sizes:", buffer.len(PubKey), buffer.len(SecKey), buffer.len(Signature)) print("ML-DSA-65 sizes:", buffer.len(Pub65), buffer.len(Sec65), MLDSA.ML_DSA_65.SigByteLen) print("ML-DSA-87 sizes:", buffer.len(Pub87), buffer.len(Sec87), MLDSA.ML_DSA_87.SigByteLen) -- Quite big
625
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/examples/MlKEM.luau
--!strict local ReplicatedStorage = game:GetService("ReplicatedStorage") -- Get the library local Cryptography = require(ReplicatedStorage:WaitForChild("Cryptography")) local MlKem = Cryptography.Verification.MlKEM local CSPRNG = Cryptography.Utilities.CSPRNG --[[ ML-KEM stands for: Module-Lattice-based Key Encapsulation Mechanism ML-KEM is a post-quantum key encapsulation method from NIST FIPS 203. It allows two parties to establish a shared 32 byte secret that can be used for symmetric encryption. ML-KEM needs two 32 byte seeds for key generation and does encapsulation with a 32 byte message to create a ciphertext and shared secret. The recipient uses their secret key to decapsulate and recover the same shared secret. --]] -- Generate keypair using required seeds local SeedD = CSPRNG.RandomBytes(32) local SeedZ = CSPRNG.RandomBytes(32) local PublicKey, SecretKey = MlKem.MLKEM_768.KeyGen(SeedD, SeedZ) --[[ ValidateDecapsulationKey checks the integrity of a decapsulation key. The decapsulation key contains an embedded copy of the public key and a hash of that public key. This function recomputes the hash and verifies it matches the stored hash, detecting any corruption or tampering. Per FIPS 203 Section 7.3, this check doesn't need to run on every decapsulation. You can call it once when: - Loading a key from storage - Receiving a key from another source - After key generation (optional, as freshly generated keys are valid) Returns true if the key is valid, false if corrupted/tampered. --]] local IsKeyValid = MlKem.MLKEM_768.ValidateDecapsulationKey(SecretKey) if not IsKeyValid then error("Decapsulation key failed integrity check") end -- Encapsulate with 32-byte message local Message = CSPRNG.RandomBytes(32) local Ciphertext, SharedSecret = MlKem.MLKEM_768.Encapsulate(Message, PublicKey) if not Ciphertext or not SharedSecret then error("Encapsulation failed") end -- Decapsulate to recover shared secret local RecoveredSecret = MlKem.MLKEM_768.Decapsulate(Ciphertext, SecretKey) -- Verify secrets match print("Success:", MlKem.SecretsEqual(SharedSecret, RecoveredSecret)) -- Different security levels local Pub512, Sec512 = MlKem.MLKEM_512.KeyGen(CSPRNG.RandomBytes(32), CSPRNG.RandomBytes(32)) local Pub1024, Sec1024 = MlKem.MLKEM_1024.KeyGen(CSPRNG.RandomBytes(32), CSPRNG.RandomBytes(32)) -- Key sizes print("ML-KEM-512 sizes:", buffer.len(Pub512), buffer.len(Sec512)) print("ML-KEM-768 sizes:", buffer.len(PublicKey), buffer.len(SecretKey)) print("ML-KEM-1024 sizes:", buffer.len(Pub1024), buffer.len(Sec1024)) -- Quite big
702
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/examples/Password.luau
--[=[ Password Storage System using BLAKE3 This system uses BLAKE3 for password hashing instead of Argon2id. Idea: Argon2id intentionally slows down each hash to make brute force attacks expensive. This is needed when users choose their own passwords, as human chosen passwords are predictable and exist in a searchable space even with strict requirements. However, my idea takes a different approach: passwords are generated using a cryptographically secure random number generator (CSPRNG), creating truly random 24+ character passwords from a 94 character charset. This creates a search space of 94^24 ≈ 10^47 possibilities, computationally infeasible to brute force no matter hashing speed. With CSPRNG-generated passwords: - No dictionary attacks possible (no human patterns) - No need for expensive key derivation functions - BLAKE3's speed becomes an advantage - Users store passwords in their password manager (1Password, Bitwarden, etc.) Password Requirements: - Minimum 24 characters (CSPRNG-generated) - Maximum 128 characters Usage: local GeneratedPassword = GenerateSecurePassword(24) -- App generates this locally -- User stores GeneratedPassword in their password manager local Hash, Salt = CreatePasswordHash(GeneratedPassword) local IsValid = VerifyPassword(GeneratedPassword, Hash, Salt) --]=] --!strict --!optimize 2 --!native local ReplicatedStorage = game:GetService("ReplicatedStorage") local Cryptography = require(ReplicatedStorage:WaitForChild("Cryptography")) local BLAKE3 = Cryptography.Hashing.Blake3 local CSPRNG = Cryptography.Utilities.CSPRNG local Conversions = Cryptography.Utilities.Conversions type PasswordValidationResult = { Valid: boolean, Errors: {string} } type StoredPassword = { Hash: buffer, Salt: buffer, CreatedAt: number } local MIN_LENGTH = 24 local MAX_LENGTH = 128 local SALT_SIZE = 32 local HASH_SIZE = 32 local MIN_UNPREDICTABILITY = 6.0 local SPECIAL_CHARS = "!@#$%^&*()_+-=[]{}|;:,.<>?" local function GenerateRandomSalt(): buffer return CSPRNG.RandomBytes(SALT_SIZE) end local function ConstantTimeEquals(Buffer1: buffer, Buffer2: buffer, Length: number): boolean local Result = 0 for I = 0, Length - 1 do local Byte1 = buffer.readu8(Buffer1, I) local Byte2 = buffer.readu8(Buffer2, I) Result = bit32.bor(Result, bit32.bxor(Byte1, Byte2)) end return Result == 0 end local function CreatePasswordHash(Password: string): (buffer, buffer) local Salt = GenerateRandomSalt() local PasswordBuffer = buffer.fromstring(Password) local Combined = buffer.create(SALT_SIZE + #Password) buffer.copy(Combined, 0, Salt, 0, SALT_SIZE) buffer.copy(Combined, SALT_SIZE, PasswordBuffer, 0, #Password) local _, Hash = BLAKE3.Digest(Combined) return Hash, Salt end local function VerifyPassword(Password: string, StoredHash: buffer, Salt: buffer): boolean local PasswordBuffer = buffer.fromstring(Password) local Combined = buffer.create(SALT_SIZE + #Password) buffer.copy(Combined, 0, Salt, 0, SALT_SIZE) buffer.copy(Combined, SALT_SIZE, PasswordBuffer, 0, #Password) local _, ComputedHash = BLAKE3.Digest(Combined) return ConstantTimeEquals(ComputedHash, StoredHash, HASH_SIZE) end local function CreateStoredPassword(Password: string): StoredPassword local Hash, Salt = CreatePasswordHash(Password) return { Hash = Hash, Salt = Salt, CreatedAt = os.time() } end return { CreatePasswordHash = CreatePasswordHash, VerifyPassword = VerifyPassword, CreateStoredPassword = CreateStoredPassword, }
894
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/scripts/run-tests.server.luau
local ReplicatedStorage = game:GetService("ReplicatedStorage") local Cryptography = ReplicatedStorage:WaitForChild("Cryptography") local Tests = Cryptography.Testing for _, Test: ModuleScript in Tests:GetChildren() do require(Test) end return nil
57
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Checksums/Adler.luau
--[=[ Cryptography library: Adler Return type: number Example Usage: local Message = buffer.fromstring("Hello World") local Hash = Adler(Message) --]=] --!strict --!optimize 2 --!native local function Adler(Message: buffer): number local MOD_ALDER = 65522 local Sum = bit32.band(bit32.rshift(MOD_ALDER, 16), 0xffff) MOD_ALDER = bit32.band(MOD_ALDER, 0xffff) local MessageLength = buffer.len(Message) if MessageLength == 1 then MOD_ALDER += buffer.readu8(Message, 0) if MOD_ALDER >= 65521 then MOD_ALDER -= 65521 end Sum += MOD_ALDER if Sum >= 65521 then Sum -= 65521 end return bit32.bor(MOD_ALDER, bit32.lshift(Sum, 16)) end if MessageLength == 0 then return 0x1 end local BufferPointer = 0 if MessageLength < 16 then while MessageLength > 0 do local Value = buffer.readu8(Message, BufferPointer) MOD_ALDER += Value Sum += MOD_ALDER BufferPointer += 1 MessageLength -= 1 end if MOD_ALDER >= 65521 then MOD_ALDER -= 65521 end Sum %= 65521 return bit32.bor(MOD_ALDER, bit32.lshift(Sum, 16)) end local NMAX = 5552 while MessageLength >= NMAX do MessageLength -= NMAX local Iters = NMAX / 16 while Iters > 0 do Iters -= 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 end end if MessageLength > 0 then while MessageLength >= 16 do MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MessageLength -= 16 end while MessageLength > 0 do MOD_ALDER += buffer.readu8(Message, BufferPointer) Sum += MOD_ALDER BufferPointer += 1 MessageLength -= 1 end MOD_ALDER %= 65521 Sum %= 65521 end return bit32.bor(MOD_ALDER, bit32.lshift(Sum, 16)) end return Adler
1,493
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Checksums/CRC32.luau
--[=[ Cryptography library: CRC32 Function can return JAM or ISO-HDLC CRC32 checksums. Return type: number in regular mode, string in hex mode Example Usage: local Message = buffer.fromstring("Hello World") --------Usage Case 1-------- local Hash = CRC32(Message) --------Usage Case 2-------- local Hash = CRC32(Message, "Jam") --------Usage Case 3-------- local Hash = CRC32(Message, "Jam", true) --]=] --!strict --!optimize 2 --!native local CRC32_LOOKUP = table.create(256) :: {number} for Index = 0, 255 do local CRC = Index for _ = 1, 8 do if bit32.band(CRC, 1) == 1 then CRC = bit32.bxor(bit32.rshift(CRC, 1), 0xEDB88320) else CRC = bit32.rshift(CRC, 1) end end CRC32_LOOKUP[Index + 1] = CRC end local function CRC32(Message: buffer, Mode: "Jam" | "Iso"?, Hex: boolean?): number | string local Lookup = CRC32_LOOKUP local Hash = 0xFFFFFFFF local Leftover = buffer.len(Message) % 4 for Index = 0, Leftover - 1 do local Value = buffer.readu8(Message, Index) local TableIndex = bit32.band(bit32.bxor(Hash, Value), 0xFF) + 1 Hash = bit32.bxor( Lookup[TableIndex], bit32.rshift(Hash, 8) ) end for Index = Leftover, buffer.len(Message) - 1, 4 do local TableIndex = bit32.band(bit32.bxor(Hash, buffer.readu8(Message, Index)), 0xFF) + 1 Hash = bit32.bxor(Lookup[TableIndex], bit32.rshift(Hash, 8)) TableIndex = bit32.band(bit32.bxor(Hash, buffer.readu8(Message, Index + 1)), 0xFF) + 1 Hash = bit32.bxor(Lookup[TableIndex], bit32.rshift(Hash, 8)) TableIndex = bit32.band(bit32.bxor(Hash, buffer.readu8(Message, Index + 2)), 0xFF) + 1 Hash = bit32.bxor(Lookup[TableIndex], bit32.rshift(Hash, 8)) TableIndex = bit32.band(bit32.bxor(Hash, buffer.readu8(Message, Index + 3)), 0xFF) + 1 Hash = bit32.bxor(Lookup[TableIndex], bit32.rshift(Hash, 8)) end if Mode == "Jam" then return Hex == true and string.format("%08x", Hash) or Hash end Hash = bit32.bxor(Hash, 0xFFFFFFFF) return Hex == true and string.format("%08x", Hash) or Hash end return CRC32
695
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Checksums/init.luau
--!strict local Algorithms = table.freeze({ CRC32 = require("@self/CRC32"), Adler = require("@self/Adler") }) return Algorithms
35
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Encryption/AEAD/ChaCha.luau
--[=[ Cryptography library: ChaCha20 Sizes: Nonce: 12/24 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 = ChaCha.ChaCha20(Data, Key, Nonce) --------Usage Case 2-------- local LongNonce = buffer.fromstring(string.rep("n", 24)) local Encrypted = ChaCha.XChaCha20(Data, Key, LongNonce) --]=] --!strict --!optimize 2 --!native local ChaCha = {} local DWORD = 4 local BLOCK_SIZE = 64 local STATE_SIZE = 16 local CHACHA20_NONCE_SIZE = 12 local XCHACHA20_NONCE_SIZE = 24 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, 2 do 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) 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 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 function ChaCha.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) local Leftover = BytesToProcess % 4 for Index = 0, BytesToProcess - Leftover - 1, 4 do local DataWord = buffer.readu32(Data, DataOffset + Index) local KeystreamWord = buffer.readu32(State, Index) buffer.writeu32(Output, DataOffset + Index, bit32.bxor(DataWord, KeystreamWord)) end for Index = BytesToProcess - Leftover, 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 function ChaCha.HChaCha20(Key: buffer, Nonce: buffer, Rounds: number?) : buffer 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 ~= 16 then error(`HChaCha20 requires a 16-byte nonce, got {NonceLength} bytes`, 2) 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 BlockRounds = Rounds or 20 local Key32: buffer if KeyLength == CHACHA20_KEY_SIZE_32 then Key32 = Key else Key32 = buffer.create(32) buffer.copy(Key32, 0, Key, 0, 16) buffer.copy(Key32, 16, Key, 0, 16) end local Constants = (buffer.len(Key32) == 32) and SIGMA_CONSTANTS or TAU_CONSTANTS local State = buffer.create(STATE_SIZE * DWORD) buffer.copy(State, 0, Constants, 0, 16) buffer.copy(State, 16, Key32, 0, 16) buffer.copy(State, 32, Key32, 16, 16) buffer.copy(State, 48, Nonce, 0, 16) 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(State, 0), buffer.readu32(State, 4), buffer.readu32(State, 8), buffer.readu32(State, 12), buffer.readu32(State, 16), buffer.readu32(State, 20), buffer.readu32(State, 24), buffer.readu32(State, 28), buffer.readu32(State, 32), buffer.readu32(State, 36), buffer.readu32(State, 40), buffer.readu32(State, 44), buffer.readu32(State, 48), buffer.readu32(State, 52), buffer.readu32(State, 56), buffer.readu32(State, 60) for Round = 1, BlockRounds 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 local Subkey = buffer.create(32) buffer.writeu32(Subkey, 0, S0) buffer.writeu32(Subkey, 4, S1) buffer.writeu32(Subkey, 8, S2) buffer.writeu32(Subkey, 12, S3) buffer.writeu32(Subkey, 16, S12) buffer.writeu32(Subkey, 20, S13) buffer.writeu32(Subkey, 24, S14) buffer.writeu32(Subkey, 28, S15) return Subkey end function ChaCha.XChaCha20(Data: buffer, Key: buffer, Nonce: buffer, Counter: number?, Rounds: number?) : buffer 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 ~= XCHACHA20_NONCE_SIZE then error(`XChaCha20 requires a 24-byte nonce, got {NonceLength} bytes`, 2) end local Subkey = ChaCha.HChaCha20(Key, (function() local N = buffer.create(16) buffer.copy(N, 0, Nonce, 0, 16) return N end)(), Rounds) local ChaNonce = buffer.create(12) buffer.copy(ChaNonce, 4, Nonce, 16, 8) return ChaCha.ChaCha20(Data, Subkey, ChaNonce, Counter, Rounds) end return ChaCha
5,680
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Encryption/AEAD/Poly1305.luau
--[=[ Cryptography library: Poly1305 Sizes: Key: 32 bytes Tag: 16 bytes Return type: buffer Example usage: local Message = buffer.fromstring("Hello World") local Key = buffer.fromstring(string.rep("k", 32)) local Tag = Poly1305(Message, Key) --]=] --!strict --!optimize 2 --!native local TAG_SIZE = 16 local BLOCK_SIZE = 16 local POLY1305_KEY_SIZE = 32 local function ProcessMessage(Message: buffer, Key: buffer): buffer local MessageLength = buffer.len(Message) local PaddedMessage = Message local ProcessLength = MessageLength if MessageLength % BLOCK_SIZE ~= 0 or MessageLength == 0 then local PaddingSize = BLOCK_SIZE - (MessageLength % BLOCK_SIZE) ProcessLength = MessageLength + PaddingSize PaddedMessage = buffer.create(ProcessLength) buffer.copy(PaddedMessage, 0, Message, 0, MessageLength) buffer.writeu8(PaddedMessage, MessageLength, 1) end local PartialBlockLength = MessageLength - 15 local R0 = buffer.readu32(Key, 0) % (2 ^ 28) local R1 = bit32.band(buffer.readu32(Key, 4), 0x0FFFFFFC) % (2 ^ 28) * (2 ^ 32) local R2 = bit32.band(buffer.readu32(Key, 8), 0x0FFFFFFC) % (2 ^ 28) * (2 ^ 64) local R3 = bit32.band(buffer.readu32(Key, 12), 0x0FFFFFFC) % (2 ^ 28) * (2 ^ 96) local R0Low = R0 % (2 ^ 18) local R0High = R0 - R0Low local R1Low = R1 % (2 ^ 50) local R1High = R1 - R1Low local R2Low = R2 % (2 ^ 82) local R2High = R2 - R2Low local R3Low = R3 % (2 ^ 112) local R3High = R3 - R3Low local S1 = 5 / (2 ^ 130) * R1 local S2 = 5 / (2 ^ 130) * R2 local S3 = 5 / (2 ^ 130) * R3 local S1Low = S1 % (2 ^ -80) local S1High = S1 - S1Low local S2Low = S2 % (2 ^ -48) local S2High = S2 - S2Low local S3Low = S3 % (2 ^ -16) local S3High = S3 - S3Low local Accumulator0, Accumulator1, Accumulator2, Accumulator3 = 0, 0, 0, 0 local Accumulator4, Accumulator5, Accumulator6, Accumulator7 = 0, 0, 0, 0 for BlockOffset = 0, ProcessLength - 1, BLOCK_SIZE do local MessageBlock0 = buffer.readu32(PaddedMessage, BlockOffset) local MessageBlock1 = buffer.readu32(PaddedMessage, BlockOffset + 4) local MessageBlock2 = buffer.readu32(PaddedMessage, BlockOffset + 8) local MessageBlock3 = buffer.readu32(PaddedMessage, BlockOffset + 12) local X0 = Accumulator0 + Accumulator1 + MessageBlock0 local X2 = Accumulator2 + Accumulator3 + MessageBlock1 * (2 ^ 32) local X4 = Accumulator4 + Accumulator5 + MessageBlock2 * (2 ^ 64) local X6 = Accumulator6 + Accumulator7 + MessageBlock3 * (2 ^ 96) if BlockOffset < PartialBlockLength then X6 = X6 + (2 ^ 128) end Accumulator0 = X0 * R0Low + X2 * S3Low + X4 * S2Low + X6 * S1Low Accumulator1 = X0 * R0High + X2 * S3High + X4 * S2High + X6 * S1High Accumulator2 = X0 * R1Low + X2 * R0Low + X4 * S3Low + X6 * S2Low Accumulator3 = X0 * R1High + X2 * R0High + X4 * S3High + X6 * S2High Accumulator4 = X0 * R2Low + X2 * R1Low + X4 * R0Low + X6 * S3Low Accumulator5 = X0 * R2High + X2 * R1High + X4 * R0High + X6 * S3High Accumulator6 = X0 * R3Low + X2 * R2Low + X4 * R1Low + X6 * R0Low Accumulator7 = X0 * R3High + X2 * R2High + X4 * R1High + X6 * R0High local Y0 = Accumulator0 + 3 * (2 ^ 69) - 3 * (2 ^ 69) Accumulator0 -= Y0 Accumulator1 += Y0 local Y1 = Accumulator1 + 3 * (2 ^ 83) - 3 * (2 ^ 83) Accumulator1 -= Y1 Accumulator2 += Y1 local Y2 = Accumulator2 + 3 * (2 ^ 101) - 3 * (2 ^ 101) Accumulator2 -= Y2 Accumulator3 += Y2 local Y3 = Accumulator3 + 3 * (2 ^ 115) - 3 * (2 ^ 115) Accumulator3 -= Y3 Accumulator4 += Y3 local Y4 = Accumulator4 + 3 * (2 ^ 133) - 3 * (2 ^ 133) Accumulator4 -= Y4 Accumulator5 += Y4 local Y5 = Accumulator5 + 3 * (2 ^ 147) - 3 * (2 ^ 147) Accumulator5 -= Y5 Accumulator6 += Y5 local Y6 = Accumulator6 + 3 * (2 ^ 163) - 3 * (2 ^ 163) Accumulator6 -= Y6 Accumulator7 += Y6 local Y7 = Accumulator7 + 3 * (2 ^ 181) - 3 * (2 ^ 181) Accumulator7 -= Y7 Accumulator0 += 5 / (2 ^ 130) * Y7 end local Carry0 = Accumulator0 % (2 ^ 16) Accumulator1 = Accumulator0 - Carry0 + Accumulator1 local Carry1 = Accumulator1 % (2 ^ 32) Accumulator2 = Accumulator1 - Carry1 + Accumulator2 local Carry2 = Accumulator2 % (2 ^ 48) Accumulator3 = Accumulator2 - Carry2 + Accumulator3 local Carry3 = Accumulator3 % (2 ^ 64) Accumulator4 = Accumulator3 - Carry3 + Accumulator4 local Carry4 = Accumulator4 % (2 ^ 80) Accumulator5 = Accumulator4 - Carry4 + Accumulator5 local Carry5 = Accumulator5 % (2 ^ 96) Accumulator6 = Accumulator5 - Carry5 + Accumulator6 local Carry6 = Accumulator6 % (2 ^ 112) Accumulator7 = Accumulator6 - Carry6 + Accumulator7 local Carry7 = Accumulator7 % (2 ^ 130) Accumulator0 = Carry0 + 5 / (2 ^ 130) * (Accumulator7 - Carry7) Carry0 = Accumulator0 % (2 ^ 16) Carry1 = Accumulator0 - Carry0 + Carry1 if Carry7 == 0x3ffff * (2 ^ 112) and Carry6 == 0xffff * (2 ^ 96) and Carry5 == 0xffff * (2 ^ 80) and Carry4 == 0xffff * (2 ^ 64) and Carry3 == 0xffff * (2 ^ 48) and Carry2 == 0xffff * (2 ^ 32) and Carry1 == 0xffff * (2 ^ 16) and Carry0 >= 0xfffb then Carry7, Carry6, Carry5, Carry4 = 0, 0, 0, 0 Carry3, Carry2, Carry1 = 0, 0, 0 Carry0 -= 0xfffb end local S0 = buffer.readu32(Key, 16) local S1Val = buffer.readu32(Key, 20) local S2Val = buffer.readu32(Key, 24) local S3Val = buffer.readu32(Key, 28) local Unpacked0 = S0 + Carry0 + Carry1 local Unpacked1 = Unpacked0 % (2 ^ 32) local Unpacked2 = Unpacked0 - Unpacked1 + S1Val * (2 ^ 32) + Carry2 + Carry3 local Unpacked3 = Unpacked2 % (2 ^ 64) local Unpacked4 = Unpacked2 - Unpacked3 + S2Val * (2 ^ 64) + Carry4 + Carry5 local Unpacked5 = Unpacked4 % (2 ^ 96) local Unpacked6 = Unpacked4 - Unpacked5 + S3Val * (2 ^ 96) + Carry6 + Carry7 local Unpacked7 = Unpacked6 % (2 ^ 128) local Output = buffer.create(TAG_SIZE) buffer.writeu32(Output, 0, Unpacked1) buffer.writeu32(Output, 4, Unpacked3 / (2 ^ 32)) buffer.writeu32(Output, 8, Unpacked5 / (2 ^ 64)) buffer.writeu32(Output, 12, Unpacked7 / (2 ^ 96)) return Output end local function Poly1305(Message: buffer, Key: buffer): buffer if Message == nil then error("Message cannot be nil", 2) end if typeof(Message) ~= "buffer" then error(`Message must be a buffer, got {typeof(Message)}`, 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 ~= POLY1305_KEY_SIZE then error(`Key must be exactly {POLY1305_KEY_SIZE} bytes long, got {KeyLength} bytes`, 2) end return ProcessMessage(Message, Key) end return Poly1305
2,497
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Encryption/AEAD/init.luau
--[=[ Cryptography library: ChaCha20-Poly1305 AEAD Sizes: Key: 16/32 bytes Nonce: 12/24 bytes Tag: 16 bytes Rounds: even positive integer (default: 20) Return type: buffer, buffer (ciphertext, tag) Example usage: local Plaintext = buffer.fromstring("Hello World") local Key = buffer.fromstring(string.rep("k", 32)) local Nonce = buffer.fromstring(string.rep("n", 12)) local AAD = buffer.fromstring("additional data") --------Usage Case 1-------- local Ciphertext, Tag = AEAD.Encrypt(Plaintext, Key, Nonce, AAD, Rounds, UseXChaCha20) --------Usage Case 2-------- local DecryptedText = AEAD.Decrypt(Ciphertext, Key, Nonce, Tag, AAD, Rounds, UseXChaCha20) --]=] --!strict --!optimize 2 --!native local ChaCha = require("@self/ChaCha") local Poly1305 = require("@self/Poly1305") local QWORD = 8 local CHACHA20_KEY_SIZE = 32 local CHACHA20_NONCE_SIZE = 12 local XCHACHA20_NONCE_SIZE = 24 local POLY1305_TAG_SIZE = 16 local AEAD = { ChaCha20 = ChaCha.ChaCha20, XChaCha20 = ChaCha.XChaCha20, Poly1305 = Poly1305 } local function GetFn(UseXChaCha20: boolean?): typeof(ChaCha.ChaCha20) | typeof(ChaCha.XChaCha20) if UseXChaCha20 then return ChaCha.XChaCha20 else return ChaCha.ChaCha20 end end local function ConstantTimeCompare(Buffer1: buffer, Buffer2: buffer): boolean local Length1 = buffer.len(Buffer1) local Length2 = buffer.len(Buffer2) if Length1 ~= Length2 then return false end local Difference = 0 for Index = 0, Length1 - 1 do Difference = bit32.bor(Difference, bit32.bxor( buffer.readu8(Buffer1, Index), buffer.readu8(Buffer2, Index) )) end return Difference == 0 end local function ConstructAuthData(AAD: buffer, Ciphertext: buffer): buffer local AADLength = buffer.len(AAD) local CiphertextLength = buffer.len(Ciphertext) local AADPadding = (-AADLength) % 16 local CiphertextPadding = (-CiphertextLength) % 16 local TotalSize = AADLength + AADPadding + CiphertextLength + CiphertextPadding + 16 local AuthData = buffer.create(TotalSize) local Offset = 0 buffer.copy(AuthData, Offset, AAD, 0, AADLength) Offset += AADLength + AADPadding buffer.copy(AuthData, Offset, Ciphertext, 0, CiphertextLength) Offset += CiphertextLength + CiphertextPadding buffer.writeu32(AuthData, Offset, AADLength) buffer.writeu32(AuthData, Offset + QWORD, CiphertextLength) return AuthData end local function GenerateAuthKey(Key: buffer, Nonce: buffer, Rounds: number?, UseXChaCha20: boolean?): buffer local BlockRounds = Rounds or 20 local ZeroBlock = buffer.create(32) return GetFn(UseXChaCha20)(ZeroBlock, Key, Nonce, 0, BlockRounds) end function AEAD.Encrypt(Message: buffer, Key: buffer, Nonce: buffer, AdditionalAuthData: buffer?, Rounds: number?, UseXChaCha20: boolean?): (buffer, buffer) if Message == nil then error("Message cannot be nil", 2) end if typeof(Message) ~= "buffer" then error(`Message must be a buffer, got {typeof(Message)}`, 2) end local MessageLength = buffer.len(Message) if MessageLength == 0 then error("Message cannot be empty", 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 then error(`Key must be exactly {CHACHA20_KEY_SIZE} 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) local RequiredNonceLength = if UseXChaCha20 then XCHACHA20_NONCE_SIZE else CHACHA20_NONCE_SIZE if NonceLength ~= RequiredNonceLength then error(`Nonce must be exactly {RequiredNonceLength} bytes long, got {NonceLength} bytes`, 2) end if AdditionalAuthData then if typeof(AdditionalAuthData) ~= "buffer" then error(`AdditionalAuthData must be a buffer, got {typeof(AdditionalAuthData)}`, 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 % 2 ~= 0 then error(`Rounds must be even, got {Rounds}`, 2) end end local BlockRounds = Rounds or 20 local AAD = AdditionalAuthData or buffer.create(0) local AuthenticationKey = GenerateAuthKey(Key, Nonce, BlockRounds, UseXChaCha20) local Ciphertext = GetFn(UseXChaCha20)(Message, Key, Nonce, 1, BlockRounds) local AuthData = ConstructAuthData(AAD, Ciphertext) local Tag = Poly1305(AuthData, AuthenticationKey) return Ciphertext, Tag end function AEAD.Decrypt(Ciphertext: buffer, Key: buffer, Nonce: buffer, Tag: buffer, AdditionalAuthData: buffer?, Rounds: number?, UseXChaCha20: boolean?): buffer? if Ciphertext == nil then error("Ciphertext cannot be nil", 2) end if typeof(Ciphertext) ~= "buffer" then error(`Ciphertext must be a buffer, got {typeof(Ciphertext)}`, 2) end local CiphertextLength = buffer.len(Ciphertext) if CiphertextLength == 0 then error("Ciphertext cannot be empty", 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 then error(`Key must be exactly {CHACHA20_KEY_SIZE} 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) local RequiredNonceLength = if UseXChaCha20 then XCHACHA20_NONCE_SIZE else CHACHA20_NONCE_SIZE if NonceLength ~= RequiredNonceLength then error(`Nonce must be exactly {RequiredNonceLength} bytes long, got {NonceLength} bytes`, 2) end if Tag == nil then error("Tag cannot be nil", 2) end if typeof(Tag) ~= "buffer" then error(`Tag must be a buffer, got {typeof(Tag)}`, 2) end local TagLength = buffer.len(Tag) if TagLength ~= POLY1305_TAG_SIZE then error(`Tag must be exactly {POLY1305_TAG_SIZE} bytes long, got {TagLength} bytes`, 2) end if AdditionalAuthData then if typeof(AdditionalAuthData) ~= "buffer" then error(`AdditionalAuthData must be a buffer, got {typeof(AdditionalAuthData)}`, 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 % 2 ~= 0 then error(`Rounds must be even, got {Rounds}`, 2) end end local BlockRounds = Rounds or 20 local AAD = AdditionalAuthData or buffer.create(0) local AuthenticationKey = GenerateAuthKey(Key, Nonce, BlockRounds, UseXChaCha20) local AuthData = ConstructAuthData(AAD, Ciphertext) local ExpectedTag = Poly1305(AuthData, AuthenticationKey) if not ConstantTimeCompare(Tag, ExpectedTag) then return nil end return GetFn(UseXChaCha20)(Ciphertext, Key, Nonce, 1, BlockRounds) end return AEAD
2,117
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Encryption/AES.luau
--[=[ Cryptography library: AES Sizes: Init Vector: 16 bytes Key Size: 16 / 24 / 32 bytes Example usage: local Key = CSPRNG.RandomBytes(32) local IV = CSPRNG.RandomBytes(12) local Message = "This is a secret message" local Plaintext = buffer.fromstring(Message) local AAD = buffer.fromstring("user:john,timestamp:456745683") local Ciphertext, Tag = AES.Encrypt(Plaintext, Key, IV, AAD) --]=] --!strict --!optimize 2 --!native type Processor = (PlaintextBlock: buffer, PlaintextOffset: number, OutputBuffer: buffer, OutputOffset: number) -> () local AES = {} local SBOX_16BIT = buffer.create(131072) local SMIX_TABLE0 = buffer.create(65536) local SMIX_TABLE1 = buffer.create(65536) local ALL_TABLES = buffer.create(32 * 16 * 16) local DOUBLES = buffer.create(128 * 16) local INVS_XOR_TABLE = buffer.create(65536) local INVMIX_TABLE0 = buffer.create(65536) local INVMIX_TABLE1 = buffer.create(65536) local KEY_CONFIGS = { [16] = {ExpandedLength = 176, MaterialLength = 128}, [24] = {ExpandedLength = 208, MaterialLength = 160}, [32] = {ExpandedLength = 240, MaterialLength = 192} } local SUBSTITUTION_BOX, INVERSE_SUBSTITUTION_BOX = buffer.create(256), buffer.create(256) do local GaloisMultiply3, GaloisMultiply9, GaloisMultiply11 = buffer.create(256), buffer.create(256), buffer.create(256) local function GaloisFieldMultiply(FirstValue: number, SecondValue: number): number local Product = 0 for _ = 0, 7 do if SecondValue % 2 == 1 then Product = bit32.bxor(Product, FirstValue) end FirstValue = FirstValue >= 128 and bit32.bxor(FirstValue * 2 % 256, 27) or FirstValue * 2 % 256 SecondValue = math.floor(SecondValue / 2) end return Product end local PolynomialP = 1 local PolynomialQ = 1 buffer.writeu8(SUBSTITUTION_BOX, 0, 99) for _ = 1, 255 do PolynomialP = bit32.bxor(PolynomialP, PolynomialP * 2, PolynomialP < 128 and 0 or 27) % 256 PolynomialQ = bit32.bxor(PolynomialQ, PolynomialQ * 2) PolynomialQ = bit32.bxor(PolynomialQ, PolynomialQ * 4) PolynomialQ = bit32.bxor(PolynomialQ, PolynomialQ * 16) % 256 if PolynomialQ >= 128 then PolynomialQ = bit32.bxor(PolynomialQ, 9) end local TempValue = bit32.bxor( PolynomialQ, PolynomialQ % 128 * 2 + PolynomialQ / 128, PolynomialQ % 64 * 4 + PolynomialQ / 64, PolynomialQ % 32 * 8 + PolynomialQ / 32, PolynomialQ % 16 * 16 + PolynomialQ / 16, 99 ) buffer.writeu8(SUBSTITUTION_BOX, PolynomialP, TempValue) buffer.writeu8(INVERSE_SUBSTITUTION_BOX, TempValue, PolynomialP) buffer.writeu8(GaloisMultiply3, PolynomialP, GaloisFieldMultiply(3, PolynomialP)) buffer.writeu8(GaloisMultiply9, PolynomialP, GaloisFieldMultiply(9, PolynomialP)) buffer.writeu8(GaloisMultiply11, PolynomialP, GaloisFieldMultiply(11, PolynomialP)) end local TableIndex = 0 for OuterIndex = 0, 255 do local PolynomialPOuter = buffer.readu8(SUBSTITUTION_BOX, OuterIndex) local PolynomialPBytes = PolynomialPOuter * 256 local Galois2 = GaloisFieldMultiply(2, PolynomialPOuter) local Galois13 = GaloisFieldMultiply(13, OuterIndex) local Galois14 = GaloisFieldMultiply(14, OuterIndex) for InnerIndex = 0, 255 do local PolynomialQInner = buffer.readu8(SUBSTITUTION_BOX, InnerIndex) buffer.writeu16(SBOX_16BIT, TableIndex * 2, PolynomialPBytes + PolynomialQInner) buffer.writeu8(INVS_XOR_TABLE, TableIndex, buffer.readu8(INVERSE_SUBSTITUTION_BOX, bit32.bxor(OuterIndex, InnerIndex))) buffer.writeu8(SMIX_TABLE0, TableIndex, bit32.bxor(Galois2, buffer.readu8(GaloisMultiply3, PolynomialQInner))) buffer.writeu8(SMIX_TABLE1, TableIndex, bit32.bxor(PolynomialPOuter, PolynomialQInner)) buffer.writeu8(INVMIX_TABLE0, TableIndex, bit32.bxor(Galois14, buffer.readu8(GaloisMultiply11, InnerIndex))) buffer.writeu8(INVMIX_TABLE1, TableIndex, bit32.bxor(Galois13, buffer.readu8(GaloisMultiply9, InnerIndex))) TableIndex += 1 end end end local function ExpandKeySchedule(Key: buffer, KeyLength: number, OutputBuffer: buffer): buffer buffer.copy(OutputBuffer, 0, Key, 0, KeyLength) local Word = bit32.rrotate(buffer.readu32(OutputBuffer, KeyLength - 4), 8) local RoundConstant = 0.5 local SBox_16 = SBOX_16BIT if KeyLength == 32 then for KeyOffset = 32, 192, 32 do RoundConstant = RoundConstant * 2 % 229 local SBoxLookup = buffer.readu16(SBox_16, Word // 65536 * 2) * 65536 + buffer.readu16(SBox_16, Word % 65536 * 2) Word = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 32), SBoxLookup, RoundConstant) buffer.writeu32(OutputBuffer, KeyOffset, Word) local W1 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 28), Word) buffer.writeu32(OutputBuffer, KeyOffset + 4, W1) local W2 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 24), W1) buffer.writeu32(OutputBuffer, KeyOffset + 8, W2) local W3 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 20), W2) buffer.writeu32(OutputBuffer, KeyOffset + 12, W3) SBoxLookup = buffer.readu16(SBox_16, W3 // 65536 * 2) * 65536 + buffer.readu16(SBox_16, W3 % 65536 * 2) Word = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 16), SBoxLookup) buffer.writeu32(OutputBuffer, KeyOffset + 16, Word) W1 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 12), Word) buffer.writeu32(OutputBuffer, KeyOffset + 20, W1) W2 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 8), W1) buffer.writeu32(OutputBuffer, KeyOffset + 24, W2) Word = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 4), W2) buffer.writeu32(OutputBuffer, KeyOffset + 28, Word) Word = bit32.rrotate(Word, 8) end local SBoxLookup = buffer.readu16(SBox_16, Word // 65536 * 2) * 65536 + buffer.readu16(SBox_16, Word % 65536 * 2) Word = bit32.bxor(buffer.readu32(OutputBuffer, 192), SBoxLookup, 64) buffer.writeu32(OutputBuffer, 224, Word) local W1 = bit32.bxor(buffer.readu32(OutputBuffer, 196), Word) buffer.writeu32(OutputBuffer, 228, W1) local W2 = bit32.bxor(buffer.readu32(OutputBuffer, 200), W1) buffer.writeu32(OutputBuffer, 232, W2) buffer.writeu32(OutputBuffer, 236, bit32.bxor(buffer.readu32(OutputBuffer, 204), W2)) elseif KeyLength == 24 then for KeyOffset = 24, 168, 24 do RoundConstant = RoundConstant * 2 % 229 local SBoxLookup = buffer.readu16(SBox_16, Word // 65536 * 2) * 65536 + buffer.readu16(SBox_16, Word % 65536 * 2) Word = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 24), SBoxLookup, RoundConstant) buffer.writeu32(OutputBuffer, KeyOffset, Word) local W1 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 20), Word) buffer.writeu32(OutputBuffer, KeyOffset + 4, W1) local W2 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 16), W1) buffer.writeu32(OutputBuffer, KeyOffset + 8, W2) local W3 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 12), W2) buffer.writeu32(OutputBuffer, KeyOffset + 12, W3) local W4 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 8), W3) buffer.writeu32(OutputBuffer, KeyOffset + 16, W4) Word = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 4), W4) buffer.writeu32(OutputBuffer, KeyOffset + 20, Word) Word = bit32.rrotate(Word, 8) end local SBoxLookup = buffer.readu16(SBox_16, Word // 65536 * 2) * 65536 + buffer.readu16(SBox_16, Word % 65536 * 2) Word = bit32.bxor(buffer.readu32(OutputBuffer, 168), SBoxLookup, 128) buffer.writeu32(OutputBuffer, 192, Word) local W1 = bit32.bxor(buffer.readu32(OutputBuffer, 172), Word) buffer.writeu32(OutputBuffer, 196, W1) local W2 = bit32.bxor(buffer.readu32(OutputBuffer, 176), W1) buffer.writeu32(OutputBuffer, 200, W2) buffer.writeu32(OutputBuffer, 204, bit32.bxor(buffer.readu32(OutputBuffer, 180), W2)) else for KeyOffset = 16, 144, 16 do RoundConstant = RoundConstant * 2 % 229 local SBoxLookup = buffer.readu16(SBox_16, Word // 65536 * 2) * 65536 + buffer.readu16(SBox_16, Word % 65536 * 2) Word = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 16), SBoxLookup, RoundConstant) buffer.writeu32(OutputBuffer, KeyOffset, Word) local W1 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 12), Word) buffer.writeu32(OutputBuffer, KeyOffset + 4, W1) local W2 = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 8), W1) buffer.writeu32(OutputBuffer, KeyOffset + 8, W2) Word = bit32.bxor(buffer.readu32(OutputBuffer, KeyOffset - 4), W2) buffer.writeu32(OutputBuffer, KeyOffset + 12, Word) Word = bit32.rrotate(Word, 8) end local SBoxLookup = buffer.readu16(SBox_16, Word // 65536 * 2) * 65536 + buffer.readu16(SBox_16, Word % 65536 * 2) Word = bit32.bxor(buffer.readu32(OutputBuffer, 144), SBoxLookup, 54) buffer.writeu32(OutputBuffer, 160, Word) local W1 = bit32.bxor(buffer.readu32(OutputBuffer, 148), Word) buffer.writeu32(OutputBuffer, 164, W1) local W2 = bit32.bxor(buffer.readu32(OutputBuffer, 152), W1) buffer.writeu32(OutputBuffer, 168, W2) buffer.writeu32(OutputBuffer, 172, bit32.bxor(buffer.readu32(OutputBuffer, 156), W2)) end return OutputBuffer end local A0: number, A1: number, A2: number, A3: number, A4: number, A5: number, A6: number, A7: number, A8: number, A9: number, A10: number, A11: number, A12: number, A13: number, A14: number, A15: number local function EncryptBlock(RoundKeys: buffer, MaterialLength: number, Plaintext: buffer, PlaintextOffset: number, Output: buffer, OutputOffset: number) A0 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset), buffer.readu8(RoundKeys, 0)) A1 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 1), buffer.readu8(RoundKeys, 1)) A2 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 2), buffer.readu8(RoundKeys, 2)) A3 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 3), buffer.readu8(RoundKeys, 3)) A4 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 4), buffer.readu8(RoundKeys, 4)) A5 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 5), buffer.readu8(RoundKeys, 5)) A6 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 6), buffer.readu8(RoundKeys, 6)) A7 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 7), buffer.readu8(RoundKeys, 7)) A8 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 8), buffer.readu8(RoundKeys, 8)) A9 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 9), buffer.readu8(RoundKeys, 9)) A10 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 10), buffer.readu8(RoundKeys, 10)) A11 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 11), buffer.readu8(RoundKeys, 11)) A12 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 12), buffer.readu8(RoundKeys, 12)) A13 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 13), buffer.readu8(RoundKeys, 13)) A14 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 14), buffer.readu8(RoundKeys, 14)) A15 = bit32.bxor(buffer.readu8(Plaintext, PlaintextOffset + 15), buffer.readu8(RoundKeys, 15)) local B0: number, B1: number, B2: number, B3: number, B4: number, B5: number, B6: number, B7: number, B8: number, B9: number, B10: number, B11: number, B12: number, B13: number, B14: number, B15: number = A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15 local I0: number = B0 * 256 + B5; local I1: number = B5 * 256 + B10; local I2: number = B10 * 256 + B15; local I3: number = B15 * 256 + B0 local I4: number = B4 * 256 + B9; local I5: number = B9 * 256 + B14; local I6: number = B14 * 256 + B3; local I7: number = B3 * 256 + B4 local I8: number = B8 * 256 + B13; local I9: number = B13 * 256 + B2; local I10: number = B2 * 256 + B7; local I11: number = B7 * 256 + B8 local I12: number = B12 * 256 + B1; local I13: number = B1 * 256 + B6; local I14: number = B6 * 256 + B11; local I15: number = B11 * 256 + B12 local Tbl0, Tbl1 = SMIX_TABLE0, SMIX_TABLE1 for RoundOffset = 16, MaterialLength, 16 do B0 = bit32.bxor(buffer.readu8(Tbl0, I0), buffer.readu8(Tbl1, I2), buffer.readu8(RoundKeys, RoundOffset)) B1 = bit32.bxor(buffer.readu8(Tbl0, I1), buffer.readu8(Tbl1, I3), buffer.readu8(RoundKeys, RoundOffset + 1)) B2 = bit32.bxor(buffer.readu8(Tbl0, I2), buffer.readu8(Tbl1, I0), buffer.readu8(RoundKeys, RoundOffset + 2)) B3 = bit32.bxor(buffer.readu8(Tbl0, I3), buffer.readu8(Tbl1, I1), buffer.readu8(RoundKeys, RoundOffset + 3)) B4 = bit32.bxor(buffer.readu8(Tbl0, I4), buffer.readu8(Tbl1, I6), buffer.readu8(RoundKeys, RoundOffset + 4)) B5 = bit32.bxor(buffer.readu8(Tbl0, I5), buffer.readu8(Tbl1, I7), buffer.readu8(RoundKeys, RoundOffset + 5)) B6 = bit32.bxor(buffer.readu8(Tbl0, I6), buffer.readu8(Tbl1, I4), buffer.readu8(RoundKeys, RoundOffset + 6)) B7 = bit32.bxor(buffer.readu8(Tbl0, I7), buffer.readu8(Tbl1, I5), buffer.readu8(RoundKeys, RoundOffset + 7)) B8 = bit32.bxor(buffer.readu8(Tbl0, I8), buffer.readu8(Tbl1, I10), buffer.readu8(RoundKeys, RoundOffset + 8)) B9 = bit32.bxor(buffer.readu8(Tbl0, I9), buffer.readu8(Tbl1, I11), buffer.readu8(RoundKeys, RoundOffset + 9)) B10 = bit32.bxor(buffer.readu8(Tbl0, I10), buffer.readu8(Tbl1, I8), buffer.readu8(RoundKeys, RoundOffset + 10)) B11 = bit32.bxor(buffer.readu8(Tbl0, I11), buffer.readu8(Tbl1, I9), buffer.readu8(RoundKeys, RoundOffset + 11)) B12 = bit32.bxor(buffer.readu8(Tbl0, I12), buffer.readu8(Tbl1, I14), buffer.readu8(RoundKeys, RoundOffset + 12)) B13 = bit32.bxor(buffer.readu8(Tbl0, I13), buffer.readu8(Tbl1, I15), buffer.readu8(RoundKeys, RoundOffset + 13)) B14 = bit32.bxor(buffer.readu8(Tbl0, I14), buffer.readu8(Tbl1, I12), buffer.readu8(RoundKeys, RoundOffset + 14)) B15 = bit32.bxor(buffer.readu8(Tbl0, I15), buffer.readu8(Tbl1, I13), buffer.readu8(RoundKeys, RoundOffset + 15)) I0, I1, I2, I3 = B0 * 256 + B5, B5 * 256 + B10, B10 * 256 + B15, B15 * 256 + B0 I4, I5, I6, I7 = B4 * 256 + B9, B9 * 256 + B14, B14 * 256 + B3, B3 * 256 + B4 I8, I9, I10, I11 = B8 * 256 + B13, B13 * 256 + B2, B2 * 256 + B7, B7 * 256 + B8 I12, I13, I14, I15 = B12 * 256 + B1, B1 * 256 + B6, B6 * 256 + B11, B11 * 256 + B12 end buffer.writeu32(Output, OutputOffset, bit32.bxor( buffer.readu16(SBOX_16BIT, bit32.bxor(buffer.readu8(Tbl0, I15), buffer.readu8(SMIX_TABLE1, I13), buffer.readu8(RoundKeys, MaterialLength + 31)) * 512 + bit32.bxor(buffer.readu8(Tbl0, I10), buffer.readu8(SMIX_TABLE1, I8), buffer.readu8(RoundKeys, MaterialLength + 26)) * 2) * 65536 + buffer.readu16(SBOX_16BIT, bit32.bxor(buffer.readu8(Tbl0, I5), buffer.readu8(SMIX_TABLE1, I7), buffer.readu8(RoundKeys, MaterialLength + 21)) * 512 + bit32.bxor(buffer.readu8(Tbl0, I0), buffer.readu8(SMIX_TABLE1, I2), buffer.readu8(RoundKeys, MaterialLength + 16)) * 2), buffer.readu32(RoundKeys, MaterialLength + 32) )) buffer.writeu32(Output, OutputOffset + 4, bit32.bxor( buffer.readu16(SBOX_16BIT, bit32.bxor(buffer.readu8(Tbl0, I3), buffer.readu8(SMIX_TABLE1, I1), buffer.readu8(RoundKeys, MaterialLength + 19)) * 512 + bit32.bxor(buffer.readu8(Tbl0, I14), buffer.readu8(SMIX_TABLE1, I12), buffer.readu8(RoundKeys, MaterialLength + 30)) * 2) * 65536 + buffer.readu16(SBOX_16BIT, bit32.bxor(buffer.readu8(Tbl0, I9), buffer.readu8(SMIX_TABLE1, I11), buffer.readu8(RoundKeys, MaterialLength + 25)) * 512 + bit32.bxor(buffer.readu8(Tbl0, I4), buffer.readu8(SMIX_TABLE1, I6), buffer.readu8(RoundKeys, MaterialLength + 20)) * 2), buffer.readu32(RoundKeys, MaterialLength + 36) )) buffer.writeu32(Output, OutputOffset + 8, bit32.bxor( buffer.readu16(SBOX_16BIT, bit32.bxor(buffer.readu8(Tbl0, I7), buffer.readu8(SMIX_TABLE1, I5), buffer.readu8(RoundKeys, MaterialLength + 23)) * 512 + bit32.bxor(buffer.readu8(Tbl0, I2), buffer.readu8(SMIX_TABLE1, I0), buffer.readu8(RoundKeys, MaterialLength + 18)) * 2) * 65536 + buffer.readu16(SBOX_16BIT, bit32.bxor(buffer.readu8(Tbl0, I13), buffer.readu8(SMIX_TABLE1, I15), buffer.readu8(RoundKeys, MaterialLength + 29)) * 512 + bit32.bxor(buffer.readu8(Tbl0, I8), buffer.readu8(SMIX_TABLE1, I10), buffer.readu8(RoundKeys, MaterialLength + 24)) * 2), buffer.readu32(RoundKeys, MaterialLength + 40) )) buffer.writeu32(Output, OutputOffset + 12, bit32.bxor( buffer.readu16(SBOX_16BIT, bit32.bxor(buffer.readu8(Tbl0, I11), buffer.readu8(SMIX_TABLE1, I9), buffer.readu8(RoundKeys, MaterialLength + 27)) * 512 + bit32.bxor(buffer.readu8(Tbl0, I6), buffer.readu8(SMIX_TABLE1, I4), buffer.readu8(RoundKeys, MaterialLength + 22)) * 2) * 65536 + buffer.readu16(SBOX_16BIT, bit32.bxor(buffer.readu8(Tbl0, I1), buffer.readu8(SMIX_TABLE1, I3), buffer.readu8(RoundKeys, MaterialLength + 17)) * 512 + bit32.bxor(buffer.readu8(Tbl0, I12), buffer.readu8(SMIX_TABLE1, I14), buffer.readu8(RoundKeys, MaterialLength + 28)) * 2), buffer.readu32(RoundKeys, MaterialLength + 44) )) end local function ConstantTimeCompare(Buffer1: buffer, Buffer2: buffer): boolean local Length1 = buffer.len(Buffer1) local Length2 = buffer.len(Buffer2) if Length1 ~= Length2 then return false end local Difference = 0 for Index = 0, Length1 - 1 do Difference = bit32.bor(Difference, bit32.bxor( buffer.readu8(Buffer1, Index), buffer.readu8(Buffer2, Index) )) end return Difference == 0 end local function BuildShoupTables(H: buffer): buffer local Doubles = DOUBLES local AllTables = ALL_TABLES buffer.copy(Doubles, 0, H, 0, 16) for I = 1, 127 do local PrevOffset = (I - 1) * 16 local CurrOffset = I * 16 local LSB = bit32.band(buffer.readu8(Doubles, PrevOffset + 15), 1) local Carry = 0 for BytePos = 0, 15 do local B = buffer.readu8(Doubles, PrevOffset + BytePos) local NewCarry = bit32.lshift(bit32.band(B, 1), 7) buffer.writeu8(Doubles, CurrOffset + BytePos, bit32.bor(bit32.rshift(B, 1), Carry)) Carry = NewCarry end if LSB == 1 then buffer.writeu8(Doubles, CurrOffset, bit32.bxor(buffer.readu8(Doubles, CurrOffset), 0xE1)) end end for NibbleIdx = 0, 31 do local TableOffset = NibbleIdx * 256 buffer.writeu32(AllTables, TableOffset, 0) buffer.writeu32(AllTables, TableOffset + 4, 0) buffer.writeu32(AllTables, TableOffset + 8, 0) buffer.writeu32(AllTables, TableOffset + 12, 0) for Entry = 1, 15 do local EntryOffset = TableOffset + Entry * 16 local Z0, Z1, Z2, Z3 = 0, 0, 0, 0 for Bit = 0, 3 do if bit32.band(Entry, bit32.lshift(1, 3 - Bit)) ~= 0 then local DoubleOffset = (NibbleIdx * 4 + Bit) * 16 Z0 = bit32.bxor(Z0, buffer.readu32(Doubles, DoubleOffset)) Z1 = bit32.bxor(Z1, buffer.readu32(Doubles, DoubleOffset + 4)) Z2 = bit32.bxor(Z2, buffer.readu32(Doubles, DoubleOffset + 8)) Z3 = bit32.bxor(Z3, buffer.readu32(Doubles, DoubleOffset + 12)) end end buffer.writeu32(AllTables, EntryOffset, Z0) buffer.writeu32(AllTables, EntryOffset + 4, Z1) buffer.writeu32(AllTables, EntryOffset + 8, Z2) buffer.writeu32(AllTables, EntryOffset + 12, Z3) end end return AllTables end local function GfMult(Y: buffer, Tables: buffer, Z: buffer) local Z0, Z1, Z2, Z3 = 0, 0, 0, 0 for ByteIdx = 0, 15 do local ByteVal = buffer.readu8(Y, ByteIdx) local BaseOffset = ByteIdx * 512 local HighOffset = BaseOffset + bit32.rshift(ByteVal, 4) * 16 Z0 = bit32.bxor(Z0, buffer.readu32(Tables, HighOffset)) Z1 = bit32.bxor(Z1, buffer.readu32(Tables, HighOffset + 4)) Z2 = bit32.bxor(Z2, buffer.readu32(Tables, HighOffset + 8)) Z3 = bit32.bxor(Z3, buffer.readu32(Tables, HighOffset + 12)) local LowOffset = BaseOffset + 256 + bit32.band(ByteVal, 0x0F) * 16 Z0 = bit32.bxor(Z0, buffer.readu32(Tables, LowOffset)) Z1 = bit32.bxor(Z1, buffer.readu32(Tables, LowOffset + 4)) Z2 = bit32.bxor(Z2, buffer.readu32(Tables, LowOffset + 8)) Z3 = bit32.bxor(Z3, buffer.readu32(Tables, LowOffset + 12)) end buffer.writeu32(Z, 0, Z0) buffer.writeu32(Z, 4, Z1) buffer.writeu32(Z, 8, Z2) buffer.writeu32(Z, 12, Z3) end local function Ghash(Tables: buffer, X: buffer, XLen: number, Y: buffer) local M = math.floor(XLen / 16) local XPos = 0 local Tmp = buffer.create(16) local GfMult = GfMult for _ = 1, M do buffer.writeu32(Y, 0, bit32.bxor(buffer.readu32(Y, 0), buffer.readu32(X, XPos))) buffer.writeu32(Y, 4, bit32.bxor(buffer.readu32(Y, 4), buffer.readu32(X, XPos + 4))) buffer.writeu32(Y, 8, bit32.bxor(buffer.readu32(Y, 8), buffer.readu32(X, XPos + 8))) buffer.writeu32(Y, 12, bit32.bxor(buffer.readu32(Y, 12), buffer.readu32(X, XPos + 12))) XPos += 16 GfMult(Y, Tables, Tmp) buffer.writeu32(Y, 0, buffer.readu32(Tmp, 0)) buffer.writeu32(Y, 4, buffer.readu32(Tmp, 4)) buffer.writeu32(Y, 8, buffer.readu32(Tmp, 8)) buffer.writeu32(Y, 12, buffer.readu32(Tmp, 12)) end if XPos < XLen then local Last = XLen - XPos buffer.writeu32(Tmp, 0, 0) buffer.writeu32(Tmp, 4, 0) buffer.writeu32(Tmp, 8, 0) buffer.writeu32(Tmp, 12, 0) buffer.copy(Tmp, 0, X, XPos, Last) buffer.writeu32(Y, 0, bit32.bxor(buffer.readu32(Y, 0), buffer.readu32(Tmp, 0))) buffer.writeu32(Y, 4, bit32.bxor(buffer.readu32(Y, 4), buffer.readu32(Tmp, 4))) buffer.writeu32(Y, 8, bit32.bxor(buffer.readu32(Y, 8), buffer.readu32(Tmp, 8))) buffer.writeu32(Y, 12, bit32.bxor(buffer.readu32(Y, 12), buffer.readu32(Tmp, 12))) GfMult(Y, Tables, Tmp) buffer.writeu32(Y, 0, buffer.readu32(Tmp, 0)) buffer.writeu32(Y, 4, buffer.readu32(Tmp, 4)) buffer.writeu32(Y, 8, buffer.readu32(Tmp, 8)) buffer.writeu32(Y, 12, buffer.readu32(Tmp, 12)) end end local function Gctr(RoundKeys: buffer, KeyMaterialLength: number, ICB: buffer, X: buffer, XLen: number, Y: buffer) if XLen == 0 then return end local N = math.floor(XLen / 16) local CB = buffer.create(16) local Tmp = buffer.create(16) local XPos = 0 local YPos = 0 buffer.writeu32(CB, 0, buffer.readu32(ICB, 0)) buffer.writeu32(CB, 4, buffer.readu32(ICB, 4)) buffer.writeu32(CB, 8, buffer.readu32(ICB, 8)) buffer.writeu32(CB, 12, buffer.readu32(ICB, 12)) local Encrypt = EncryptBlock for I = 0, N - 1 do Encrypt(RoundKeys, KeyMaterialLength, CB, 0, Tmp, 0) buffer.writeu32(Y, YPos + 0, bit32.bxor(buffer.readu32(X, XPos + 0), buffer.readu32(Tmp, 0))) buffer.writeu32(Y, YPos + 4, bit32.bxor(buffer.readu32(X, XPos + 4), buffer.readu32(Tmp, 4))) buffer.writeu32(Y, YPos + 8, bit32.bxor(buffer.readu32(X, XPos + 8), buffer.readu32(Tmp, 8))) buffer.writeu32(Y, YPos + 12, bit32.bxor(buffer.readu32(X, XPos + 12), buffer.readu32(Tmp, 12))) XPos += 16 YPos += 16 local Val = bit32.byteswap(buffer.readu32(CB, 12)) Val = (Val + 1) % 0x100000000 buffer.writeu32(CB, 12, bit32.byteswap(Val)) end local Last = XLen - XPos if Last > 0 then EncryptBlock(RoundKeys, KeyMaterialLength, CB, 0, Tmp, 0) for I = 0, Last - 1 do local XByte = buffer.readu8(X, XPos + I) local TmpByte = buffer.readu8(Tmp, I) buffer.writeu8(Y, YPos + I, bit32.bxor(XByte, TmpByte)) end end end local function PrepareJ0(H: buffer, IV: buffer, IVLen: number, J0: buffer): buffer local Tables = BuildShoupTables(H) if IVLen == 12 then buffer.writeu32(J0, 0, buffer.readu32(IV, 0)) buffer.writeu32(J0, 4, buffer.readu32(IV, 4)) buffer.writeu32(J0, 8, buffer.readu32(IV, 8)) buffer.writeu32(J0, 12, 0x01000000) else buffer.writeu32(J0, 0, 0) buffer.writeu32(J0, 4, 0) buffer.writeu32(J0, 8, 0) buffer.writeu32(J0, 12, 0) Ghash(Tables, IV, IVLen, J0) local LenBuf = buffer.create(16) local IVLenBits = IVLen * 8 buffer.writeu32(LenBuf, 0, 0) buffer.writeu32(LenBuf, 4, 0) buffer.writeu32(LenBuf, 8, 0) buffer.writeu32(LenBuf, 12, bit32.byteswap(IVLenBits)) Ghash(Tables, LenBuf, 16, J0) end return Tables end local function GcmGctr(RoundKeys: buffer, KeyMaterialLength: number, J0: buffer, Input: buffer, Len: number, Output: buffer) if Len == 0 then return end local J0Inc = buffer.create(16) buffer.writeu32(J0Inc, 0, buffer.readu32(J0, 0)) buffer.writeu32(J0Inc, 4, buffer.readu32(J0, 4)) buffer.writeu32(J0Inc, 8, buffer.readu32(J0, 8)) buffer.writeu32(J0Inc, 12, buffer.readu32(J0, 12)) local Val = bit32.byteswap(buffer.readu32(J0Inc, 12)) Val = (Val + 1) % 0x100000000 buffer.writeu32(J0Inc, 12, bit32.byteswap(Val)) Gctr(RoundKeys, KeyMaterialLength, J0Inc, Input, Len, Output) end local function GcmHash(Tables: buffer, AAD: buffer, AADLen: number, Crypt: buffer, CryptLen: number, S: buffer) local Tmp = buffer.create(16) local GfMult = GfMult buffer.writeu32(S, 0, 0) buffer.writeu32(S, 4, 0) buffer.writeu32(S, 8, 0) buffer.writeu32(S, 12, 0) local M = math.floor(AADLen / 16) local XPos = 0 for _ = 1, M do buffer.writeu32(S, 0, bit32.bxor(buffer.readu32(S, 0), buffer.readu32(AAD, XPos))) buffer.writeu32(S, 4, bit32.bxor(buffer.readu32(S, 4), buffer.readu32(AAD, XPos + 4))) buffer.writeu32(S, 8, bit32.bxor(buffer.readu32(S, 8), buffer.readu32(AAD, XPos + 8))) buffer.writeu32(S, 12, bit32.bxor(buffer.readu32(S, 12), buffer.readu32(AAD, XPos + 12))) XPos += 16 GfMult(S, Tables, Tmp) buffer.writeu32(S, 0, buffer.readu32(Tmp, 0)) buffer.writeu32(S, 4, buffer.readu32(Tmp, 4)) buffer.writeu32(S, 8, buffer.readu32(Tmp, 8)) buffer.writeu32(S, 12, buffer.readu32(Tmp, 12)) end if XPos < AADLen then local Last = AADLen - XPos buffer.writeu32(Tmp, 0, 0) buffer.writeu32(Tmp, 4, 0) buffer.writeu32(Tmp, 8, 0) buffer.writeu32(Tmp, 12, 0) buffer.copy(Tmp, 0, AAD, XPos, Last) buffer.writeu32(S, 0, bit32.bxor(buffer.readu32(S, 0), buffer.readu32(Tmp, 0))) buffer.writeu32(S, 4, bit32.bxor(buffer.readu32(S, 4), buffer.readu32(Tmp, 4))) buffer.writeu32(S, 8, bit32.bxor(buffer.readu32(S, 8), buffer.readu32(Tmp, 8))) buffer.writeu32(S, 12, bit32.bxor(buffer.readu32(S, 12), buffer.readu32(Tmp, 12))) GfMult(S, Tables, Tmp) buffer.writeu32(S, 0, buffer.readu32(Tmp, 0)) buffer.writeu32(S, 4, buffer.readu32(Tmp, 4)) buffer.writeu32(S, 8, buffer.readu32(Tmp, 8)) buffer.writeu32(S, 12, buffer.readu32(Tmp, 12)) end M = math.floor(CryptLen / 16) XPos = 0 for _ = 1, M do buffer.writeu32(S, 0, bit32.bxor(buffer.readu32(S, 0), buffer.readu32(Crypt, XPos))) buffer.writeu32(S, 4, bit32.bxor(buffer.readu32(S, 4), buffer.readu32(Crypt, XPos + 4))) buffer.writeu32(S, 8, bit32.bxor(buffer.readu32(S, 8), buffer.readu32(Crypt, XPos + 8))) buffer.writeu32(S, 12, bit32.bxor(buffer.readu32(S, 12), buffer.readu32(Crypt, XPos + 12))) XPos += 16 GfMult(S, Tables, Tmp) buffer.writeu32(S, 0, buffer.readu32(Tmp, 0)) buffer.writeu32(S, 4, buffer.readu32(Tmp, 4)) buffer.writeu32(S, 8, buffer.readu32(Tmp, 8)) buffer.writeu32(S, 12, buffer.readu32(Tmp, 12)) end if XPos < CryptLen then local Last = CryptLen - XPos buffer.writeu32(Tmp, 0, 0) buffer.writeu32(Tmp, 4, 0) buffer.writeu32(Tmp, 8, 0) buffer.writeu32(Tmp, 12, 0) buffer.copy(Tmp, 0, Crypt, XPos, Last) buffer.writeu32(S, 0, bit32.bxor(buffer.readu32(S, 0), buffer.readu32(Tmp, 0))) buffer.writeu32(S, 4, bit32.bxor(buffer.readu32(S, 4), buffer.readu32(Tmp, 4))) buffer.writeu32(S, 8, bit32.bxor(buffer.readu32(S, 8), buffer.readu32(Tmp, 8))) buffer.writeu32(S, 12, bit32.bxor(buffer.readu32(S, 12), buffer.readu32(Tmp, 12))) GfMult(S, Tables, Tmp) buffer.writeu32(S, 0, buffer.readu32(Tmp, 0)) buffer.writeu32(S, 4, buffer.readu32(Tmp, 4)) buffer.writeu32(S, 8, buffer.readu32(Tmp, 8)) buffer.writeu32(S, 12, buffer.readu32(Tmp, 12)) end local AADLenBits = AADLen * 8 local CryptLenBits = CryptLen * 8 buffer.writeu32(S, 4, bit32.bxor(buffer.readu32(S, 4), bit32.byteswap(AADLenBits))) buffer.writeu32(S, 12, bit32.bxor(buffer.readu32(S, 12), bit32.byteswap(CryptLenBits))) GfMult(S, Tables, Tmp) buffer.writeu32(S, 0, buffer.readu32(Tmp, 0)) buffer.writeu32(S, 4, buffer.readu32(Tmp, 4)) buffer.writeu32(S, 8, buffer.readu32(Tmp, 8)) buffer.writeu32(S, 12, buffer.readu32(Tmp, 12)) end function AES.Encrypt(Plaintext: buffer, Key: buffer, IV: buffer, AAD: buffer?): (buffer, buffer) if not Key or typeof(Key) ~= "buffer" then error("Key must be a buffer", 2) end if not IV or typeof(IV) ~= "buffer" then error("IV must be a buffer", 2) end if not Plaintext or typeof(Plaintext) ~= "buffer" then error("Plaintext must be a buffer", 2) end local KeyLength = buffer.len(Key) if KeyLength ~= 16 and KeyLength ~= 24 and KeyLength ~= 32 then error("Key must be 16, 24, or 32 bytes", 2) end local KeyConfig = KEY_CONFIGS[KeyLength] local RoundKeys = ExpandKeySchedule(Key, KeyLength, buffer.create(KeyConfig.ExpandedLength)) local KeyMaterialLength = KeyConfig.MaterialLength local IVLen = buffer.len(IV) local AADLen = buffer.len(AAD or buffer.create(0)) local PlainLen = buffer.len(Plaintext) local AuthData = AAD or buffer.create(0) local OutputBuffer = buffer.create(PlainLen) local OutputTag = buffer.create(16) local H = buffer.create(16) local J0 = buffer.create(16) local S = buffer.create(16) EncryptBlock(RoundKeys, KeyMaterialLength, H, 0, H, 0) local Tables = PrepareJ0(H, IV, IVLen, J0) GcmGctr(RoundKeys, KeyMaterialLength, J0, Plaintext, PlainLen, OutputBuffer) GcmHash(Tables, AuthData, AADLen, OutputBuffer, PlainLen, S) Gctr(RoundKeys, KeyMaterialLength, J0, S, 16, OutputTag) return OutputBuffer, OutputTag end function AES.Decrypt(Ciphertext: buffer, Key: buffer, IV: buffer, Tag: buffer, AAD: buffer?): (boolean, buffer?) if not Key or typeof(Key) ~= "buffer" then error("Key must be a buffer", 2) end if not IV or typeof(IV) ~= "buffer" then error("IV must be a buffer", 2) end if not Ciphertext or typeof(Ciphertext) ~= "buffer" then error("Ciphertext must be a buffer", 2) end if not Tag or typeof(Tag) ~= "buffer" then error("Tag must be a buffer", 2) end local KeyLength = buffer.len(Key) if KeyLength ~= 16 and KeyLength ~= 24 and KeyLength ~= 32 then error("Key must be 16, 24, or 32 bytes", 2) end local KeyConfig = KEY_CONFIGS[KeyLength] local RoundKeys = ExpandKeySchedule(Key, KeyLength, buffer.create(KeyConfig.ExpandedLength)) local KeyMaterialLength = KeyConfig.MaterialLength local IVLen = buffer.len(IV) local AADLen = buffer.len(AAD or buffer.create(0)) local CryptLen = buffer.len(Ciphertext) local AuthData = AAD or buffer.create(0) local OutputBuffer = buffer.create(CryptLen) local H = buffer.create(16) local J0 = buffer.create(16) local S = buffer.create(16) local ComputedTag = buffer.create(16) EncryptBlock(RoundKeys, KeyMaterialLength, H, 0, H, 0) local Tables = PrepareJ0(H, IV, IVLen, J0) GcmGctr(RoundKeys, KeyMaterialLength, J0, Ciphertext, CryptLen, OutputBuffer) GcmHash(Tables, AuthData, AADLen, Ciphertext, CryptLen, S) Gctr(RoundKeys, KeyMaterialLength, J0, S, 16, ComputedTag) if not ConstantTimeCompare(Tag, ComputedTag) then return false, nil end return true, OutputBuffer end return AES
11,019
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Encryption/Simon.luau
--[=[ Cryptography library: Simon Cipher 64-bit ⚠️ WARNING: Simon is not very secure! For security, use AES or CHACHA20. ⚠️ Sizes: Key: 16 bytes Return type: buffer Example Usage: local Message = buffer.fromstring("Hello World") local Key = buffer.fromstring("MySecretKey12345") local Encrypted = Encrypt(Message, Key) local Decrypted = Decrypt(Encrypted, Key) --]=] --!strict --!optimize 2 --!native local ROUNDS: number = 44 local KEY_WORDS: number = 4 local BLOCK_SIZE: number = 8 local Z_SEQUENCE: {number} = { 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1 } local Simon = {} local function GenerateKeySchedule(KeyBuffer: buffer): buffer local Key = buffer.create(176) buffer.writeu32(Key, 0, buffer.readu32(KeyBuffer, 0)) buffer.writeu32(Key, 4, buffer.readu32(KeyBuffer, 4)) buffer.writeu32(Key, 8, buffer.readu32(KeyBuffer, 8)) buffer.writeu32(Key, 12, buffer.readu32(KeyBuffer, 12)) for Index = KEY_WORDS, ROUNDS - 1 do local PrevKey = buffer.readu32(Key, (Index - 1) * 4) local Temp = bit32.bxor(bit32.rrotate(PrevKey, 3), buffer.readu32(Key, (Index - 3) * 4)) local TempRotated = bit32.rrotate(Temp, 1) local C = Z_SEQUENCE[((Index - KEY_WORDS) % 62) + 1] buffer.writeu32(Key, Index * 4, bit32.bxor(bit32.bxor(buffer.readu32(Key, (Index - KEY_WORDS) * 4), bit32.bxor(Temp, TempRotated)), bit32.bxor(3, C))) end return Key end local function EncryptBlocks(CipherBuffer: buffer, PlaintextBuffer: buffer, RoundKeys: buffer, Length: number): () for Offset = 0, Length - 1, BLOCK_SIZE do local X = buffer.readu32(PlaintextBuffer, Offset) local Y = buffer.readu32(PlaintextBuffer, Offset + 4) for Round = 0, (ROUNDS - 1) * 4, 16 do X, Y = bit32.bxor(Y, bit32.bxor(bit32.bxor(bit32.band(bit32.lrotate(X, 1), bit32.lrotate(X, 8)), bit32.lrotate(X, 2)), buffer.readu32(RoundKeys, Round))), X X, Y = bit32.bxor(Y, bit32.bxor(bit32.bxor(bit32.band(bit32.lrotate(X, 1), bit32.lrotate(X, 8)), bit32.lrotate(X, 2)), buffer.readu32(RoundKeys, Round + 4))), X X, Y = bit32.bxor(Y, bit32.bxor(bit32.bxor(bit32.band(bit32.lrotate(X, 1), bit32.lrotate(X, 8)), bit32.lrotate(X, 2)), buffer.readu32(RoundKeys, Round + 8))), X X, Y = bit32.bxor(Y, bit32.bxor(bit32.bxor(bit32.band(bit32.lrotate(X, 1), bit32.lrotate(X, 8)), bit32.lrotate(X, 2)), buffer.readu32(RoundKeys, Round + 12))), X end buffer.writeu32(CipherBuffer, Offset, X) buffer.writeu32(CipherBuffer, Offset + 4, Y) end end local function DecryptBlocks(PlaintextBuffer: buffer, CipherBuffer: buffer, RoundKeys: buffer, Length: number): () for Offset = 0, Length - 1, BLOCK_SIZE do local X = buffer.readu32(CipherBuffer, Offset) local Y = buffer.readu32(CipherBuffer, Offset + 4) for Round = (ROUNDS - 1) * 4, 0, -16 do Y, X = bit32.bxor(X, bit32.bxor(bit32.bxor(bit32.band(bit32.lrotate(Y, 1), bit32.lrotate(Y, 8)), bit32.lrotate(Y, 2)), buffer.readu32(RoundKeys, Round))), Y Y, X = bit32.bxor(X, bit32.bxor(bit32.bxor(bit32.band(bit32.lrotate(Y, 1), bit32.lrotate(Y, 8)), bit32.lrotate(Y, 2)), buffer.readu32(RoundKeys, Round - 4))), Y Y, X = bit32.bxor(X, bit32.bxor(bit32.bxor(bit32.band(bit32.lrotate(Y, 1), bit32.lrotate(Y, 8)), bit32.lrotate(Y, 2)), buffer.readu32(RoundKeys, Round - 8))), Y Y, X = bit32.bxor(X, bit32.bxor(bit32.bxor(bit32.band(bit32.lrotate(Y, 1), bit32.lrotate(Y, 8)), bit32.lrotate(Y, 2)), buffer.readu32(RoundKeys, Round - 12))), Y end buffer.writeu32(PlaintextBuffer, Offset, X) buffer.writeu32(PlaintextBuffer, Offset + 4, Y) end end local function PadBuffer(InputBuffer: buffer): buffer local Length = buffer.len(InputBuffer) local Amount = BLOCK_SIZE - (Length % BLOCK_SIZE) local PaddedBuffer = buffer.create(Length + Amount) buffer.copy(PaddedBuffer, 0, InputBuffer, 0, Length) if Amount == 1 then buffer.writeu8(PaddedBuffer, Length, Amount) elseif Amount == 2 then buffer.writeu16(PaddedBuffer, Length, Amount * 0x0101) elseif Amount == 4 then buffer.writeu32(PaddedBuffer, Length, Amount * 0x01010101) else for Index = Length, Length + Amount - 1 do buffer.writeu8(PaddedBuffer, Index, Amount) end end return PaddedBuffer end local function UnpadBuffer(InputBuffer: buffer): buffer local Length = buffer.len(InputBuffer) if Length == 0 then return InputBuffer end local Amount = buffer.readu8(InputBuffer, Length - 1) local UnpaddedBuffer = buffer.create(Length - Amount) buffer.copy(UnpaddedBuffer, 0, InputBuffer, 0, Length - Amount) return UnpaddedBuffer end local function PrepareKey(KeyBuffer: buffer): buffer local KeyLength = buffer.len(KeyBuffer) local PreparedKey = buffer.create(16) if KeyLength >= 16 then buffer.writeu32(PreparedKey, 0, buffer.readu32(KeyBuffer, 0)) buffer.writeu32(PreparedKey, 4, buffer.readu32(KeyBuffer, 4)) buffer.writeu32(PreparedKey, 8, buffer.readu32(KeyBuffer, 8)) buffer.writeu32(PreparedKey, 12, buffer.readu32(KeyBuffer, 12)) else buffer.copy(PreparedKey, 0, KeyBuffer, 0, KeyLength) for ZeroStart = KeyLength, 15, 4 do if ZeroStart + 3 < 16 then buffer.writeu32(PreparedKey, ZeroStart, 0) else for ByteIndex = ZeroStart, 15 do buffer.writeu8(PreparedKey, ByteIndex, 0) end break end end end return PreparedKey end function Simon.Encrypt(PlaintextBuffer: buffer, KeyBuffer: buffer): buffer local PaddedPlaintext = PadBuffer(PlaintextBuffer) local PreparedKey = PrepareKey(KeyBuffer) local RoundKeys = GenerateKeySchedule(PreparedKey) local Length = buffer.len(PaddedPlaintext) local CipherBuffer = buffer.create(Length) EncryptBlocks(CipherBuffer, PaddedPlaintext, RoundKeys, Length) return CipherBuffer end function Simon.Decrypt(CipherBuffer: buffer, KeyBuffer: buffer): buffer local PreparedKey = PrepareKey(KeyBuffer) local RoundKeys = GenerateKeySchedule(PreparedKey) local Length = buffer.len(CipherBuffer) local PlaintextBuffer = buffer.create(Length) DecryptBlocks(PlaintextBuffer, CipherBuffer, RoundKeys, Length) return UnpadBuffer(PlaintextBuffer) end return Simon
2,088
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Encryption/Speck.luau
--[=[ Cryptography library: Speck ⚠️ WARNING: Speck is not very secure! For security, use AES or CHACHA20. ⚠️ Sizes: Key: 8 bytes Return type: buffer Example Usage: local Message = buffer.fromstring("Hello World") local Key = buffer.fromstring("Key") local Encrypted = Encrypt(Message, Key) local Decrypted = Decrypt(Encrypted, Key) --]=] --!strict --!optimize 2 --!native local Speck = {} local function EncryptBlocks(CipherBuffer: buffer, PlaintextBuffer: buffer, KeyBuffer: buffer, Length: number): () for Offset = 0, Length - 1, 8 do local Y = buffer.readu32(PlaintextBuffer, Offset) local X = buffer.readu32(PlaintextBuffer, Offset + 4) local B = buffer.readu32(KeyBuffer, 0) local A = buffer.readu32(KeyBuffer, 4) X = bit32.bxor(bit32.rrotate(X, 8) + Y, B) Y = bit32.bxor(bit32.lrotate(Y, 3), X) for RoundIndex = 0, 27, 4 do A = bit32.bxor(bit32.rrotate(A, 8) + B, RoundIndex) B = bit32.bxor(bit32.lrotate(B, 3), A) X = bit32.bxor(bit32.rrotate(X, 8) + Y, B) Y = bit32.bxor(bit32.lrotate(Y, 3), X) A = bit32.bxor(bit32.rrotate(A, 8) + B, RoundIndex + 1) B = bit32.bxor(bit32.lrotate(B, 3), A) X = bit32.bxor(bit32.rrotate(X, 8) + Y, B) Y = bit32.bxor(bit32.lrotate(Y, 3), X) A = bit32.bxor(bit32.rrotate(A, 8) + B, RoundIndex + 2) B = bit32.bxor(bit32.lrotate(B, 3), A) X = bit32.bxor(bit32.rrotate(X, 8) + Y, B) Y = bit32.bxor(bit32.lrotate(Y, 3), X) A = bit32.bxor(bit32.rrotate(A, 8) + B, RoundIndex + 3) B = bit32.bxor(bit32.lrotate(B, 3), A) X = bit32.bxor(bit32.rrotate(X, 8) + Y, B) Y = bit32.bxor(bit32.lrotate(Y, 3), X) end A = bit32.bxor(bit32.rrotate(A, 8) + B, 28) B = bit32.bxor(bit32.lrotate(B, 3), A) X = bit32.bxor(bit32.rrotate(X, 8) + Y, B) Y = bit32.bxor(bit32.lrotate(Y, 3), X) A = bit32.bxor(bit32.rrotate(A, 8) + B, 29) B = bit32.bxor(bit32.lrotate(B, 3), A) X = bit32.bxor(bit32.rrotate(X, 8) + Y, B) Y = bit32.bxor(bit32.lrotate(Y, 3), X) A = bit32.bxor(bit32.rrotate(A, 8) + B, 30) B = bit32.bxor(bit32.lrotate(B, 3), A) X = bit32.bxor(bit32.rrotate(X, 8) + Y, B) Y = bit32.bxor(bit32.lrotate(Y, 3), X) buffer.writeu32(CipherBuffer, Offset, Y) buffer.writeu32(CipherBuffer, Offset + 4, X) end end local function DecryptBlocks(PlaintextBuffer: buffer, CipherBuffer: buffer, RoundKeys: buffer, Length: number): () for Offset = 0, Length - 1, 8 do local Y = buffer.readu32(CipherBuffer, Offset) local X = buffer.readu32(CipherBuffer, Offset + 4) for RoundIndex = 27, 0, -4 do Y = bit32.rrotate(bit32.bxor(Y, X), 3) X = bit32.lrotate(bit32.bxor(X, buffer.readu32(RoundKeys, (RoundIndex + 4) * 4)) - Y, 8) Y = bit32.rrotate(bit32.bxor(Y, X), 3) X = bit32.lrotate(bit32.bxor(X, buffer.readu32(RoundKeys, (RoundIndex + 3) * 4)) - Y, 8) Y = bit32.rrotate(bit32.bxor(Y, X), 3) X = bit32.lrotate(bit32.bxor(X, buffer.readu32(RoundKeys, (RoundIndex + 2) * 4)) - Y, 8) Y = bit32.rrotate(bit32.bxor(Y, X), 3) X = bit32.lrotate(bit32.bxor(X, buffer.readu32(RoundKeys, (RoundIndex + 1) * 4)) - Y, 8) end Y = bit32.rrotate(bit32.bxor(Y, X), 3) X = bit32.lrotate(bit32.bxor(X, buffer.readu32(RoundKeys, 12)) - Y, 8) Y = bit32.rrotate(bit32.bxor(Y, X), 3) X = bit32.lrotate(bit32.bxor(X, buffer.readu32(RoundKeys, 8)) - Y, 8) Y = bit32.rrotate(bit32.bxor(Y, X), 3) X = bit32.lrotate(bit32.bxor(X, buffer.readu32(RoundKeys, 4)) - Y, 8) Y = bit32.rrotate(bit32.bxor(Y, X), 3) X = bit32.lrotate(bit32.bxor(X, buffer.readu32(RoundKeys, 0)) - Y, 8) buffer.writeu32(PlaintextBuffer, Offset, Y) buffer.writeu32(PlaintextBuffer, Offset + 4, X) end end local function PadBuffer(InputBuffer: buffer): buffer local Length = buffer.len(InputBuffer) local Amount = 8 - (Length % 8) local PaddedBuffer = buffer.create(Length + Amount) buffer.copy(PaddedBuffer, 0, InputBuffer, 0, Length) if Amount == 8 then buffer.writeu32(PaddedBuffer, Length, 0x08080808) buffer.writeu32(PaddedBuffer, Length + 4, 0x08080808) elseif Amount == 4 then buffer.writeu32(PaddedBuffer, Length, Amount * 0x01010101) else for Index = Length, Length + Amount - 1 do buffer.writeu8(PaddedBuffer, Index, Amount) end end return PaddedBuffer end local function UnpadBuffer(InputBuffer: buffer): buffer local Length = buffer.len(InputBuffer) if Length == 0 then return InputBuffer end local Amount = buffer.readu8(InputBuffer, Length - 1) local UnpaddedBuffer = buffer.create(Length - Amount) buffer.copy(UnpaddedBuffer, 0, InputBuffer, 0, Length - Amount) return UnpaddedBuffer end local function PadKey(KeyBuffer: buffer): buffer local KeyLength = buffer.len(KeyBuffer) local PreparedKey = buffer.create(8) if KeyLength >= 8 then buffer.writeu32(PreparedKey, 0, buffer.readu32(KeyBuffer, 0)) buffer.writeu32(PreparedKey, 4, buffer.readu32(KeyBuffer, 4)) else buffer.copy(PreparedKey, 0, KeyBuffer, 0, KeyLength) for Index = KeyLength, 7 do buffer.writeu8(PreparedKey, Index, 0) end end return PreparedKey end local function ExpandKey(KeyBuffer: buffer): buffer local B = buffer.readu32(KeyBuffer, 0) local A = buffer.readu32(KeyBuffer, 4) local RoundKeys = buffer.create(128) buffer.writeu32(RoundKeys, 0, B) for RoundIndex = 0, 29, 2 do A = bit32.bxor(bit32.rrotate(A, 8) + B, RoundIndex) B = bit32.bxor(bit32.lrotate(B, 3), A) buffer.writeu32(RoundKeys, (RoundIndex + 1) * 4, B) A = bit32.bxor(bit32.rrotate(A, 8) + B, RoundIndex + 1) B = bit32.bxor(bit32.lrotate(B, 3), A) buffer.writeu32(RoundKeys, (RoundIndex + 2) * 4, B) end A = bit32.bxor(bit32.rrotate(A, 8) + B, 30) B = bit32.bxor(bit32.lrotate(B, 3), A) buffer.writeu32(RoundKeys, 124, B) return RoundKeys end function Speck.Encrypt(PlaintextBuffer: buffer, KeyBuffer: buffer): buffer local PaddedPlainText = PadBuffer(PlaintextBuffer) local PreparedKey = PadKey(KeyBuffer) local Length = buffer.len(PaddedPlainText) local CipherBuffer = buffer.create(Length) EncryptBlocks(CipherBuffer, PaddedPlainText, PreparedKey, Length) return CipherBuffer end function Speck.Decrypt(CipherBuffer: buffer, KeyBuffer: buffer): buffer local PreparedKey = PadKey(KeyBuffer) local Length = buffer.len(CipherBuffer) local PlainTextBuffer = buffer.create(Length) local RoundKeys = ExpandKey(PreparedKey) DecryptBlocks(PlainTextBuffer, CipherBuffer, RoundKeys, Length) return UnpadBuffer(PlainTextBuffer) end return Speck
2,257
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Encryption/XOR.luau
--[=[ Cryptography library: XOR Symmetric Cipher ⚠️ WARNING: XOR is not cryptographically secure! Do not use the same key twice! For security, use AES or CHACHA20. ⚠️ Return type: buffer Example Usage: local Message = buffer.fromstring("Hello World") local Key = buffer.fromstring("MySecretKey12345") -- Fastest when its a multiple of 4 or is longer than the message local Encrypted = XOR(Message, Key) local Decrypted = XOR(Encrypted, Key) --]=] --!strict --!optimize 2 --!native local function XOR(StringBuffer: buffer, KeyBuffer: buffer): buffer local StringLength = buffer.len(StringBuffer) local KeyLength = buffer.len(KeyBuffer) local OutputBuffer = buffer.create(StringLength) buffer.copy(OutputBuffer, 0, StringBuffer, 0, StringLength) if KeyLength == 1 then local KeyByte = buffer.readu8(KeyBuffer, 0) local KeyWord = bit32.bor( KeyByte, bit32.lshift(KeyByte, 8), bit32.lshift(KeyByte, 16), bit32.lshift(KeyByte, 24) ) local Offset = 0 while Offset + 3 < StringLength do buffer.writeu32(OutputBuffer, Offset, bit32.bxor(buffer.readu32(OutputBuffer, Offset), KeyWord)) Offset += 4 end while Offset < StringLength do buffer.writeu8(OutputBuffer, Offset, bit32.bxor(buffer.readu8(OutputBuffer, Offset), KeyByte)) Offset += 1 end return OutputBuffer end if KeyLength == 4 then local KeyWord = buffer.readu32(KeyBuffer, 0) local Offset = 0 while Offset + 3 < StringLength do buffer.writeu32(OutputBuffer, Offset, bit32.bxor(buffer.readu32(OutputBuffer, Offset), KeyWord)) Offset += 4 end for Index = 0, StringLength - Offset - 1 do local ByteOffset = Offset + Index buffer.writeu8(OutputBuffer, ByteOffset, bit32.bxor( buffer.readu8(OutputBuffer, ByteOffset), buffer.readu8(KeyBuffer, Index) )) end return OutputBuffer end local ExtendedKeyLength = math.min(StringLength, KeyLength * 256) local ExtendedKeyBuffer = buffer.create(ExtendedKeyLength) local Pos = 0 while Pos < ExtendedKeyLength do local CopyLen = math.min(KeyLength, ExtendedKeyLength - Pos) buffer.copy(ExtendedKeyBuffer, Pos, KeyBuffer, 0, CopyLen) Pos += CopyLen end local StringOffset = 0 while StringOffset < StringLength do local ChunkSize = math.min(ExtendedKeyLength, StringLength - StringOffset) local KeyOffset = 0 while KeyOffset + 3 < ChunkSize and StringOffset + KeyOffset + 3 < StringLength do local Offset = StringOffset + KeyOffset buffer.writeu32(OutputBuffer, Offset, bit32.bxor( buffer.readu32(OutputBuffer, Offset), buffer.readu32(ExtendedKeyBuffer, KeyOffset) )) KeyOffset += 4 end while KeyOffset < ChunkSize and StringOffset + KeyOffset < StringLength do local Offset = StringOffset + KeyOffset buffer.writeu8(OutputBuffer, Offset, bit32.bxor( buffer.readu8(OutputBuffer, Offset), buffer.readu8(ExtendedKeyBuffer, KeyOffset) )) KeyOffset += 1 end StringOffset += ChunkSize end return OutputBuffer end return XOR
839
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Encryption/init.luau
--!strict local Algorithms = table.freeze({ AEAD = require("@self/AEAD"), AES = require("@self/AES"), XOR = require("@self/XOR"), Simon = require("@self/Simon"), Speck = require("@self/Speck") }) return Algorithms
62
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/Blake2b.luau
--[=[ Cryptography library: BLAKE2b Return type: string Example usage: local Message = buffer.fromstring("Hello World") -- BLAKE2b-128 (128-bit output) local Result128 = BLAKE2b(Message, 16) -- BLAKE2b-256 (256-bit output) local Result256 = BLAKE2b(Message, 32) -- BLAKE2b-384 (384-bit output) local Result384 = BLAKE2b(Message, 48) -- BLAKE2b-512 (512-bit output, default) local Result512 = BLAKE2b(Message, 64) -- or simply: local Result512 = BLAKE2b(Message) -- With optional key local OptionalKey = buffer.fromstring("MyKey") local Result = BLAKE2b(Message, 64, OptionalKey) --]=] --!strict --!optimize 2 --!native local BLOCK_SIZE_BYTES = 128 local DEFAULT_OUTPUT_BYTES = 64 local BLAKE2B_MIN_OUTPUT_BYTES = 1 local BLAKE2B_MAX_OUTPUT_BYTES = 64 local BLAKE2B_MAX_KEY_BYTES = 64 local InitVectors = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, 0xf3bcc908, 0x84caa73b, 0xfe94f82b, 0x5f1d36f1, 0xade682d1, 0x2b3e6c1f, 0xfb41bd6b, 0x137e2179 } local PERMUTATION_TABLE = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 15, 11, 5, 9, 10, 16, 14, 7, 2, 13, 1, 3, 12, 8, 6, 4, 12, 9, 13, 1, 6, 3, 16, 14, 11, 15, 4, 7, 8, 2, 10, 5, 8, 10, 4, 2, 14, 13, 12, 15, 3, 7, 6, 11, 5, 1, 16, 9, 10, 1, 6, 8, 3, 5, 11, 16, 15, 2, 12, 13, 7, 9, 4, 14, 3, 13, 7, 11, 1, 12, 9, 4, 5, 14, 8, 6, 16, 15, 2, 10, 13, 6, 2, 16, 15, 14, 5, 11, 1, 8, 7, 4, 10, 3, 9, 12, 14, 12, 8, 15, 13, 2, 4, 10, 6, 1, 16, 5, 9, 7, 3, 11, 7, 16, 15, 10, 12, 4, 1, 9, 13, 3, 14, 8, 2, 5, 11, 6, 11, 3, 9, 5, 8, 7, 2, 6, 16, 12, 10, 15, 4, 13, 14, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 15, 11, 5, 9, 10, 16, 14, 7, 2, 13, 1, 3, 12, 8, 6, 4 } local WH9, WH10, WH11, WH12, WH13, WH14, WH15, WH16 = InitVectors[1], InitVectors[2], InitVectors[3], InitVectors[4], InitVectors[5], InitVectors[6], InitVectors[7], InitVectors[8] local WL9, WL10, WL11, WL12, WL13, WL14, WL15, WL16 = InitVectors[9], InitVectors[10], InitVectors[11], InitVectors[12], InitVectors[13], InitVectors[14], InitVectors[15], InitVectors[16] local function ExtractWordsFromBlock(InputBuffer: buffer, StartOffset: number, HighWords: {number}, LowWords: {number}) for WordIdx = 1, 16 do local BytePos = StartOffset + (WordIdx - 1) * 8 LowWords[WordIdx] = buffer.readu32(InputBuffer, BytePos) HighWords[WordIdx] = buffer.readu32(InputBuffer, BytePos + 4) end end local function ProcessCompressionRound(HighWords: {number}, LowWords: {number}, ByteCounter: number, FinalBlock: boolean, StateHigh: {number}, StateLow: {number}) local WH1, WH2, WH3, WH4, WH5, WH6, WH7, WH8 = StateHigh[1], StateHigh[2], StateHigh[3], StateHigh[4], StateHigh[5], StateHigh[6], StateHigh[7], StateHigh[8] local WL1, WL2, WL3, WL4, WL5, WL6, WL7, WL8 = StateLow[1], StateLow[2], StateLow[3], StateLow[4], StateLow[5], StateLow[6], StateLow[7], StateLow[8] local WorkH9, WorkH10, WorkH11, WorkH12, WorkH13, WorkH14, WorkH15, WorkH16 = WH9, WH10, WH11, WH12, WH13, WH14, WH15, WH16 local WorkL9, WorkL10, WorkL11, WorkL12, WorkL13, WorkL14, WorkL15, WorkL16 = WL9, WL10, WL11, WL12, WL13, WL14, WL15, WL16 WorkH13 = bit32.bxor(WorkH13, ByteCounter // 0x100000000) WorkL13 = bit32.bxor(WorkL13, bit32.bor(ByteCounter, 0)) if FinalBlock then WorkH15 = bit32.bnot(WorkH15) WorkL15 = bit32.bnot(WorkL15) end local CarryBits, MsgHighX, MsgLowX, MsgHighY, MsgLowY = 0, 0, 0, 0, 0 local Permutation = PERMUTATION_TABLE for RoundNum = 1, 12 do local ScheduleBase = (RoundNum - 1) * 16 local S1, S2 = Permutation[ScheduleBase + 1], Permutation[ScheduleBase + 2] MsgHighX, MsgLowX = HighWords[S1], LowWords[S1] MsgHighY, MsgLowY = HighWords[S2], LowWords[S2] CarryBits = WL1 + WL5 + MsgLowX WH1 += WH5 + MsgHighX + CarryBits // 0x100000000 WL1 = bit32.bor(CarryBits, 0) CarryBits = WorkH13 WorkH13 = bit32.bxor(WorkL13, WL1) WorkL13 = bit32.bxor(CarryBits, WH1) CarryBits = WorkL9 + WorkL13 WorkH9 += WorkH13 + CarryBits // 0x100000000 WorkL9 = bit32.bor(CarryBits, 0) CarryBits = WH5 WH5 = bit32.bxor(bit32.rshift(WH5, 24), bit32.lshift(WL5, 8), bit32.rshift(WorkH9, 24), bit32.lshift(WorkL9, 8)) WL5 = bit32.bxor(bit32.rshift(WL5, 24), bit32.lshift(CarryBits, 8), bit32.rshift(WorkL9, 24), bit32.lshift(WorkH9, 8)) CarryBits = WL1 + WL5 + MsgLowY WH1 += WH5 + MsgHighY + CarryBits // 0x100000000 WL1 = bit32.bor(CarryBits, 0) CarryBits = WorkH13 WorkH13 = bit32.bxor(bit32.rshift(WorkH13, 16), bit32.lshift(WorkL13, 16), bit32.rshift(WH1, 16), bit32.lshift(WL1, 16)) WorkL13 = bit32.bxor(bit32.rshift(WorkL13, 16), bit32.lshift(CarryBits, 16), bit32.rshift(WL1, 16), bit32.lshift(WH1, 16)) CarryBits = WorkL9 + WorkL13 WorkH9 += WorkH13 + CarryBits // 0x100000000 WorkL9 = bit32.bor(CarryBits, 0) CarryBits = WH5 WH5 = bit32.bxor(bit32.lshift(WH5, 1), bit32.rshift(WL5, 31), bit32.lshift(WorkH9, 1), bit32.rshift(WorkL9, 31)) WL5 = bit32.bxor(bit32.lshift(WL5, 1), bit32.rshift(CarryBits, 31), bit32.lshift(WorkL9, 1), bit32.rshift(WorkH9, 31)) local S3, S4 = Permutation[ScheduleBase + 3], Permutation[ScheduleBase + 4] MsgHighX, MsgLowX = HighWords[S3], LowWords[S3] MsgHighY, MsgLowY = HighWords[S4], LowWords[S4] CarryBits = WL2 + WL6 + MsgLowX WH2 += WH6 + MsgHighX + CarryBits // 0x100000000 WL2 = bit32.bor(CarryBits, 0) CarryBits = WorkH14 WorkH14 = bit32.bxor(WorkL14, WL2) WorkL14 = bit32.bxor(CarryBits, WH2) CarryBits = WorkL10 + WorkL14 WorkH10 += WorkH14 + CarryBits // 0x100000000 WorkL10 = bit32.bor(CarryBits, 0) CarryBits = WH6 WH6 = bit32.bxor(bit32.rshift(WH6, 24), bit32.lshift(WL6, 8), bit32.rshift(WorkH10, 24), bit32.lshift(WorkL10, 8)) WL6 = bit32.bxor(bit32.rshift(WL6, 24), bit32.lshift(CarryBits, 8), bit32.rshift(WorkL10, 24), bit32.lshift(WorkH10, 8)) CarryBits = WL2 + WL6 + MsgLowY WH2 += WH6 + MsgHighY + CarryBits // 0x100000000 WL2 = bit32.bor(CarryBits, 0) CarryBits = WorkH14 WorkH14 = bit32.bxor(bit32.rshift(WorkH14, 16), bit32.lshift(WorkL14, 16), bit32.rshift(WH2, 16), bit32.lshift(WL2, 16)) WorkL14 = bit32.bxor(bit32.rshift(WorkL14, 16), bit32.lshift(CarryBits, 16), bit32.rshift(WL2, 16), bit32.lshift(WH2, 16)) CarryBits = WorkL10 + WorkL14 WorkH10 += WorkH14 + CarryBits // 0x100000000 WorkL10 = bit32.bor(CarryBits, 0) CarryBits = WH6 WH6 = bit32.bxor(bit32.lshift(WH6, 1), bit32.rshift(WL6, 31), bit32.lshift(WorkH10, 1), bit32.rshift(WorkL10, 31)) WL6 = bit32.bxor(bit32.lshift(WL6, 1), bit32.rshift(CarryBits, 31), bit32.lshift(WorkL10, 1), bit32.rshift(WorkH10, 31)) local S5, S6 = Permutation[ScheduleBase + 5], Permutation[ScheduleBase + 6] MsgHighX, MsgLowX = HighWords[S5], LowWords[S5] MsgHighY, MsgLowY = HighWords[S6], LowWords[S6] CarryBits = WL3 + WL7 + MsgLowX WH3 += WH7 + MsgHighX + CarryBits // 0x100000000 WL3 = bit32.bor(CarryBits, 0) CarryBits = WorkH15 WorkH15 = bit32.bxor(WorkL15, WL3) WorkL15 = bit32.bxor(CarryBits, WH3) CarryBits = WorkL11 + WorkL15 WorkH11 += WorkH15 + CarryBits // 0x100000000 WorkL11 = bit32.bor(CarryBits, 0) CarryBits = WH7 WH7 = bit32.bxor(bit32.rshift(WH7, 24), bit32.lshift(WL7, 8), bit32.rshift(WorkH11, 24), bit32.lshift(WorkL11, 8)) WL7 = bit32.bxor(bit32.rshift(WL7, 24), bit32.lshift(CarryBits, 8), bit32.rshift(WorkL11, 24), bit32.lshift(WorkH11, 8)) CarryBits = WL3 + WL7 + MsgLowY WH3 += WH7 + MsgHighY + CarryBits // 0x100000000 WL3 = bit32.bor(CarryBits, 0) CarryBits = WorkH15 WorkH15 = bit32.bxor(bit32.rshift(WorkH15, 16), bit32.lshift(WorkL15, 16), bit32.rshift(WH3, 16), bit32.lshift(WL3, 16)) WorkL15 = bit32.bxor(bit32.rshift(WorkL15, 16), bit32.lshift(CarryBits, 16), bit32.rshift(WL3, 16), bit32.lshift(WH3, 16)) CarryBits = WorkL11 + WorkL15 WorkH11 += WorkH15 + CarryBits // 0x100000000 WorkL11 = bit32.bor(CarryBits, 0) CarryBits = WH7 WH7 = bit32.bxor(bit32.lshift(WH7, 1), bit32.rshift(WL7, 31), bit32.lshift(WorkH11, 1), bit32.rshift(WorkL11, 31)) WL7 = bit32.bxor(bit32.lshift(WL7, 1), bit32.rshift(CarryBits, 31), bit32.lshift(WorkL11, 1), bit32.rshift(WorkH11, 31)) local S7, S8 = Permutation[ScheduleBase + 7], Permutation[ScheduleBase + 8] MsgHighX, MsgLowX = HighWords[S7], LowWords[S7] MsgHighY, MsgLowY = HighWords[S8], LowWords[S8] CarryBits = WL4 + WL8 + MsgLowX WH4 += WH8 + MsgHighX + CarryBits // 0x100000000 WL4 = bit32.bor(CarryBits, 0) CarryBits = WorkH16 WorkH16 = bit32.bxor(WorkL16, WL4) WorkL16 = bit32.bxor(CarryBits, WH4) CarryBits = WorkL12 + WorkL16 WorkH12 += WorkH16 + CarryBits // 0x100000000 WorkL12 = bit32.bor(CarryBits, 0) CarryBits = WH8 WH8 = bit32.bxor(bit32.rshift(WH8, 24), bit32.lshift(WL8, 8), bit32.rshift(WorkH12, 24), bit32.lshift(WorkL12, 8)) WL8 = bit32.bxor(bit32.rshift(WL8, 24), bit32.lshift(CarryBits, 8), bit32.rshift(WorkL12, 24), bit32.lshift(WorkH12, 8)) CarryBits = WL4 + WL8 + MsgLowY WH4 += WH8 + MsgHighY + CarryBits // 0x100000000 WL4 = bit32.bor(CarryBits, 0) CarryBits = WorkH16 WorkH16 = bit32.bxor(bit32.rshift(WorkH16, 16), bit32.lshift(WorkL16, 16), bit32.rshift(WH4, 16), bit32.lshift(WL4, 16)) WorkL16 = bit32.bxor(bit32.rshift(WorkL16, 16), bit32.lshift(CarryBits, 16), bit32.rshift(WL4, 16), bit32.lshift(WH4, 16)) CarryBits = WorkL12 + WorkL16 WorkH12 += WorkH16 + CarryBits // 0x100000000 WorkL12 = bit32.bor(CarryBits, 0) CarryBits = WH8 WH8 = bit32.bxor(bit32.lshift(WH8, 1), bit32.rshift(WL8, 31), bit32.lshift(WorkH12, 1), bit32.rshift(WorkL12, 31)) WL8 = bit32.bxor(bit32.lshift(WL8, 1), bit32.rshift(CarryBits, 31), bit32.lshift(WorkL12, 1), bit32.rshift(WorkH12, 31)) local S9, S10 = Permutation[ScheduleBase + 9], Permutation[ScheduleBase + 10] MsgHighX, MsgLowX = HighWords[S9], LowWords[S9] MsgHighY, MsgLowY = HighWords[S10], LowWords[S10] CarryBits = WL1 + WL6 + MsgLowX WH1 += WH6 + MsgHighX + CarryBits // 0x100000000 WL1 = bit32.bor(CarryBits, 0) CarryBits = WorkH16 WorkH16 = bit32.bxor(WorkL16, WL1) WorkL16 = bit32.bxor(CarryBits, WH1) CarryBits = WorkL11 + WorkL16 WorkH11 += WorkH16 + CarryBits // 0x100000000 WorkL11 = bit32.bor(CarryBits, 0) CarryBits = WH6 WH6 = bit32.bxor(bit32.rshift(WH6, 24), bit32.lshift(WL6, 8), bit32.rshift(WorkH11, 24), bit32.lshift(WorkL11, 8)) WL6 = bit32.bxor(bit32.rshift(WL6, 24), bit32.lshift(CarryBits, 8), bit32.rshift(WorkL11, 24), bit32.lshift(WorkH11, 8)) CarryBits = WL1 + WL6 + MsgLowY WH1 += WH6 + MsgHighY + CarryBits // 0x100000000 WL1 = bit32.bor(CarryBits, 0) CarryBits = WorkH16 WorkH16 = bit32.bxor(bit32.rshift(WorkH16, 16), bit32.lshift(WorkL16, 16), bit32.rshift(WH1, 16), bit32.lshift(WL1, 16)) WorkL16 = bit32.bxor(bit32.rshift(WorkL16, 16), bit32.lshift(CarryBits, 16), bit32.rshift(WL1, 16), bit32.lshift(WH1, 16)) CarryBits = WorkL11 + WorkL16 WorkH11 += WorkH16 + CarryBits // 0x100000000 WorkL11 = bit32.bor(CarryBits, 0) CarryBits = WH6 WH6 = bit32.bxor(bit32.lshift(WH6, 1), bit32.rshift(WL6, 31), bit32.lshift(WorkH11, 1), bit32.rshift(WorkL11, 31)) WL6 = bit32.bxor(bit32.lshift(WL6, 1), bit32.rshift(CarryBits, 31), bit32.lshift(WorkL11, 1), bit32.rshift(WorkH11, 31)) local S11, S12 = Permutation[ScheduleBase + 11], Permutation[ScheduleBase + 12] MsgHighX, MsgLowX = HighWords[S11], LowWords[S11] MsgHighY, MsgLowY = HighWords[S12], LowWords[S12] CarryBits = WL2 + WL7 + MsgLowX WH2 += WH7 + MsgHighX + CarryBits // 0x100000000 WL2 = bit32.bor(CarryBits, 0) CarryBits = WorkH13 WorkH13 = bit32.bxor(WorkL13, WL2) WorkL13 = bit32.bxor(CarryBits, WH2) CarryBits = WorkL12 + WorkL13 WorkH12 += WorkH13 + CarryBits // 0x100000000 WorkL12 = bit32.bor(CarryBits, 0) CarryBits = WH7 WH7 = bit32.bxor(bit32.rshift(WH7, 24), bit32.lshift(WL7, 8), bit32.rshift(WorkH12, 24), bit32.lshift(WorkL12, 8)) WL7 = bit32.bxor(bit32.rshift(WL7, 24), bit32.lshift(CarryBits, 8), bit32.rshift(WorkL12, 24), bit32.lshift(WorkH12, 8)) CarryBits = WL2 + WL7 + MsgLowY WH2 += WH7 + MsgHighY + CarryBits // 0x100000000 WL2 = bit32.bor(CarryBits, 0) CarryBits = WorkH13 WorkH13 = bit32.bxor(bit32.rshift(WorkH13, 16), bit32.lshift(WorkL13, 16), bit32.rshift(WH2, 16), bit32.lshift(WL2, 16)) WorkL13 = bit32.bxor(bit32.rshift(WorkL13, 16), bit32.lshift(CarryBits, 16), bit32.rshift(WL2, 16), bit32.lshift(WH2, 16)) CarryBits = WorkL12 + WorkL13 WorkH12 += WorkH13 + CarryBits // 0x100000000 WorkL12 = bit32.bor(CarryBits, 0) CarryBits = WH7 WH7 = bit32.bxor(bit32.lshift(WH7, 1), bit32.rshift(WL7, 31), bit32.lshift(WorkH12, 1), bit32.rshift(WorkL12, 31)) WL7 = bit32.bxor(bit32.lshift(WL7, 1), bit32.rshift(CarryBits, 31), bit32.lshift(WorkL12, 1), bit32.rshift(WorkH12, 31)) local S13, S14 = Permutation[ScheduleBase + 13], Permutation[ScheduleBase + 14] MsgHighX, MsgLowX = HighWords[S13], LowWords[S13] MsgHighY, MsgLowY = HighWords[S14], LowWords[S14] CarryBits = WL3 + WL8 + MsgLowX WH3 += WH8 + MsgHighX + CarryBits // 0x100000000 WL3 = bit32.bor(CarryBits, 0) CarryBits = WorkH14 WorkH14 = bit32.bxor(WorkL14, WL3) WorkL14 = bit32.bxor(CarryBits, WH3) CarryBits = WorkL9 + WorkL14 WorkH9 += WorkH14 + CarryBits // 0x100000000 WorkL9 = bit32.bor(CarryBits, 0) CarryBits = WH8 WH8 = bit32.bxor(bit32.rshift(WH8, 24), bit32.lshift(WL8, 8), bit32.rshift(WorkH9, 24), bit32.lshift(WorkL9, 8)) WL8 = bit32.bxor(bit32.rshift(WL8, 24), bit32.lshift(CarryBits, 8), bit32.rshift(WorkL9, 24), bit32.lshift(WorkH9, 8)) CarryBits = WL3 + WL8 + MsgLowY WH3 += WH8 + MsgHighY + CarryBits // 0x100000000 WL3 = bit32.bor(CarryBits, 0) CarryBits = WorkH14 WorkH14 = bit32.bxor(bit32.rshift(WorkH14, 16), bit32.lshift(WorkL14, 16), bit32.rshift(WH3, 16), bit32.lshift(WL3, 16)) WorkL14 = bit32.bxor(bit32.rshift(WorkL14, 16), bit32.lshift(CarryBits, 16), bit32.rshift(WL3, 16), bit32.lshift(WH3, 16)) CarryBits = WorkL9 + WorkL14 WorkH9 += WorkH14 + CarryBits // 0x100000000 WorkL9 = bit32.bor(CarryBits, 0) CarryBits = WH8 WH8 = bit32.bxor(bit32.lshift(WH8, 1), bit32.rshift(WL8, 31), bit32.lshift(WorkH9, 1), bit32.rshift(WorkL9, 31)) WL8 = bit32.bxor(bit32.lshift(WL8, 1), bit32.rshift(CarryBits, 31), bit32.lshift(WorkL9, 1), bit32.rshift(WorkH9, 31)) local S15, S16 = Permutation[ScheduleBase + 15], Permutation[ScheduleBase + 16] MsgHighX, MsgLowX = HighWords[S15], LowWords[S15] MsgHighY, MsgLowY = HighWords[S16], LowWords[S16] CarryBits = WL4 + WL5 + MsgLowX WH4 += WH5 + MsgHighX + CarryBits // 0x100000000 WL4 = bit32.bor(CarryBits, 0) CarryBits = WorkH15 WorkH15 = bit32.bxor(WorkL15, WL4) WorkL15 = bit32.bxor(CarryBits, WH4) CarryBits = WorkL10 + WorkL15 WorkH10 += WorkH15 + CarryBits // 0x100000000 WorkL10 = bit32.bor(CarryBits, 0) CarryBits = WH5 WH5 = bit32.bxor(bit32.rshift(WH5, 24), bit32.lshift(WL5, 8), bit32.rshift(WorkH10, 24), bit32.lshift(WorkL10, 8)) WL5 = bit32.bxor(bit32.rshift(WL5, 24), bit32.lshift(CarryBits, 8), bit32.rshift(WorkL10, 24), bit32.lshift(WorkH10, 8)) CarryBits = WL4 + WL5 + MsgLowY WH4 += WH5 + MsgHighY + CarryBits // 0x100000000 WL4 = bit32.bor(CarryBits, 0) CarryBits = WorkH15 WorkH15 = bit32.bxor(bit32.rshift(WorkH15, 16), bit32.lshift(WorkL15, 16), bit32.rshift(WH4, 16), bit32.lshift(WL4, 16)) WorkL15 = bit32.bxor(bit32.rshift(WorkL15, 16), bit32.lshift(CarryBits, 16), bit32.rshift(WL4, 16), bit32.lshift(WH4, 16)) CarryBits = WorkL10 + WorkL15 WorkH10 += WorkH15 + CarryBits // 0x100000000 WorkL10 = bit32.bor(CarryBits, 0) CarryBits = WH5 WH5 = bit32.bxor(bit32.lshift(WH5, 1), bit32.rshift(WL5, 31), bit32.lshift(WorkH10, 1), bit32.rshift(WorkL10, 31)) WL5 = bit32.bxor(bit32.lshift(WL5, 1), bit32.rshift(CarryBits, 31), bit32.lshift(WorkL10, 1), bit32.rshift(WorkH10, 31)) end StateHigh[1] = bit32.bxor(StateHigh[1], WH1, WorkH9) StateLow[1] = bit32.bxor(StateLow[1], WL1, WorkL9) StateHigh[2] = bit32.bxor(StateHigh[2], WH2, WorkH10) StateLow[2] = bit32.bxor(StateLow[2], WL2, WorkL10) StateHigh[3] = bit32.bxor(StateHigh[3], WH3, WorkH11) StateLow[3] = bit32.bxor(StateLow[3], WL3, WorkL11) StateHigh[4] = bit32.bxor(StateHigh[4], WH4, WorkH12) StateLow[4] = bit32.bxor(StateLow[4], WL4, WorkL12) StateHigh[5] = bit32.bxor(StateHigh[5], WH5, WorkH13) StateLow[5] = bit32.bxor(StateLow[5], WL5, WorkL13) StateHigh[6] = bit32.bxor(StateHigh[6], WH6, WorkH14) StateLow[6] = bit32.bxor(StateLow[6], WL6, WorkL14) StateHigh[7] = bit32.bxor(StateHigh[7], WH7, WorkH15) StateLow[7] = bit32.bxor(StateLow[7], WL7, WorkL15) StateHigh[8] = bit32.bxor(StateHigh[8], WH8, WorkH16) StateLow[8] = bit32.bxor(StateLow[8], WL8, WorkL16) end local function HashDigest(InputData: buffer, OutputLength: number, KeyData: buffer?): (string, buffer) local KeyLength = KeyData and buffer.len(KeyData) or 0 local DataLength = buffer.len(InputData) local StateHigh = { WH9, WH10, WH11, WH12, WH13, WH14, WH15, WH16 } local StateLow = { WL9, WL10, WL11, WL12, WL13, WL14, WL15, WL16 } StateLow[1] = bit32.bxor(StateLow[1], 0x01010000, bit32.lshift(KeyLength, 8), OutputLength) local BlockHigh = table.create(16) :: {number} local BlockLow = table.create(16) :: {number} local ProcessedBytes = KeyLength > 0 and 128 or 0 if KeyLength > 0 and KeyData then local KeyPadding = buffer.create(BLOCK_SIZE_BYTES) buffer.copy(KeyPadding, 0, KeyData) ExtractWordsFromBlock(KeyPadding, 0, BlockHigh, BlockLow) ProcessCompressionRound(BlockHigh, BlockLow, ProcessedBytes, DataLength == 0, StateHigh, StateLow) end local RemainingBytes = DataLength % BLOCK_SIZE_BYTES local FinalBlockSize = RemainingBytes == 0 and BLOCK_SIZE_BYTES or RemainingBytes for BlockStart = 0, DataLength - FinalBlockSize - 1, BLOCK_SIZE_BYTES do ExtractWordsFromBlock(InputData, BlockStart, BlockHigh, BlockLow) ProcessedBytes += BLOCK_SIZE_BYTES ProcessCompressionRound(BlockHigh, BlockLow, ProcessedBytes, false, StateHigh, StateLow) end if KeyLength == 0 or DataLength > 0 then local PaddedBlock = buffer.create(BLOCK_SIZE_BYTES) local CopyBytes = math.min(FinalBlockSize, DataLength) local CopyStart = math.max(0, DataLength - FinalBlockSize) if CopyBytes > 0 then buffer.copy(PaddedBlock, 0, InputData, CopyStart, CopyBytes) end ExtractWordsFromBlock(PaddedBlock, 0, BlockHigh, BlockLow) ProcessCompressionRound(BlockHigh, BlockLow, ProcessedBytes + CopyBytes, true, StateHigh, StateLow) end local Digest = buffer.create(OutputLength) local Offset = 0 for Index = 1, 8 do if Offset + 4 <= OutputLength then buffer.writeu32(Digest, Offset, StateLow[Index]) Offset += 4 end if Offset + 4 <= OutputLength then buffer.writeu32(Digest, Offset, StateHigh[Index]) Offset += 4 end if Offset >= OutputLength then break end end local FinalDigest = string.format( "%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x", bit32.byteswap(StateLow[1]), bit32.byteswap(StateHigh[1]), bit32.byteswap(StateLow[2]), bit32.byteswap(StateHigh[2]), bit32.byteswap(StateLow[3]), bit32.byteswap(StateHigh[3]), bit32.byteswap(StateLow[4]), bit32.byteswap(StateHigh[4]), bit32.byteswap(StateLow[5]), bit32.byteswap(StateHigh[5]), bit32.byteswap(StateLow[6]), bit32.byteswap(StateHigh[6]), bit32.byteswap(StateLow[7]), bit32.byteswap(StateHigh[7]), bit32.byteswap(StateLow[8]), bit32.byteswap(StateHigh[8]) ) return string.sub(FinalDigest, 1, OutputLength * 2), Digest end local function BLAKE2b(InputData: buffer, OutputLength: number?, KeyData: buffer?): (string, buffer) if InputData == nil then error("InputData cannot be nil", 2) end if typeof(InputData) ~= "buffer" then error(`InputData must be a buffer, got {typeof(InputData)}`, 2) end if OutputLength then if typeof(OutputLength) ~= "number" then error(`OutputLength must be a number, got {typeof(OutputLength)}`, 2) end if OutputLength ~= math.floor(OutputLength) then error(`OutputLength must be an integer, got {OutputLength}`, 2) end if OutputLength < BLAKE2B_MIN_OUTPUT_BYTES or OutputLength > BLAKE2B_MAX_OUTPUT_BYTES then error(`OutputLength must be between {BLAKE2B_MIN_OUTPUT_BYTES} and {BLAKE2B_MAX_OUTPUT_BYTES} bytes, got {OutputLength} bytes`, 2) end end if KeyData then if typeof(KeyData) ~= "buffer" then error(`KeyData must be a buffer, got {typeof(KeyData)}`, 2) end local KeyLength = buffer.len(KeyData) if KeyLength == 0 then error("KeyData cannot be empty", 2) end if KeyLength > BLAKE2B_MAX_KEY_BYTES then error(`KeyData must be at most {BLAKE2B_MAX_KEY_BYTES} bytes long, got {KeyLength} bytes`, 2) end end return HashDigest(InputData, OutputLength or DEFAULT_OUTPUT_BYTES, KeyData) end return BLAKE2b
8,620
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/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(Message, Key, 32) --------Key Derivation-------- local Context = buffer.fromstring("my context") local KeyDeriver = Blake3.DeriveKey(Context) local DerivedKey = KeyDeriver(Message, 32) --]=] --!strict --!optimize 2 --!native local Blake3 = {} 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 BLAKE3_KEY_SIZE = 32 local BLAKE3_MIN_OUTPUT_BYTES = 1 local BLAKE3_MAX_OUTPUT_BYTES = 2^32 - 1 local CHUNK_START = 0x01 local CHUNK_END = 0x02 local PARENT_FLAG = 0x04 local ROOT_FLAG = 0x08 local HASH_FLAG = 0x10 local DERIVE_CONTEXT_FLAG = 0x20 local DERIVE_MATERIAL_FLAG = 0x40 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 ENCODE_LOOKUP = buffer.create(256 * 2) do local HexChars = "0123456789abcdef" for Byte = 0, 255 do local HighNibble = bit32.rshift(Byte, 4) local LowNibble = Byte % 16 local HighChar = string.byte(HexChars, HighNibble + 1) local LowChar = string.byte(HexChars, LowNibble + 1) local Combined = HighChar + bit32.lshift(LowChar, 8) buffer.writeu16(ENCODE_LOOKUP, Byte * 2, Combined) 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 StateCv = buffer.create(CV_SIZE) local StackSize = 0 local StateCounter = 0 local StateChunkNumber = 0 local StateEndFlag = 0 local BlockSize = BLOCK_SIZE local CvSize = CV_SIZE local ExtendedCvSize = EXTENDED_CV_SIZE local StateStartFlag = CHUNK_START local ChunkStart = CHUNK_START local ChunkEnd = CHUNK_END local ParentFlag = PARENT_FLAG local RootFlag = ROOT_FLAG local FlagsParent = Flags + ParentFlag local BlockBuffer = buffer.create(BlockSize) local PopCv = buffer.create(CvSize) local MergeBlock = buffer.create(ExtendedCvSize) local StackCv = buffer.create(CvSize) local Block = buffer.create(ExtendedCvSize) buffer.copy(StateCv, 0, InitialHashVector, 0, CvSize) for BlockOffset = 0, MessageLength - BlockSize - 1, BlockSize do buffer.copy(BlockBuffer, 0, Message, BlockOffset, BlockSize) local StateFlags = Flags + StateStartFlag + StateEndFlag StateCv = Compress(StateCv, BlockBuffer, StateCounter, BlockSize, StateFlags) StateStartFlag = 0 StateChunkNumber += 1 if StateChunkNumber == 15 then StateEndFlag = ChunkEnd elseif StateChunkNumber == 16 then local MergeCv = StateCv local MergeAmount = StateCounter + 1 while MergeAmount % 2 == 0 do StackSize -= 1 buffer.copy(PopCv, 0, StateCvs, StackSize * CvSize, CvSize) buffer.copy(MergeBlock, 0, PopCv, 0, CvSize) buffer.copy(MergeBlock, CvSize, MergeCv, 0, CvSize) MergeCv = Compress(InitialHashVector, MergeBlock, 0, BlockSize, FlagsParent) MergeAmount /= 2 end buffer.copy(StateCvs, StackSize * CvSize, MergeCv, 0, CvSize) StackSize += 1 buffer.copy(StateCv, 0, InitialHashVector, 0, CvSize) StateStartFlag = ChunkStart StateCounter += 1 StateChunkNumber = 0 StateEndFlag = 0 end end local LastLength = MessageLength == 0 and 0 or ((MessageLength - 1) % BlockSize + 1) local PaddedMessage = buffer.create(BlockSize) 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 + ChunkEnd local MergeCv = Compress(StateCv, PaddedMessage, StateCounter, LastLength, StateFlags) for Index = StackSize, 2, -1 do buffer.copy(StackCv, 0, StateCvs, (Index - 1) * CvSize, CvSize) buffer.copy(Block, 0, StackCv, 0, CvSize) buffer.copy(Block, CvSize, MergeCv, 0, CvSize) MergeCv = Compress(InitialHashVector, Block, 0, BlockSize, FlagsParent) end OutputCv = InitialHashVector local FirstStackCv = buffer.create(CvSize) buffer.copy(FirstStackCv, 0, StateCvs, 0, CvSize) OutputBlock = buffer.create(ExtendedCvSize) buffer.copy(OutputBlock, 0, FirstStackCv, 0, CvSize) buffer.copy(OutputBlock, CvSize, MergeCv, 0, CvSize) OutputLength = BlockSize OutputFlags = Flags + RootFlag + ParentFlag else OutputCv = StateCv OutputBlock = PaddedMessage OutputLength = LastLength OutputFlags = Flags + StateStartFlag + ChunkEnd + RootFlag end local Output = buffer.create(Length) local OutputOffset = 0 for Index = 0, Length // BlockSize do local MessageDigest = Compress(OutputCv, OutputBlock, Index, OutputLength, OutputFlags, true) local BytesToCopy = math.min(BlockSize, Length - OutputOffset) buffer.copy(Output, OutputOffset, MessageDigest, 0, BytesToCopy) OutputOffset += BytesToCopy if OutputOffset >= Length then break end end return Output end local function ToHex(Buffer: buffer): string local Length = buffer.len(Buffer) local Hex = buffer.create(Length * 2) local Lookup = ENCODE_LOOKUP local Leftover = Length % 8 local HexCursor = 0 for Index = 0, Length - Leftover - 1, 8 do local Hex1 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index) * 2) local Hex2 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 1) * 2) local Hex3 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 2) * 2) local Hex4 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 3) * 2) local Hex5 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 4) * 2) local Hex6 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 5) * 2) local Hex7 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 6) * 2) local Hex8 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 7) * 2) buffer.writeu16(Hex, HexCursor, Hex1) buffer.writeu16(Hex, HexCursor + 2, Hex2) buffer.writeu16(Hex, HexCursor + 4, Hex3) buffer.writeu16(Hex, HexCursor + 6, Hex4) buffer.writeu16(Hex, HexCursor + 8, Hex5) buffer.writeu16(Hex, HexCursor + 10, Hex6) buffer.writeu16(Hex, HexCursor + 12, Hex7) buffer.writeu16(Hex, HexCursor + 14, Hex8) HexCursor += 16 end for Index = Length - Leftover, Length - 1 do local HexPair = buffer.readu16(Lookup, buffer.readu8(Buffer, Index) * 2) buffer.writeu16(Hex, HexCursor, HexPair) HexCursor += 2 end return buffer.tostring(Hex) end function Blake3.Digest(Message: buffer, Length: number?): (string, buffer) if Message == nil then error("Message cannot be nil", 2) end if typeof(Message) ~= "buffer" then error(`Message must be a buffer, got {typeof(Message)}`, 2) end if Length then if typeof(Length) ~= "number" then error(`Length must be a number, got {typeof(Length)}`, 2) end if Length ~= math.floor(Length) then error(`Length must be an integer, got {Length}`, 2) end if Length < BLAKE3_MIN_OUTPUT_BYTES then error(`Length must be at least {BLAKE3_MIN_OUTPUT_BYTES} byte, got {Length} bytes`, 2) end if Length > BLAKE3_MAX_OUTPUT_BYTES then error(`Length must be at most {BLAKE3_MAX_OUTPUT_BYTES} bytes, got {Length} bytes`, 2) end end local Result = ProcessMessage(INITIAL_VECTORS, 0, Message, Length or 32) return ToHex(Result), Result end function Blake3.DigestKeyed(Message: buffer, Key: buffer, Length: number?): (string, buffer) 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 ~= BLAKE3_KEY_SIZE then error(`Key must be exactly {BLAKE3_KEY_SIZE} bytes long, got {KeyLength} bytes`, 2) end if Message == nil then error("Message cannot be nil", 2) end if typeof(Message) ~= "buffer" then error(`Message must be a buffer, got {typeof(Message)}`, 2) end if Length then if typeof(Length) ~= "number" then error(`Length must be a number, got {typeof(Length)}`, 2) end if Length ~= math.floor(Length) then error(`Length must be an integer, got {Length}`, 2) end if Length < BLAKE3_MIN_OUTPUT_BYTES then error(`Length must be at least {BLAKE3_MIN_OUTPUT_BYTES} byte, got {Length} bytes`, 2) end if Length > BLAKE3_MAX_OUTPUT_BYTES then error(`Length must be at most {BLAKE3_MAX_OUTPUT_BYTES} bytes, got {Length} bytes`, 2) end end local Result = ProcessMessage(Key, HASH_FLAG, Message, Length or 32) return ToHex(Result), Result end function Blake3.DeriveKey(Context: buffer): (buffer, number?) -> (string, buffer) if Context == nil then error("Context cannot be nil", 2) end if typeof(Context) ~= "buffer" then error(`Context must be a buffer, got {typeof(Context)}`, 2) end local ContextHash = ProcessMessage(INITIAL_VECTORS, DERIVE_CONTEXT_FLAG, Context, 32) return function(Material: buffer, Length: number?): (string, buffer) if Material == nil then error("Material cannot be nil", 2) end if typeof(Material) ~= "buffer" then error(`Material must be a buffer, got {typeof(Material)}`, 2) end if Length then if typeof(Length) ~= "number" then error(`Length must be a number, got {typeof(Length)}`, 2) end if Length ~= math.floor(Length) then error(`Length must be an integer, got {Length}`, 2) end if Length < BLAKE3_MIN_OUTPUT_BYTES then error(`Length must be at least {BLAKE3_MIN_OUTPUT_BYTES} byte, got {Length} bytes`, 2) end if Length > BLAKE3_MAX_OUTPUT_BYTES then error(`Length must be at most {BLAKE3_MAX_OUTPUT_BYTES} bytes, got {Length} bytes`, 2) end end local Result = ProcessMessage(ContextHash, DERIVE_MATERIAL_FLAG, Material, Length or 32) return ToHex(Result), Result end end return Blake3
5,225
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/HKDF/HMAC.luau
--[=[ Cryptography library: HMAC Return type: string or function Example usage: local Message = buffer.fromstring("Hello World") local Key = buffer.fromstring("Key") local BlockSize = 64 -- SHA256 block length (= string.len(SHA256(...))) local Result = HMAC(Message, Key, SHA2.SHA256, BlockSize) -- SHA3/Blake family should have BigEndian = false --]=] --!strict --!optimize 2 --!native export type HashFunction = (...any) -> (string, buffer) local function FromByteAndSize(Byte: number, Size: number) local Buffer = buffer.create(Size) buffer.fill(Buffer, 0, Byte) return Buffer end local function ToBigEndian(Buffer: buffer) for Index = 0, buffer.len(Buffer) - 1, 4 do buffer.writeu32(Buffer, Index, bit32.byteswap(buffer.readu32(Buffer, Index))) end end local function ConcatenateBuffers(LeftBuffer: buffer, RightBuffer: buffer) local LeftBufLen = buffer.len(LeftBuffer) local Buffer = buffer.create(LeftBufLen + buffer.len(RightBuffer)) buffer.copy(Buffer, 0, LeftBuffer) buffer.copy(Buffer, LeftBufLen, RightBuffer) return Buffer end local function XORBuffer(LeftBuffer: buffer, RightBuffer: buffer) local Size = math.min(buffer.len(LeftBuffer), buffer.len(RightBuffer)) local NewBuffer = buffer.create(Size) for Index = 0, Size - 1 do local LeftValue = buffer.readu8(LeftBuffer, Index) local RightValue = buffer.readu8(RightBuffer, Index) buffer.writeu8(NewBuffer, Index, bit32.bxor(LeftValue, RightValue)) end return NewBuffer end local function ComputeBlockSizedKey(Key: buffer, HashFunction: HashFunction, BlockSizeBytes: number, BigEndian: boolean?): buffer local KeyLength = buffer.len(Key) if KeyLength > BlockSizeBytes then local _, Digest = HashFunction(Key) if BigEndian ~= false then ToBigEndian(Digest) end local PaddedKey = buffer.create(BlockSizeBytes) buffer.copy(PaddedKey, 0, Digest) return PaddedKey elseif KeyLength < BlockSizeBytes then local PaddedKey = buffer.create(BlockSizeBytes) buffer.copy(PaddedKey, 0, Key) return PaddedKey end return Key end local function HMAC(Message: buffer, Key: buffer, HashFunction: HashFunction, BlockSizeBytes: number, BigEndian: boolean?): (string, buffer) local BlockSizedKey = ComputeBlockSizedKey(Key, HashFunction, BlockSizeBytes, BigEndian) local OuterPaddedKey = XORBuffer(BlockSizedKey, FromByteAndSize(0x5C, BlockSizeBytes)) local InnerPaddedKey = XORBuffer(BlockSizedKey, FromByteAndSize(0x36, BlockSizeBytes)) local _, HashedMessageWithInnerKey = HashFunction(ConcatenateBuffers(InnerPaddedKey, Message)) if BigEndian ~= false then ToBigEndian(HashedMessageWithInnerKey) end local FinalMessage = ConcatenateBuffers(OuterPaddedKey, HashedMessageWithInnerKey) return HashFunction(FinalMessage) end return HMAC
726
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/HKDF/init.luau
--[=[ Cryptography library: HKDF (HMAC-based Key Derivation Function) RFC 5869 extract-then-expand key derivation built on HMAC. Return type: buffer Example usage: local IKM = buffer.fromstring("input key material") local OKM = HKDF(IKM, Salt, Info, 32, SHA2.SHA256, 64, 32) --]=] --!strict --!optimize 2 --!native local HMAC = require("@self/HMAC") type HashFunction = (...any) -> (string, buffer) local function ToBigEndian(Buffer: buffer) for Index = 0, buffer.len(Buffer) - 1, 4 do buffer.writeu32(Buffer, Index, bit32.byteswap(buffer.readu32(Buffer, Index))) end end local function HKDF(IKM: buffer, Salt: buffer?, Info: buffer?, Length: number, HashFunction: HashFunction, BlockSize: number, HashLength: number, BigEndian: boolean?): buffer local ActualSalt = if Salt and buffer.len(Salt) > 0 then Salt else buffer.create(HashLength) local ActualInfo = Info or buffer.create(0) local InfoLength = buffer.len(ActualInfo) local NeedsByteSwap = BigEndian ~= false local Iterations = math.ceil(Length / HashLength) if Iterations > 255 then error(`HKDF output length {Length} exceeds maximum {255 * HashLength}`) end local _, PRK = HMAC(IKM, ActualSalt, HashFunction, BlockSize, BigEndian) if NeedsByteSwap then ToBigEndian(PRK) end local MaxInputSize = HashLength + InfoLength + 1 local Input = buffer.create(MaxInputSize) local OKM = buffer.create(Length) local PreviousLength = 0 for Index = 1, Iterations do local InputSize = PreviousLength + InfoLength + 1 if InfoLength > 0 then buffer.copy(Input, PreviousLength, ActualInfo) end buffer.writeu8(Input, PreviousLength + InfoLength, Index) local InputSlice: buffer if InputSize == MaxInputSize then InputSlice = Input else InputSlice = buffer.create(InputSize) buffer.copy(InputSlice, 0, Input, 0, InputSize) end local _, Block = HMAC(InputSlice, PRK, HashFunction, BlockSize, BigEndian) if NeedsByteSwap then ToBigEndian(Block) end local Offset = (Index - 1) * HashLength buffer.copy(OKM, Offset, Block, 0, math.min(HashLength, Length - Offset)) buffer.copy(Input, 0, Block) PreviousLength = HashLength end return OKM end return HKDF
611
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/KMAC.luau
--[=[ Cryptography library: KMAC (Keccak Message Authentication Code) KMAC128 and KMAC256 are keyed hash functions based on cSHAKE128 and cSHAKE256. They give variable length output and strong authentication. Unlike SHAKE and cSHAKE, changing the output length generates a new, unrelated output. Both variants support up to 256 bits of security strength. Key Derivation Usage: For key derivation, use information related to the derived keying material as input data. Include identities and optionally a nonce. Return type: (string, buffer) Example usage: local Key = buffer.fromstring("my-secret-key") local Message = buffer.fromstring("Hello World") local Output = buffer.create(32) -- KMAC128 with 32-byte output local Hex, Digest = KMAC128(Message, Key, Output, buffer.create(0)) -- KMAC256 with custom string local Hex2, Digest2 = KMAC256(Message, Key, Output, buffer.fromstring("super-code")) --]=] --!strict --!optimize 2 --!native local KMAC = {} local ENCODE_LOOKUP = buffer.create(256 * 2) do local HexChars = "0123456789abcdef" for Byte = 0, 255 do local HighNibble = bit32.rshift(Byte, 4) local LowNibble = Byte % 16 local HighChar = string.byte(HexChars, HighNibble + 1) local LowChar = string.byte(HexChars, LowNibble + 1) local Combined = HighChar + bit32.lshift(LowChar, 8) buffer.writeu16(ENCODE_LOOKUP, Byte * 2, Combined) end end 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_NAME = buffer.fromstring("KMAC") 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 LEFT_ENCODE_RESULT = buffer.create(5) local RIGHT_ENCODE_RESULT = buffer.create(5) local function LeftEncode(Value: number): (buffer, number) local Result = LEFT_ENCODE_RESULT if Value <= 0xFF then buffer.writeu8(Result, 0, 1) buffer.writeu8(Result, 1, Value) return Result, 2 end if Value <= 0xFFFF then buffer.writeu8(Result, 0, 2) buffer.writeu16(Result, 1, bit32.byteswap(bit32.lshift(Value, 16))) return Result, 3 end local ByteLength = if Value > 0xFFFFFF then 4 else 3 buffer.writeu8(Result, 0, ByteLength) buffer.writeu32(Result, 1, bit32.byteswap(bit32.lshift(Value, (4 - ByteLength) * 8))) return Result, ByteLength + 1 end local function RightEncode(Value: number): (buffer, number) local Result = RIGHT_ENCODE_RESULT if Value <= 0xFF then buffer.writeu8(Result, 0, Value) buffer.writeu8(Result, 1, 1) return Result, 2 end if Value <= 0xFFFF then buffer.writeu16(Result, 0, bit32.byteswap(bit32.lshift(Value, 16))) buffer.writeu8(Result, 2, 2) return Result, 3 end local ByteLength = if Value > 0xFFFFFF then 4 else 3 buffer.writeu32(Result, 0, bit32.byteswap(bit32.lshift(Value, (4 - ByteLength) * 8))) buffer.writeu8(Result, ByteLength, ByteLength) return Result, ByteLength + 1 end local function EncodeString(Data: buffer): buffer local DataLength = buffer.len(Data) local LengthEncoding, LengthEncodingSize = LeftEncode(DataLength * 8) local Result = buffer.create(LengthEncodingSize + DataLength) buffer.copy(Result, 0, LengthEncoding, 0, LengthEncodingSize) buffer.copy(Result, LengthEncodingSize, Data, 0, DataLength) return Result end local function Bytepad(Data: buffer, Rate: number): buffer local DataLength = buffer.len(Data) local RateEncoding, RateEncodingSize = LeftEncode(Rate) local TotalPrePadLength = RateEncodingSize + DataLength local PadLength = Rate - (TotalPrePadLength % Rate) if PadLength == Rate then PadLength = 0 end local Result = buffer.create(TotalPrePadLength + PadLength) buffer.copy(Result, 0, RateEncoding, 0, RateEncodingSize) buffer.copy(Result, RateEncodingSize, Data, 0, DataLength) return Result end local function CSHAKE(Output: buffer, CustomBuffer: buffer?, Data: buffer, RateBytes: number): () buffer.fill(LANES_LOW, 0, 0, 100) buffer.fill(LANES_HIGH, 0, 0, 100) local LanesLow = LANES_LOW local LanesHigh = LANES_HIGH local OutputBytes = buffer.len(Output) local EncodedFunctionName = EncodeString(FUNCTION_NAME) local EncodedFunctionNameSize = buffer.len(EncodedFunctionName) local PrefixData: buffer if CustomBuffer then local EncodedCustomization = EncodeString(CustomBuffer) local EncodedCustomizationSize = buffer.len(EncodedCustomization) PrefixData = buffer.create(EncodedFunctionNameSize + EncodedCustomizationSize) buffer.copy(PrefixData, 0, EncodedFunctionName, 0, EncodedFunctionNameSize) buffer.copy(PrefixData, EncodedFunctionNameSize, EncodedCustomization, 0, EncodedCustomizationSize) else PrefixData = EncodedFunctionName end local BytepaddedPrefix = Bytepad(PrefixData, RateBytes) local BytepaddedPrefixSize = buffer.len(BytepaddedPrefix) local DataSize = buffer.len(Data) local TotalInputSize = BytepaddedPrefixSize + DataSize local PaddedLength = TotalInputSize + 1 local Remainder = PaddedLength % RateBytes if Remainder ~= 0 then PaddedLength += (RateBytes - Remainder) end local PaddedMessage = buffer.create(PaddedLength) buffer.copy(PaddedMessage, 0, BytepaddedPrefix, 0, BytepaddedPrefixSize) buffer.copy(PaddedMessage, BytepaddedPrefixSize, Data, 0, DataSize) local DomainSeparator = 0x04 if PaddedLength - TotalInputSize == 1 then buffer.writeu8(PaddedMessage, TotalInputSize, bit32.bor(DomainSeparator, 0x80)) else buffer.writeu8(PaddedMessage, TotalInputSize, DomainSeparator) if PaddedLength - TotalInputSize > 2 then buffer.fill(PaddedMessage, TotalInputSize + 1, 0, PaddedLength - TotalInputSize - 2) end buffer.writeu8(PaddedMessage, PaddedLength - 1, 0x80) end Keccak(LanesLow, LanesHigh, PaddedMessage, 0, PaddedLength, RateBytes) 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 end function KMAC.KMAC128(Data: buffer, Key: buffer, Output: buffer, CustomBuffer: buffer?): (string, buffer) local OutputBytes = buffer.len(Output) local EncodedKey = EncodeString(Key) local BytepaddedKey = Bytepad(EncodedKey, 168) local BytepaddedKeySize = buffer.len(BytepaddedKey) local DataSize = buffer.len(Data) local RightEncodedLength, RightEncodedLengthSize = RightEncode(OutputBytes * 8) local Hex = buffer.create(OutputBytes * 2) local Lookup = ENCODE_LOOKUP local Leftover = OutputBytes % 8 local HexCursor = 0 local CombinedData = buffer.create(BytepaddedKeySize + DataSize + RightEncodedLengthSize) buffer.copy(CombinedData, 0, BytepaddedKey, 0, BytepaddedKeySize) buffer.copy(CombinedData, BytepaddedKeySize, Data, 0, DataSize) buffer.copy(CombinedData, BytepaddedKeySize + DataSize, RightEncodedLength, 0, RightEncodedLengthSize) CSHAKE(Output, CustomBuffer, CombinedData, 168) for Index = 0, OutputBytes - Leftover - 1, 8 do local Hex1 = buffer.readu16(Lookup, buffer.readu8(Output, Index) * 2) local Hex2 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 1) * 2) local Hex3 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 2) * 2) local Hex4 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 3) * 2) local Hex5 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 4) * 2) local Hex6 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 5) * 2) local Hex7 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 6) * 2) local Hex8 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 7) * 2) buffer.writeu16(Hex, HexCursor, Hex1) buffer.writeu16(Hex, HexCursor + 2, Hex2) buffer.writeu16(Hex, HexCursor + 4, Hex3) buffer.writeu16(Hex, HexCursor + 6, Hex4) buffer.writeu16(Hex, HexCursor + 8, Hex5) buffer.writeu16(Hex, HexCursor + 10, Hex6) buffer.writeu16(Hex, HexCursor + 12, Hex7) buffer.writeu16(Hex, HexCursor + 14, Hex8) HexCursor += 16 end for Index = OutputBytes - Leftover, OutputBytes - 1 do local HexPair = buffer.readu16(Lookup, buffer.readu8(Output, Index) * 2) buffer.writeu16(Hex, HexCursor, HexPair) HexCursor += 2 end return buffer.tostring(Hex), Output end function KMAC.KMAC256(Data: buffer, Key: buffer, Output: buffer, CustomBuffer: buffer?): (string, buffer) local OutputBytes = buffer.len(Output) local EncodedKey = EncodeString(Key) local BytepaddedKey = Bytepad(EncodedKey, 136) local BytepaddedKeySize = buffer.len(BytepaddedKey) local DataSize = buffer.len(Data) local RightEncodedLength, RightEncodedLengthSize = RightEncode(OutputBytes * 8) local Hex = buffer.create(OutputBytes * 2) local Lookup = ENCODE_LOOKUP local Leftover = OutputBytes % 8 local HexCursor = 0 local CombinedData = buffer.create(BytepaddedKeySize + DataSize + RightEncodedLengthSize) buffer.copy(CombinedData, 0, BytepaddedKey, 0, BytepaddedKeySize) buffer.copy(CombinedData, BytepaddedKeySize, Data, 0, DataSize) buffer.copy(CombinedData, BytepaddedKeySize + DataSize, RightEncodedLength, 0, RightEncodedLengthSize) CSHAKE(Output, CustomBuffer, CombinedData, 136) for Index = 0, OutputBytes - Leftover - 1, 8 do local Hex1 = buffer.readu16(Lookup, buffer.readu8(Output, Index) * 2) local Hex2 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 1) * 2) local Hex3 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 2) * 2) local Hex4 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 3) * 2) local Hex5 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 4) * 2) local Hex6 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 5) * 2) local Hex7 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 6) * 2) local Hex8 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 7) * 2) buffer.writeu16(Hex, HexCursor, Hex1) buffer.writeu16(Hex, HexCursor + 2, Hex2) buffer.writeu16(Hex, HexCursor + 4, Hex3) buffer.writeu16(Hex, HexCursor + 6, Hex4) buffer.writeu16(Hex, HexCursor + 8, Hex5) buffer.writeu16(Hex, HexCursor + 10, Hex6) buffer.writeu16(Hex, HexCursor + 12, Hex7) buffer.writeu16(Hex, HexCursor + 14, Hex8) HexCursor += 16 end for Index = OutputBytes - Leftover, OutputBytes - 1 do local HexPair = buffer.readu16(Lookup, buffer.readu8(Output, Index) * 2) buffer.writeu16(Hex, HexCursor, HexPair) HexCursor += 2 end return buffer.tostring(Hex), Output end return KMAC
9,312
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/MD5.luau
--[=[ Cryptography library: MD5 ⚠️ WARNING: MD5 is cryptographically broken! Only use for legacy compatibility, checksums, or non-security purposes. For security, use SHA256 or higher. ⚠️ Return type: string Usage: local Message = buffer.fromstring("Hello World") local Result = MD5(Message) --]=] --!strict --!optimize 2 --!native local OFFSETS = table.create(64) :: {number} local CONSTANTS = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 } local SHIFTS = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 } local function PreProcess(Contents: buffer): (buffer, number) local ContentLength = buffer.len(Contents) local BitLength = ContentLength * 8 local Padding = (56 - ((ContentLength + 1) % 64)) % 64 local NewContentLength = ContentLength + 1 + Padding + 8 local NewContent = buffer.create(NewContentLength) buffer.copy(NewContent, 0, Contents) buffer.writeu8(NewContent, ContentLength, 0x80) local LengthOffset = ContentLength + 1 + Padding for Index = 0, 7 do local Byte = BitLength % 256 buffer.writeu8(NewContent, LengthOffset + Index, Byte) BitLength = bit32.rshift(BitLength, 8) end return NewContent, NewContentLength end local function DigestBlocks(Blocks: buffer, Length: number): (number, number, number, number) local A, B, C, D = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 local Offsets = OFFSETS local Constants = CONSTANTS local Shifts = SHIFTS for Offset = 0, Length - 1, 64 do for WordIndex = 0, 15 do local BlockOffset = Offset + WordIndex * 4 local Word = buffer.readu32(Blocks, BlockOffset) Offsets[WordIndex + 1] = Word end local OldA, OldB, OldC, OldD = A, B, C, D local Temp, Func = 0, 0 for Round = 0, 15 do local Chunk = Offsets[Round + 1] Func = bit32.bxor(OldD, bit32.band(OldB, bit32.bxor(OldC, OldD))) Temp = OldD OldD = OldC OldC = OldB OldB = OldB + bit32.lrotate(OldA + Func + Constants[Round + 1] + Chunk, Shifts[Round + 1]) OldA = Temp end for Round = 16, 31 do local Chunk = Offsets[(5 * Round + 1) % 16 + 1] Func = bit32.bxor(OldC, bit32.band(OldD, bit32.bxor(OldB, OldC))) Temp = OldD OldD = OldC OldC = OldB OldB = OldB + bit32.lrotate(OldA + Func + Constants[Round + 1] + Chunk, Shifts[Round + 1]) OldA = Temp end for Round = 32, 47 do local Chunk = Offsets[(3 * Round + 5) % 16 + 1] Func = bit32.bxor(OldB, OldC, OldD) Temp = OldD OldD = OldC OldC = OldB OldB = OldB + bit32.lrotate(OldA + Func + Constants[Round + 1] + Chunk, Shifts[Round + 1]) OldA = Temp end for Round = 48, 63 do local Chunk = Offsets[(7 * Round) % 16 + 1] Func = bit32.bxor(OldC, bit32.bor(OldB, bit32.bnot(OldD))) Temp = OldD OldD = OldC OldC = OldB OldB = OldB + bit32.lrotate(OldA + Func + Constants[Round + 1] + Chunk, Shifts[Round + 1]) OldA = Temp end A = bit32.bor(OldA + A, 0) B = bit32.bor(OldB + B, 0) C = bit32.bor(OldC + C, 0) D = bit32.bor(OldD + D, 0) end return bit32.byteswap(A), bit32.byteswap(B), bit32.byteswap(C), bit32.byteswap(D) end local function MD5(Message: buffer, Salt: buffer?): (string, buffer) if Salt and buffer.len(Salt) > 0 then local MessageWithSalt = buffer.create(buffer.len(Message) + buffer.len(Salt)) buffer.copy(MessageWithSalt, 0, Message) buffer.copy(MessageWithSalt, buffer.len(Message), Salt) Message = MessageWithSalt end local ProcessedMessage, Length = PreProcess(Message) local A, B, C, D = DigestBlocks(ProcessedMessage, Length) local Digest = buffer.create(16) buffer.writeu32(Digest, 0, A) buffer.writeu32(Digest, 4, B) buffer.writeu32(Digest, 8, C) buffer.writeu32(Digest, 12, D) return string.format("%08x%08x%08x%08x", A, B, C, D), Digest end return MD5
1,996
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/Murmur.luau
--[=[ Cryptography library: MurmurHash3-32 ⚠️ WARNING: MurmurHash3 wasn't designed with cryptographic security in mind! Only use for non-security purposes like hash tables or hyperloglog. For security, use SHA256 or higher. ⚠️ MurmurHash3 is a fast non-cryptographic hash that is well-distributed. Return type: number Example usage: local Message = buffer.fromstring("Hello World") --------Usage Case 1-------- local Result = MurmurHash3(Message) --------Usage Case 2-------- local Seed = 0xDEADBEEF local Result = MurmurHash3(Message, Seed) --]=] --!strict --!optimize 2 --!native local function Mul32(A: number, B: number): number local AHigh = bit32.rshift(A, 16) local ALow = bit32.band(A, 0xFFFF) local BHigh = bit32.rshift(B, 16) local BLow = bit32.band(B, 0xFFFF) local LoLo = ALow * BLow local HiLo = bit32.lshift(AHigh * BLow, 16) local LoHi = bit32.lshift(ALow * BHigh, 16) local Result = bit32.bor(LoLo + HiLo, 0) return bit32.bor(Result + LoHi, 0) end local function FMix32(Hash: number): number Hash = Mul32(bit32.bxor(Hash, bit32.rshift(Hash, 16)), 0x85ebca6b) Hash = Mul32(bit32.bxor(Hash, bit32.rshift(Hash, 13)), 0xc2b2ae35) Hash = bit32.bxor(Hash, bit32.rshift(Hash, 16)) return Hash end local function MurmurHash3(Message: buffer, Seed: number?): number local C1 = 0xcc9e2d51 local C2 = 0x1b873593 local Hash = bit32.bor(Seed or 0, 0) local MessageLength = buffer.len(Message) local BlockCount = MessageLength // 4 local UnrolledBlocks = BlockCount // 4 local CurrentOffset = 0 for _ = 1, UnrolledBlocks do local K1 = buffer.readu32(Message, CurrentOffset) K1 = Mul32(bit32.lrotate(Mul32(K1, 0xcc9e2d51), 15), 0x1b873593) Hash = bit32.bor(bit32.lrotate(bit32.bxor(Hash, K1), 13) * 5 + 0xe6546b64, 0) local K2 = buffer.readu32(Message, CurrentOffset + 4) K2 = Mul32(bit32.lrotate(Mul32(K2, 0xcc9e2d51), 15), 0x1b873593) Hash = bit32.bor(bit32.lrotate(bit32.bxor(Hash, K2), 13) * 5 + 0xe6546b64, 0) local K3 = buffer.readu32(Message, CurrentOffset + 8) K3 = Mul32(bit32.lrotate(Mul32(K3, 0xcc9e2d51), 15), 0x1b873593) Hash = bit32.bor(bit32.lrotate(bit32.bxor(Hash, K3), 13) * 5 + 0xe6546b64, 0) local K4 = buffer.readu32(Message, CurrentOffset + 12) K4 = Mul32(bit32.lrotate(Mul32(K4, 0xcc9e2d51), 15), 0x1b873593) Hash = bit32.bor(bit32.lrotate(bit32.bxor(Hash, K4), 13) * 5 + 0xe6546b64, 0) CurrentOffset += 16 end local RemainingBlocks = BlockCount % 4 for _ = 1, RemainingBlocks do local K = buffer.readu32(Message, CurrentOffset) K = Mul32(K, 0xcc9e2d51) K = bit32.lrotate(K, 15) K = Mul32(K, 0x1b873593) Hash = bit32.bxor(Hash, K) Hash = bit32.lrotate(Hash, 13) Hash = bit32.bor(Hash * 5 + 0xe6546b64, 0) CurrentOffset += 4 end local Remainder = MessageLength % 4 if Remainder > 0 then local K1 = 0 if Remainder >= 3 then K1 = bit32.bxor(K1, bit32.lshift(buffer.readu8(Message, CurrentOffset + 2), 16)) end if Remainder >= 2 then K1 = bit32.bxor(K1, bit32.lshift(buffer.readu8(Message, CurrentOffset + 1), 8)) end K1 = bit32.bxor(K1, buffer.readu8(Message, CurrentOffset)) K1 = Mul32(K1, C1) K1 = bit32.lrotate(K1, 15) K1 = Mul32(K1, C2) Hash = bit32.bxor(Hash, K1) end Hash = bit32.bxor(Hash, MessageLength) Hash = FMix32(Hash) return Hash end return MurmurHash3
1,248
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/SHA1.luau
--[=[ Cryptography library: SHA1 ⚠️ WARNING: SHA1 is cryptographically broken! Only use for legacy compatibility, checksums, or non-security purposes. For security, use SHA256 or higher. ⚠️ Sizes: Digest: 20 bytes Return type: string Example usage: local Message = buffer.fromstring("Hello World") --------Usage Case 1-------- local Result = SHA1(Message) --------Usage Case 2-------- local OptionalSalt = buffer.fromstring("Salty") local Result = SHA1(Message, OptionalSalt) --]=] --!strict --!optimize 2 --!native local OFFSETS = buffer.create(320) local function PreProcess(Contents: buffer): (buffer, number) local ContentLength = buffer.len(Contents) local Padding = (64 - ((ContentLength + 9) % 64)) % 64 local NewContentLength = ContentLength + 1 + Padding + 8 local NewContent = buffer.create(NewContentLength) buffer.copy(NewContent, 0, Contents) buffer.writeu8(NewContent, ContentLength, 128) local Length8 = ContentLength * 8 for Index = 7, 0, -1 do local Remainder = Length8 % 256 buffer.writeu8(NewContent, Index + ContentLength + 1 + Padding, Remainder) Length8 = (Length8 - Remainder) / 256 end return NewContent, NewContentLength end local function DigestBlocks(Blocks: buffer, Length: number): (number, number, number, number, number) local A, B, C, D, E = 0x67452301, 0xefcdaB89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 local Offsets = OFFSETS for Offset = 0, Length - 1, 64 do for BlockIndex = 0, 60, 4 do buffer.writeu32(Offsets, BlockIndex, bit32.byteswap(buffer.readu32(Blocks, Offset + BlockIndex))) end for Index = 64, 316, 4 do buffer.writeu32(Offsets, Index, bit32.lrotate(bit32.bxor( buffer.readu32(Offsets, Index - 12), buffer.readu32(Offsets, Index - 32), buffer.readu32(Offsets, Index - 56), buffer.readu32(Offsets, Index - 64) ), 1)) end local H1, H2, H3, H4, H5 = A, B, C, D, E local Temp for Round = 0, 19 do Temp = bit32.lrotate(H1, 5) + bit32.band(H2, H3) + bit32.band(-1 - H2, H4) + H5 + 0x5a827999 + buffer.readu32(Offsets, Round * 4) H5, H4, H3, H2, H1 = H4, H3, bit32.lrotate(H2, 30), H1, Temp end for Round = 20, 39 do Temp = bit32.lrotate(H1, 5) + bit32.bxor(H2, H3, H4) + H5 + 0x6ed9eba1 + buffer.readu32(Offsets, Round * 4) H5, H4, H3, H2, H1 = H4, H3, bit32.lrotate(H2, 30), H1, Temp end for Round = 40, 59 do Temp = bit32.lrotate(H1, 5) + bit32.band(H4, H3) + bit32.band(H2, bit32.bxor(H4, H3)) + H5 + 0x8f1bbcdc + buffer.readu32(Offsets, Round * 4) H5, H4, H3, H2, H1 = H4, H3, bit32.lrotate(H2, 30), H1, Temp end for Round = 60, 79 do Temp = bit32.lrotate(H1, 5) + bit32.bxor(H2, H3, H4) + H5 + 0xca62c1d6 + buffer.readu32(Offsets, Round * 4) H5, H4, H3, H2, H1 = H4, H3, bit32.lrotate(H2, 30), H1, Temp end A = bit32.bor(A + H1, 0) B = bit32.bor(B + H2, 0) C = bit32.bor(C + H3, 0) D = bit32.bor(D + H4, 0) E = bit32.bor(E + H5, 0) end return A, B, C, D, E end local function SHA1(Message: buffer, Salt: buffer?): string if Salt and buffer.len(Salt) > 0 then local MessageWithSalt = buffer.create(buffer.len(Message) + buffer.len(Salt)) buffer.copy(MessageWithSalt, 0, Message) buffer.copy(MessageWithSalt, buffer.len(Message), Salt) Message = MessageWithSalt end local ProcessedMessage, Length = PreProcess(Message) return string.format("%08x%08x%08x%08x%08x", DigestBlocks(ProcessedMessage, Length)) end return SHA1
1,268
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/SHA2/SHA224.luau
--[=[ Cryptography library: SHA224 Sizes: Digest: 28 bytes Return type: string Example usage: local Message = buffer.fromstring("Hello World") local Result = SHA224(Message) --]=] --!strict --!optimize 2 --!native local CONSTANTS = buffer.create(256) do -- CONSTANTS = k local RoundConstants = { 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 } for Index, Constant in ipairs(RoundConstants) do local BufferOffset = (Index - 1) * 4 buffer.writeu32(CONSTANTS, BufferOffset, Constant) end end local function PreProcess(Contents: buffer): (buffer, number) local ContentLength = buffer.len(Contents) local Padding = -(ContentLength + 9) % 64 local NewContentLength = ContentLength + 1 + Padding + 8 local NewContent = buffer.create(NewContentLength) buffer.copy(NewContent, 0, Contents) buffer.writeu8(NewContent, ContentLength, 128) local Length8 = ContentLength * 8 for Index = 7, 0, -1 do local Remainder = Length8 % 256 buffer.writeu8(NewContent, Index + ContentLength + 1 + Padding, Remainder) Length8 = (Length8 - Remainder) / 256 end return NewContent, NewContentLength end local OFFSETS = buffer.create(256) local function DigestBlocks(Blocks: buffer, Length: number): (number, number, number, number, number, number, number) local A, B, C, D = 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939 local E, F, G, H = 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 local Offsets = OFFSETS local Constants = CONSTANTS for Offset = 0, Length - 1, 64 do for BlockIndex = 0, 60, 4 do buffer.writeu32(Offsets, BlockIndex, bit32.byteswap(buffer.readu32(Blocks, Offset + BlockIndex))) end for Index = 64, 252, 4 do local Sub15 = buffer.readu32(Offsets, Index - 60) local S0 = bit32.bxor(bit32.rrotate(Sub15, 7), bit32.rrotate(Sub15, 18), bit32.rshift(Sub15, 3)) local Sub2 = buffer.readu32(Offsets, Index - 8) local S1 = bit32.bxor(bit32.rrotate(Sub2, 17), bit32.rrotate(Sub2, 19), bit32.rshift(Sub2, 10)) local Sub7, Sub16 = buffer.readu32(Offsets, Index - 28), buffer.readu32(Offsets, Index - 64) buffer.writeu32(Offsets, Index, (Sub16 + S0 + Sub7 + S1)) end local OldA, OldB, OldC, OldD, OldE, OldF, OldG, OldH = A, B, C, D, E, F, G, H for BufferIndex = 0, 252, 4 do local S1 = bit32.bxor(bit32.rrotate(E, 6), bit32.rrotate(E, 11), bit32.rrotate(E, 25)) local Ch = bit32.bxor(bit32.band(E, F), bit32.band(bit32.bnot(E), G)) local Temp1 = H + S1 + Ch + buffer.readu32(Constants, BufferIndex) + buffer.readu32(Offsets, BufferIndex) H, G, F, E, D = G, F, E, D + Temp1, C local S0 = bit32.bxor(bit32.rrotate(A, 2), bit32.rrotate(A, 13), bit32.rrotate(A, 22)) local Maj = bit32.bxor(bit32.band(A, B), bit32.band(A, C), bit32.band(B, C)) C, B, A = B, A, Temp1 + S0 + Maj end A, B, C, D, E, F, G, H = bit32.bor(A + OldA, 0), bit32.bor(B + OldB, 0), bit32.bor(C + OldC, 0), bit32.bor(D + OldD, 0), bit32.bor(E + OldE, 0), bit32.bor(F + OldF, 0), bit32.bor(G + OldG, 0), bit32.bor(H + OldH, 0) end return A, B, C, D, E, F, G end local function SHA224(Message: buffer): (string, buffer) local ProcessedMessage, Length = PreProcess(Message) local A, B, C, D, E, F, G = DigestBlocks(ProcessedMessage, Length) local Digest = buffer.create(28) buffer.writeu32(Digest, 0, A) buffer.writeu32(Digest, 4, B) buffer.writeu32(Digest, 8, C) buffer.writeu32(Digest, 12, D) buffer.writeu32(Digest, 16, E) buffer.writeu32(Digest, 20, F) buffer.writeu32(Digest, 24, G) return string.format("%08x%08x%08x%08x%08x%08x%08x", A, B, C, D, E, F, G), Digest end return SHA224
1,815
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/SHA2/SHA256.luau
--[=[ Cryptography library: SHA256 Sizes: Digest: 32 bytes Return type: string Example usage: local Message = buffer.fromstring("Hello World") local Result = SHA256(Message) --]=] --!strict --!optimize 2 --!native local CONSTANTS = buffer.create(256) do -- CONSTANTS = k local RoundConstants = { 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 } for Index, Constant in ipairs(RoundConstants) do local BufferOffset = (Index - 1) * 4 buffer.writeu32(CONSTANTS, BufferOffset, Constant) end end local function PreProcess(Contents: buffer): (buffer, number) local ContentLength = buffer.len(Contents) local Padding = -(ContentLength + 9) % 64 local NewContentLength = ContentLength + 1 + Padding + 8 local NewContent = buffer.create(NewContentLength) buffer.copy(NewContent, 0, Contents) buffer.writeu8(NewContent, ContentLength, 128) local Length8 = ContentLength * 8 for Index = 7, 0, -1 do local Remainder = Length8 % 256 buffer.writeu8(NewContent, Index + ContentLength + 1 + Padding, Remainder) Length8 = (Length8 - Remainder) / 256 end return NewContent, NewContentLength end local OFFSETS = buffer.create(256) local function DigestBlocks(Blocks: buffer, Length: number): (number, number, number, number, number, number, number, number) local A, B, C, D = 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a local E, F, G, H = 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 local Offsets = OFFSETS local Constants = CONSTANTS for Offset = 0, Length - 1, 64 do for BlockIndex = 0, 60, 4 do buffer.writeu32(Offsets, BlockIndex, bit32.byteswap(buffer.readu32(Blocks, Offset + BlockIndex))) end for Index = 64, 252, 4 do local Sub15 = buffer.readu32(Offsets, Index - 60) local S0 = bit32.bxor(bit32.rrotate(Sub15, 7), bit32.rrotate(Sub15, 18), bit32.rshift(Sub15, 3)) local Sub2 = buffer.readu32(Offsets, Index - 8) local S1 = bit32.bxor(bit32.rrotate(Sub2, 17), bit32.rrotate(Sub2, 19), bit32.rshift(Sub2, 10)) local Sub7, Sub16 = buffer.readu32(Offsets, Index - 28), buffer.readu32(Offsets, Index - 64) buffer.writeu32(Offsets, Index, (Sub16 + S0 + Sub7 + S1)) end local OldA, OldB, OldC, OldD, OldE, OldF, OldG, OldH = A, B, C, D, E, F, G, H for BufferIndex = 0, 252, 4 do local S1 = bit32.bxor(bit32.rrotate(E, 6), bit32.rrotate(E, 11), bit32.rrotate(E, 25)) local Ch = bit32.bxor(bit32.band(E, F), bit32.band(bit32.bnot(E), G)) local Temp1 = H + S1 + Ch + buffer.readu32(Constants, BufferIndex) + buffer.readu32(Offsets, BufferIndex) H, G, F, E, D = G, F, E, D + Temp1, C local S0 = bit32.bxor(bit32.rrotate(A, 2), bit32.rrotate(A, 13), bit32.rrotate(A, 22)) local Maj = bit32.bxor(bit32.band(A, B), bit32.band(A, C), bit32.band(B, C)) C, B, A = B, A, Temp1 + S0 + Maj end A, B, C, D, E, F, G, H = bit32.bor(A + OldA, 0), bit32.bor(B + OldB, 0), bit32.bor(C + OldC, 0), bit32.bor(D + OldD, 0), bit32.bor(E + OldE, 0), bit32.bor(F + OldF, 0), bit32.bor(G + OldG, 0), bit32.bor(H + OldH, 0) :: number end return A, B, C, D, E, F, G, H end local function SHA256(Message: buffer): (string, buffer) local ProcessedMessage, Length = PreProcess(Message) local A, B, C, D, E, F, G, H = DigestBlocks(ProcessedMessage, Length) local Digest = buffer.create(32) buffer.writeu32(Digest, 0, A) buffer.writeu32(Digest, 4, B) buffer.writeu32(Digest, 8, C) buffer.writeu32(Digest, 12, D) buffer.writeu32(Digest, 16, E) buffer.writeu32(Digest, 20, F) buffer.writeu32(Digest, 24, G) buffer.writeu32(Digest, 28, H) return string.format("%08x%08x%08x%08x%08x%08x%08x%08x", A, B, C, D, E, F, G, H), Digest end return SHA256
1,847
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/SHA2/SHA384.luau
--[=[ Cryptography library: SHA384 Sizes: Digest: 48 bytes Return type: (string, buffer) Example usage: local Message = buffer.fromstring("Hello World") local Hash, HashBuffer = SHA384(Message) --]=] --!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 DIGEST = buffer.create(48) 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 DigestBlocks(Blocks: buffer, Length: number) local Hi, Lo = W_HI, W_LO local KHi, KLo = K_HI, K_LO local H1Hi, H2Hi, H3Hi, H4Hi = 0xcbbb9d5d, 0x629a292a, 0x9159015a, 0x152fecd8 local H5Hi, H6Hi, H7Hi, H8Hi = 0x67332667, 0x8eb44a87, 0xdb0c2e0d, 0x47b5481d local H1Lo, H2Lo, H3Lo, H4Lo = 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939 local H5Lo, H6Lo, H7Lo, H8Lo = 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 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(DIGEST, 0, H1Hi) buffer.writeu32(DIGEST, 4, H1Lo) buffer.writeu32(DIGEST, 8, H2Hi) buffer.writeu32(DIGEST, 12, H2Lo) buffer.writeu32(DIGEST, 16, H3Hi) buffer.writeu32(DIGEST, 20, H3Lo) buffer.writeu32(DIGEST, 24, H4Hi) buffer.writeu32(DIGEST, 28, H4Lo) buffer.writeu32(DIGEST, 32, H5Hi) buffer.writeu32(DIGEST, 36, H5Lo) buffer.writeu32(DIGEST, 40, H6Hi) buffer.writeu32(DIGEST, 44, H6Lo) end local function SHA384(Message: buffer): (string, buffer) local Processed, Length = PreProcess(Message) DigestBlocks(Processed, Length) local H1Hi, H1Lo = buffer.readu32(DIGEST, 0), buffer.readu32(DIGEST, 4) local H2Hi, H2Lo = buffer.readu32(DIGEST, 8), buffer.readu32(DIGEST, 12) local H3Hi, H3Lo = buffer.readu32(DIGEST, 16), buffer.readu32(DIGEST, 20) local H4Hi, H4Lo = buffer.readu32(DIGEST, 24), buffer.readu32(DIGEST, 28) local H5Hi, H5Lo = buffer.readu32(DIGEST, 32), buffer.readu32(DIGEST, 36) local H6Hi, H6Lo = buffer.readu32(DIGEST, 40), buffer.readu32(DIGEST, 44) local Result = buffer.create(48) buffer.copy(Result, 0, DIGEST) return string.format( "%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x", H1Hi, H1Lo, H2Hi, H2Lo, H3Hi, H3Lo, H4Hi, H4Lo, H5Hi, H5Lo, H6Hi, H6Lo ), Result end return SHA384
4,903
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/SHA2/SHA512.luau
--[=[ Cryptography library: SHA512 Sizes: Digest: 64 bytes Return type: (string, buffer) Example usage: local Message = buffer.fromstring("Hello World") local Hash, HashBuffer = SHA512(Message) --]=] --!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 DIGEST = 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 DigestBlocks(Blocks: buffer, Length: number) 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(DIGEST, 0, H1Hi) buffer.writeu32(DIGEST, 4, H1Lo) buffer.writeu32(DIGEST, 8, H2Hi) buffer.writeu32(DIGEST, 12, H2Lo) buffer.writeu32(DIGEST, 16, H3Hi) buffer.writeu32(DIGEST, 20, H3Lo) buffer.writeu32(DIGEST, 24, H4Hi) buffer.writeu32(DIGEST, 28, H4Lo) buffer.writeu32(DIGEST, 32, H5Hi) buffer.writeu32(DIGEST, 36, H5Lo) buffer.writeu32(DIGEST, 40, H6Hi) buffer.writeu32(DIGEST, 44, H6Lo) buffer.writeu32(DIGEST, 48, H7Hi) buffer.writeu32(DIGEST, 52, H7Lo) buffer.writeu32(DIGEST, 56, H8Hi) buffer.writeu32(DIGEST, 60, H8Lo) end local function SHA512(Message: buffer): (string, buffer) local Processed, Length = PreProcess(Message) DigestBlocks(Processed, Length) local H1Hi, H1Lo = buffer.readu32(DIGEST, 0), buffer.readu32(DIGEST, 4) local H2Hi, H2Lo = buffer.readu32(DIGEST, 8), buffer.readu32(DIGEST, 12) local H3Hi, H3Lo = buffer.readu32(DIGEST, 16), buffer.readu32(DIGEST, 20) local H4Hi, H4Lo = buffer.readu32(DIGEST, 24), buffer.readu32(DIGEST, 28) local H5Hi, H5Lo = buffer.readu32(DIGEST, 32), buffer.readu32(DIGEST, 36) local H6Hi, H6Lo = buffer.readu32(DIGEST, 40), buffer.readu32(DIGEST, 44) local H7Hi, H7Lo = buffer.readu32(DIGEST, 48), buffer.readu32(DIGEST, 52) local H8Hi, H8Lo = buffer.readu32(DIGEST, 56), buffer.readu32(DIGEST, 60) local Result = buffer.create(64) buffer.copy(Result, 0, DIGEST) return string.format( "%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x", H1Hi, H1Lo, H2Hi, H2Lo, H3Hi, H3Lo, H4Hi, H4Lo, H5Hi, H5Lo, H6Hi, H6Lo, H7Hi, H7Lo, H8Hi, H8Lo ), Result end return SHA512
5,062
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/SHA2/init.luau
--[[ Cryptography library: SHA2 Family --]] return { SHA224 = require("@self/SHA224"), SHA256 = require("@self/SHA256"), SHA384 = require("@self/SHA384"), SHA512 = require("@self/SHA512"), }
59
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/SHA3.luau
--[=[ Cryptography library: Keccak/SHA-3 Sizes: SHA3-224 Digest: 28 bytes SHA3-256 Digest: 32 bytes SHA3-384 Digest: 48 bytes SHA3-512 Digest: 64 bytes SHAKE128 Digest: variable SHAKE256 Digest: variable Return type: string Example usage: local Message = buffer.fromstring("Hello World") local Result1 = SHA3_256(Message) local Result2 = SHAKE128(Message, 32) --]=] --!strict --!optimize 2 --!native local SHA3 = {} local ENCODE_LOOKUP = buffer.create(256 * 2) do local HexChars = "0123456789abcdef" for Byte = 0, 255 do local HighNibble = bit32.rshift(Byte, 4) local LowNibble = Byte % 16 local HighChar = string.byte(HexChars, HighNibble + 1) local LowChar = string.byte(HexChars, LowNibble + 1) local Combined = HighChar + bit32.lshift(LowChar, 8) buffer.writeu16(ENCODE_LOOKUP, Byte * 2, Combined) end end 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): (string, 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 Length = buffer.len(Output) local Hex = buffer.create(Length * 2) local Lookup = ENCODE_LOOKUP local Leftover = Length % 8 local HexCursor = 0 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 for Index = 0, Length - Leftover - 1, 8 do local Hex1 = buffer.readu16(Lookup, buffer.readu8(Output, Index) * 2) local Hex2 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 1) * 2) local Hex3 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 2) * 2) local Hex4 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 3) * 2) local Hex5 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 4) * 2) local Hex6 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 5) * 2) local Hex7 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 6) * 2) local Hex8 = buffer.readu16(Lookup, buffer.readu8(Output, Index + 7) * 2) buffer.writeu16(Hex, HexCursor, Hex1) buffer.writeu16(Hex, HexCursor + 2, Hex2) buffer.writeu16(Hex, HexCursor + 4, Hex3) buffer.writeu16(Hex, HexCursor + 6, Hex4) buffer.writeu16(Hex, HexCursor + 8, Hex5) buffer.writeu16(Hex, HexCursor + 10, Hex6) buffer.writeu16(Hex, HexCursor + 12, Hex7) buffer.writeu16(Hex, HexCursor + 14, Hex8) HexCursor += 16 end for Index = Length - Leftover, Length - 1 do local HexPair = buffer.readu16(Lookup, buffer.readu8(Output, Index) * 2) buffer.writeu16(Hex, HexCursor, HexPair) HexCursor += 2 end return buffer.tostring(Hex), Output end function SHA3.SHA3_224(Message: buffer): (string, buffer) return ProcessSponge(Message, 448, 28, 0x06) end function SHA3.SHA3_256(Message: buffer): (string, buffer) return ProcessSponge(Message, 512, 32, 0x06) end function SHA3.SHA3_384(Message: buffer): (string, buffer) return ProcessSponge(Message, 768, 48, 0x06) end function SHA3.SHA3_512(Message: buffer): (string, buffer) return ProcessSponge(Message, 1024, 64, 0x06) end function SHA3.SHAKE128(Message: buffer, OutputBytes: number): (string, buffer) return ProcessSponge(Message, 256, OutputBytes, 0x1F) end function SHA3.SHAKE256(Message: buffer, OutputBytes: number): (string, buffer) return ProcessSponge(Message, 512, OutputBytes, 0x1F) end return SHA3
7,716
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/XXH32.luau
--[=[ Cryptography library: XXHash32 ⚠️ WARNING: XXHash32 wasn't designed with cryptographic security in mind! Only use for non-security purposes. For security, use SHA256 or higher. ⚠️ Return type: number Example usage: local Message = buffer.fromstring("Hello World") --------Usage Case 1-------- local Result = XXHash32(Message) --------Usage Case 2-------- local Seed = 0xDEADBEEF local Result = XXHash32(Message, Seed) --]=] --!strict --!optimize 2 --!native local function XXH32(Message: buffer, Seed: number?): number local PRIME_1, PRIME_1_HIGH, PRIME_1_LOW = 0x9e3779B1, 40503, 31153 local PRIME_2, PRIME_2_HIGH, PRIME_2_LOW = 0x85ebca77, 34283, 51831 local PRIME_3_HIGH, PRIME_3_LOW = 49842, 44605 local PRIME_4_HIGH, PRIME_4_LOW = 10196, 60207 local PRIME_5, PRIME_5_HIGH, PRIME_5_LOW = 0x165667b1, 5718, 26545 local UsedSeed = Seed or 0 local MessageLength = buffer.len(Message) local Digest: number local CurrentOffset = 0 if MessageLength >= 16 then local Accumulator1 = UsedSeed + PRIME_1 + PRIME_2 local Accumulator2 = UsedSeed + PRIME_2 local Accumulator3 = UsedSeed local Accumulator4 = UsedSeed - PRIME_1 while CurrentOffset <= MessageLength - 16 do local Word1 = buffer.readu32(Message, CurrentOffset) local Word2 = buffer.readu32(Message, CurrentOffset + 4) local Word3 = buffer.readu32(Message, CurrentOffset + 8) local Word4 = buffer.readu32(Message, CurrentOffset + 12) local AHigh1, ALow1 = bit32.rshift(Word1, 16), bit32.band(Word1, 65535) local Mult1 = bit32.lshift((AHigh1 * PRIME_2_LOW) + (ALow1 * PRIME_2_HIGH), 16) + (ALow1 * PRIME_2_LOW) local Temp1 = bit32.lrotate(Accumulator1 + Mult1, 13) local AHigh1_2, ALow1_2 = bit32.rshift(Temp1, 16), bit32.band(Temp1, 65535) Accumulator1 = bit32.lshift((AHigh1_2 * PRIME_1_LOW) + (ALow1_2 * PRIME_1_HIGH), 16) + (ALow1_2 * PRIME_1_LOW) local AHigh2, ALow2 = bit32.rshift(Word2, 16), bit32.band(Word2, 65535) local Mult2 = bit32.lshift((AHigh2 * PRIME_2_LOW) + (ALow2 * PRIME_2_HIGH), 16) + (ALow2 * PRIME_2_LOW) local Temp2 = bit32.lrotate(Accumulator2 + Mult2, 13) local AHigh2_2, ALow2_2 = bit32.rshift(Temp2, 16), bit32.band(Temp2, 65535) Accumulator2 = bit32.lshift((AHigh2_2 * PRIME_1_LOW) + (ALow2_2 * PRIME_1_HIGH), 16) + (ALow2_2 * PRIME_1_LOW) local AHigh3, ALow3 = bit32.rshift(Word3, 16), bit32.band(Word3, 65535) local Mult3 = bit32.lshift((AHigh3 * PRIME_2_LOW) + (ALow3 * PRIME_2_HIGH), 16) + (ALow3 * PRIME_2_LOW) local Temp3 = bit32.lrotate(Accumulator3 + Mult3, 13) local AHigh3_2, ALow3_2 = bit32.rshift(Temp3, 16), bit32.band(Temp3, 65535) Accumulator3 = bit32.lshift((AHigh3_2 * PRIME_1_LOW) + (ALow3_2 * PRIME_1_HIGH), 16) + (ALow3_2 * PRIME_1_LOW) local AHigh4, ALow4 = bit32.rshift(Word4, 16), bit32.band(Word4, 65535) local Mult4 = bit32.lshift((AHigh4 * PRIME_2_LOW) + (ALow4 * PRIME_2_HIGH), 16) + (ALow4 * PRIME_2_LOW) local Temp4 = bit32.lrotate(Accumulator4 + Mult4, 13) local AHigh4_2, ALow4_2 = bit32.rshift(Temp4, 16), bit32.band(Temp4, 65535) Accumulator4 = bit32.lshift((AHigh4_2 * PRIME_1_LOW) + (ALow4_2 * PRIME_1_HIGH), 16) + (ALow4_2 * PRIME_1_LOW) CurrentOffset += 16 end Digest = bit32.lrotate(Accumulator1, 1) + bit32.lrotate(Accumulator2, 7) + bit32.lrotate(Accumulator3, 12) + bit32.lrotate(Accumulator4, 18) else Digest = UsedSeed + PRIME_5 end Digest += MessageLength while CurrentOffset <= MessageLength - 4 do if CurrentOffset + 4 <= buffer.len(Message) then local Word = buffer.readu32(Message, CurrentOffset) local AHigh_w, ALow_w = bit32.rshift(Word, 16), bit32.band(Word, 65535) local Mult_w = bit32.lshift((AHigh_w * PRIME_3_LOW) + (ALow_w * PRIME_3_HIGH), 16) + (ALow_w * PRIME_3_LOW) Digest += Mult_w local Rotated = bit32.lrotate(Digest, 17) local AHigh_r, ALow_r = bit32.rshift(Rotated, 16), bit32.band(Rotated, 65535) Digest = bit32.lshift((AHigh_r * PRIME_4_LOW) + (ALow_r * PRIME_4_HIGH), 16) + (ALow_r * PRIME_4_LOW) end CurrentOffset += 4 end while CurrentOffset < MessageLength do if CurrentOffset < buffer.len(Message) then local ByteValue = buffer.readu8(Message, CurrentOffset) local AHigh_b, ALow_b = bit32.rshift(ByteValue, 16), bit32.band(ByteValue, 65535) local Mult_b = bit32.lshift((AHigh_b * PRIME_5_LOW) + (ALow_b * PRIME_5_HIGH), 16) + (ALow_b * PRIME_5_LOW) Digest += Mult_b local Rotated_b = bit32.lrotate(Digest, 11) local AHigh_rb, ALow_rb = bit32.rshift(Rotated_b, 16), bit32.band(Rotated_b, 65535) Digest = bit32.lshift((AHigh_rb * PRIME_1_LOW) + (ALow_rb * PRIME_1_HIGH), 16) + (ALow_rb * PRIME_1_LOW) end CurrentOffset += 1 end local XorResult1 = bit32.bxor(Digest, bit32.rshift(Digest, 15)) local AHigh_f1, ALow_f1 = bit32.rshift(XorResult1, 16), bit32.band(XorResult1, 65535) Digest = bit32.lshift((AHigh_f1 * PRIME_2_LOW) + (ALow_f1 * PRIME_2_HIGH), 16) + (ALow_f1 * PRIME_2_LOW) local XorResult2 = bit32.bxor(Digest, bit32.rshift(Digest, 13)) local AHigh_f2, ALow_f2 = bit32.rshift(XorResult2, 16), bit32.band(XorResult2, 65535) Digest = bit32.lshift((AHigh_f2 * PRIME_3_LOW) + (ALow_f2 * PRIME_3_HIGH), 16) + (ALow_f2 * PRIME_3_LOW) return bit32.bxor(Digest, bit32.rshift(Digest, 16)) end return XXH32
2,006
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Hashing/init.luau
--!strict local Algorithms = table.freeze({ HMAC = require("@self/HMAC"), HKDF = require("@self/HKDF"), KMAC = require("@self/KMAC"), MD5 = require("@self/MD5"), SHA1 = require("@self/SHA1"), SHA2 = require("@self/SHA2"), SHA3 = require("@self/SHA3"), XXH32 = require("@self/XXH32"), Blake2b = require("@self/Blake2b"), Blake3 = require("@self/Blake3"), MurMur = require("@self/Murmur") }) return Algorithms
133
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Utilities/Base64.luau
--[=[ Cryptography library: Base64 Return type: buffer Example usage: local Input = buffer.fromstring("Hello World") local Encoded = Base64.Encode(Input) local Decoded = Base64.Decode(Encoded) --]=] --!strict --!optimize 2 --!native local PADDING_CHARACTER = 61 local ALPHABET_BYTES = buffer.create(64) do local Characters = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47 } for Index = 1, 64 do buffer.writeu8(ALPHABET_BYTES, Index - 1, Characters[Index]) end end local ENCODE_A, ENCODE_B = buffer.create(131072), buffer.create(131072) do for Byte0 = 0, 255 do local Sextet0 = Byte0 // 4 local Sextet0Char = buffer.readu8(ALPHABET_BYTES, Sextet0) local Byte0Low = Byte0 % 4 for Byte1 = 0, 255 do local Sextet1 = Byte0Low * 16 + (Byte1 // 16) local Index = (Byte0 + Byte1 * 256) * 2 buffer.writeu16(ENCODE_A, Index, Sextet0Char + buffer.readu8(ALPHABET_BYTES, Sextet1) * 256) end end for Byte1 = 0, 255 do local Nibble = (Byte1 % 16) * 4 for Byte2 = 0, 255 do local Sextet2 = Nibble + (Byte2 // 64) local Sextet3 = Byte2 % 64 local Index = (Byte1 + Byte2 * 256) * 2 buffer.writeu16(ENCODE_B, Index, buffer.readu8(ALPHABET_BYTES, Sextet2) + buffer.readu8(ALPHABET_BYTES, Sextet3) * 256) end end end local DECODE_TET = buffer.create(256) do for Index = 1, 64 do buffer.writeu8(DECODE_TET, buffer.readu8(ALPHABET_BYTES, Index - 1), Index - 1) end buffer.writeu8(DECODE_TET, PADDING_CHARACTER, 254) end local DECODE_PAIR = buffer.create(131072) do for Char0 = 0, 255 do local Decoded0 = buffer.readu8(DECODE_TET, Char0) for Char1 = 0, 255 do local Decoded1 = buffer.readu8(DECODE_TET, Char1) local Key = (Char0 + Char1 * 256) * 2 if Decoded0 < 64 and Decoded1 < 64 then buffer.writeu16(DECODE_PAIR, Key, Decoded0 * 64 + Decoded1) elseif Decoded0 == 254 or Decoded1 == 254 then buffer.writeu16(DECODE_PAIR, Key, 254) end end end end local PAIR_A_BYTE1_HIGH = buffer.create(4096) local PAIR_B_BYTE1_LOW = buffer.create(4096) local PAIR_A_BYTE0, PAIR_B_BYTE2 = buffer.create(4096), buffer.create(4096) do for PairA = 0, 4095 do local Sextet0 = PairA // 64 local Sextet1 = PairA % 64 buffer.writeu8(PAIR_A_BYTE0, PairA, Sextet0 * 4 + (Sextet1 // 16)) buffer.writeu8(PAIR_A_BYTE1_HIGH, PairA, (Sextet1 % 16) * 16) end for PairB = 0, 4095 do local Sextet2 = PairB // 64 local Sextet3 = PairB % 64 buffer.writeu8(PAIR_B_BYTE1_LOW, PairB, Sextet2 // 4) buffer.writeu8(PAIR_B_BYTE2, PairB, (Sextet2 % 4) * 64 + Sextet3) end end local function Encode(Input: buffer): buffer local InputLength = buffer.len(Input) if InputLength == 0 then return buffer.create(0) end local Output = buffer.create(((InputLength + 2) // 3) * 4) local InputIndex = 0 local OutputIndex = 0 local FullTripletEnd = InputLength - (InputLength % 3) local UnrollStop = InputLength - 13 local EncodeA = ENCODE_A local EncodeB = ENCODE_B local AlphabetBytes = ALPHABET_BYTES while InputIndex <= UnrollStop do local Word0 = buffer.readu32(Input, InputIndex) local Word1 = buffer.readu32(Input, InputIndex + 3) local Word2 = buffer.readu32(Input, InputIndex + 6) local Word3 = buffer.readu32(Input, InputIndex + 9) local KeyA0 = Word0 % 65536 local KeyB0 = (Word0 // 256) % 65536 buffer.writeu32(Output, OutputIndex, buffer.readu16(EncodeA, KeyA0 * 2) + buffer.readu16(EncodeB, KeyB0 * 2) * 0x10000) local KeyA1 = Word1 % 65536 local KeyB1 = (Word1 // 256) % 65536 buffer.writeu32(Output, OutputIndex + 4, buffer.readu16(EncodeA, KeyA1 * 2) + buffer.readu16(EncodeB, KeyB1 * 2) * 0x10000) local KeyA2 = Word2 % 65536 local KeyB2 = (Word2 // 256) % 65536 buffer.writeu32(Output, OutputIndex + 8, buffer.readu16(EncodeA, KeyA2 * 2) + buffer.readu16(EncodeB, KeyB2 * 2) * 0x10000) local KeyA3 = Word3 % 65536 local KeyB3 = (Word3 // 256) % 65536 buffer.writeu32(Output, OutputIndex + 12, buffer.readu16(EncodeA, KeyA3 * 2) + buffer.readu16(EncodeB, KeyB3 * 2) * 0x10000) InputIndex += 12 OutputIndex += 16 end while InputIndex < FullTripletEnd do local KeyA = buffer.readu16(Input, InputIndex) local Byte2 = buffer.readu8(Input, InputIndex + 2) local KeyB = (KeyA // 256) + Byte2 * 256 buffer.writeu32(Output, OutputIndex, buffer.readu16(EncodeA, KeyA * 2) + buffer.readu16(EncodeB, KeyB * 2) * 0x10000) InputIndex += 3 OutputIndex += 4 end local Remainder = InputLength - InputIndex if Remainder == 1 then local Byte0 = buffer.readu8(Input, InputIndex) local Sextet0 = Byte0 // 4 local Sextet1 = (Byte0 % 4) * 16 local Pair = buffer.readu8(AlphabetBytes, Sextet0) + buffer.readu8(AlphabetBytes, Sextet1) * 256 buffer.writeu16(Output, OutputIndex, Pair) buffer.writeu8(Output, OutputIndex + 2, PADDING_CHARACTER) buffer.writeu8(Output, OutputIndex + 3, PADDING_CHARACTER) elseif Remainder == 2 then local Byte0 = buffer.readu8(Input, InputIndex) local Byte1 = buffer.readu8(Input, InputIndex + 1) local KeyA = Byte0 + Byte1 * 256 buffer.writeu16(Output, OutputIndex, buffer.readu16(EncodeA, KeyA * 2)) local Sextet2 = (Byte1 % 16) * 4 buffer.writeu8(Output, OutputIndex + 2, buffer.readu8(AlphabetBytes, Sextet2)) buffer.writeu8(Output, OutputIndex + 3, PADDING_CHARACTER) end return Output end local function Decode(Input: buffer): buffer local InputLength = buffer.len(Input) if InputLength == 0 then return buffer.create(0) end local Padding = 0 if buffer.readu8(Input, InputLength - 1) == PADDING_CHARACTER then Padding = 1 if buffer.readu8(Input, InputLength - 2) == PADDING_CHARACTER then Padding = 2 end end local Output = buffer.create((InputLength // 4) * 3 - Padding) local InputIndex = 0 local OutputIndex = 0 local BodyEnd = InputLength - 4 local UnrollStop = BodyEnd - 8 local DecodePair = DECODE_PAIR local Pair0 = PAIR_A_BYTE0 local PairAHigh = PAIR_A_BYTE1_HIGH local PairBLow = PAIR_B_BYTE1_LOW local Pair2 = PAIR_B_BYTE2 local Dtet = DECODE_TET while InputIndex <= UnrollStop do local Word0 = buffer.readu32(Input, InputIndex) local Word1 = buffer.readu32(Input, InputIndex + 4) local PairA0 = buffer.readu16(DecodePair, (Word0 % 65536) * 2) local PairB0 = buffer.readu16(DecodePair, (Word0 // 65536) * 2) buffer.writeu8(Output, OutputIndex, buffer.readu8(Pair0, PairA0)) buffer.writeu8(Output, OutputIndex + 1, buffer.readu8(PairAHigh, PairA0) + buffer.readu8(PairBLow, PairB0)) buffer.writeu8(Output, OutputIndex + 2, buffer.readu8(Pair2, PairB0)) local PairA1 = buffer.readu16(DecodePair, (Word1 % 65536) * 2) local PairB1 = buffer.readu16(DecodePair, (Word1 // 65536) * 2) buffer.writeu8(Output, OutputIndex + 3, buffer.readu8(Pair0, PairA1)) buffer.writeu8(Output, OutputIndex + 4, buffer.readu8(PairAHigh, PairA1) + buffer.readu8(PairBLow, PairB1)) buffer.writeu8(Output, OutputIndex + 5, buffer.readu8(Pair2, PairB1)) InputIndex += 8 OutputIndex += 6 end while InputIndex <= BodyEnd - 4 do local Word = buffer.readu32(Input, InputIndex) local PairA = buffer.readu16(DecodePair, (Word % 65536) * 2) local PairB = buffer.readu16(DecodePair, (Word // 65536) * 2) buffer.writeu8(Output, OutputIndex, buffer.readu8(Pair0, PairA)) buffer.writeu8(Output, OutputIndex + 1, buffer.readu8(PairAHigh, PairA) + buffer.readu8(PairBLow, PairB)) buffer.writeu8(Output, OutputIndex + 2, buffer.readu8(Pair2, PairB)) InputIndex += 4 OutputIndex += 3 end local Char0 = buffer.readu8(Input, InputIndex) local Char1 = buffer.readu8(Input, InputIndex + 1) local Char2 = buffer.readu8(Input, InputIndex + 2) local Char3 = buffer.readu8(Input, InputIndex + 3) local Decoded0 = buffer.readu8(Dtet, Char0) local Decoded1 = buffer.readu8(Dtet, Char1) if Char2 == PADDING_CHARACTER then local PairA = Decoded0 * 64 + Decoded1 buffer.writeu8(Output, OutputIndex, buffer.readu8(Pair0, PairA)) elseif Char3 == PADDING_CHARACTER then local Decoded2 = buffer.readu8(Dtet, Char2) local PairA = Decoded0 * 64 + Decoded1 local PairB = Decoded2 * 64 buffer.writeu8(Output, OutputIndex, buffer.readu8(Pair0, PairA)) buffer.writeu8(Output, OutputIndex + 1, buffer.readu8(PairAHigh, PairA) + (PairB // 256)) else local Decoded2 = buffer.readu8(Dtet, Char2) local Decoded3 = buffer.readu8(Dtet, Char3) local PairA = Decoded0 * 64 + Decoded1 local PairB = Decoded2 * 64 + Decoded3 buffer.writeu8(Output, OutputIndex, buffer.readu8(Pair0, PairA)) buffer.writeu8(Output, OutputIndex + 1, buffer.readu8(PairAHigh, PairA) + buffer.readu8(PairBLow, PairB)) buffer.writeu8(Output, OutputIndex + 2, buffer.readu8(Pair2, PairB)) end return Output end return { Encode = Encode, Decode = Decode }
3,196
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Utilities/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 XOR = bit32.bxor local LEFTROTATE = bit32.lrotate local Temp for Index = 1, 7 do V00 += V04 + M00; V12 = LEFTROTATE(XOR(V12, V00), 16) V08 += V12; V04 = LEFTROTATE(XOR(V04, V08), 20) V00 += V04 + M01; V12 = LEFTROTATE(XOR(V12, V00), 24) V08 += V12; V04 = LEFTROTATE(XOR(V04, V08), 25) V01 += V05 + M02; V13 = LEFTROTATE(XOR(V13, V01), 16) V09 += V13; V05 = LEFTROTATE(XOR(V05, V09), 20) V01 += V05 + M03; V13 = LEFTROTATE(XOR(V13, V01), 24) V09 += V13; V05 = LEFTROTATE(XOR(V05, V09), 25) V02 += V06 + M04; V14 = LEFTROTATE(XOR(V14, V02), 16) V10 += V14; V06 = LEFTROTATE(XOR(V06, V10), 20) V02 += V06 + M05; V14 = LEFTROTATE(XOR(V14, V02), 24) V10 += V14; V06 = LEFTROTATE(XOR(V06, V10), 25) V03 += V07 + M06; V15 = LEFTROTATE(XOR(V15, V03), 16) V11 += V15; V07 = LEFTROTATE(XOR(V07, V11), 20) V03 += V07 + M07; V15 = LEFTROTATE(XOR(V15, V03), 24) V11 += V15; V07 = LEFTROTATE(XOR(V07, V11), 25) V00 += V05 + M08; V15 = LEFTROTATE(XOR(V15, V00), 16) V10 += V15; V05 = LEFTROTATE(XOR(V05, V10), 20) V00 += V05 + M09; V15 = LEFTROTATE(XOR(V15, V00), 24) V10 += V15; V05 = LEFTROTATE(XOR(V05, V10), 25) V01 += V06 + M10; V12 = LEFTROTATE(XOR(V12, V01), 16) V11 += V12; V06 = LEFTROTATE(XOR(V06, V11), 20) V01 += V06 + M11; V12 = LEFTROTATE(XOR(V12, V01), 24) V11 += V12; V06 = LEFTROTATE(XOR(V06, V11), 25) V02 += V07 + M12; V13 = LEFTROTATE(XOR(V13, V02), 16) V08 += V13; V07 = LEFTROTATE(XOR(V07, V08), 20) V02 += V07 + M13; V13 = LEFTROTATE(XOR(V13, V02), 24) V08 += V13; V07 = LEFTROTATE(XOR(V07, V08), 25) V03 += V04 + M14; V14 = LEFTROTATE(XOR(V14, V03), 16) V09 += V14; V04 = LEFTROTATE(XOR(V04, V09), 20) V03 += V04 + M15; V14 = LEFTROTATE(XOR(V14, V03), 24) V09 += V14; V04 = LEFTROTATE(XOR(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, XOR(V00, V08)) buffer.writeu32(Result, 4, XOR(V01, V09)) buffer.writeu32(Result, 8, XOR(V02, V10)) buffer.writeu32(Result, 12, XOR(V03, V11)) buffer.writeu32(Result, 16, XOR(V04, V12)) buffer.writeu32(Result, 20, XOR(V05, V13)) buffer.writeu32(Result, 24, XOR(V06, V14)) buffer.writeu32(Result, 28, XOR(V07, V15)) buffer.writeu32(Result, 32, XOR(V08, Hash00)) buffer.writeu32(Result, 36, XOR(V09, Hash01)) buffer.writeu32(Result, 40, XOR(V10, Hash02)) buffer.writeu32(Result, 44, XOR(V11, Hash03)) buffer.writeu32(Result, 48, XOR(V12, Hash04)) buffer.writeu32(Result, 52, XOR(V13, Hash05)) buffer.writeu32(Result, 56, XOR(V14, Hash06)) buffer.writeu32(Result, 60, XOR(V15, Hash07)) return Result else local Result = buffer.create(CV_SIZE) buffer.writeu32(Result, 0, XOR(V00, V08)) buffer.writeu32(Result, 4, XOR(V01, V09)) buffer.writeu32(Result, 8, XOR(V02, V10)) buffer.writeu32(Result, 12, XOR(V03, V11)) buffer.writeu32(Result, 16, XOR(V04, V12)) buffer.writeu32(Result, 20, XOR(V05, V13)) buffer.writeu32(Result, 24, XOR(V06, V14)) buffer.writeu32(Result, 28, XOR(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,393
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Utilities/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, 2 do 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) 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 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) local Leftover = BytesToProcess % 4 for Index = 0, BytesToProcess - Leftover - 1, 4 do local DataWord = buffer.readu32(Data, DataOffset + Index) local KeystreamWord = buffer.readu32(State, Index) buffer.writeu32(Output, DataOffset + Index, bit32.bxor(DataWord, KeystreamWord)) end for Index = BytesToProcess - Leftover, 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,274
daily3014/rbx-cryptography
daily3014-rbx-cryptography-f07e0f5/src/Utilities/CSPRNG/Conversions.luau
--[=[ Cryptography library: Conversions Return type: string / buffer Example Usage: local HexString = Conversions.ToHex(buffer.fromstring("Hello World")) local OriginalBuffer = Conversions.FromHex("48656c6c6f20576f726c64") --]=] --!strict --!optimize 2 --!native local ENCODE_LOOKUP = buffer.create(256 * 2) do local HexChars = "0123456789abcdef" for Byte = 0, 255 do local HighNibble = bit32.rshift(Byte, 4) local LowNibble = Byte % 16 local HighChar = string.byte(HexChars, HighNibble + 1) local LowChar = string.byte(HexChars, LowNibble + 1) local Combined = HighChar + bit32.lshift(LowChar, 8) buffer.writeu16(ENCODE_LOOKUP, Byte * 2, Combined) end end local DECODE_LOOKUP = buffer.create(65536 * 2) do for High = 0, 255 do for Low = 0, 255 do local HighNibble = 0 local LowNibble = 0 if High >= 48 and High <= 57 then HighNibble = High - 48 elseif High >= 65 and High <= 70 then HighNibble = High - 55 elseif High >= 97 and High <= 102 then HighNibble = High - 87 else HighNibble = 0 end if Low >= 48 and Low <= 57 then LowNibble = Low - 48 elseif Low >= 65 and Low <= 70 then LowNibble = Low - 55 elseif Low >= 97 and Low <= 102 then LowNibble = Low - 87 else LowNibble = 0 end local Combined = bit32.lshift(HighNibble, 4) + LowNibble local Index = bit32.lshift(Low, 8) + High buffer.writeu16(DECODE_LOOKUP, Index * 2, Combined) end end end local Conversions = {} function Conversions.ToHex(Buffer: buffer): string local Length = buffer.len(Buffer) local Hex = buffer.create(Length * 2) local Lookup = ENCODE_LOOKUP local Leftover = Length % 8 local HexCursor = 0 for Index = 0, Length - Leftover - 1, 8 do local Hex1 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index) * 2) local Hex2 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 1) * 2) local Hex3 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 2) * 2) local Hex4 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 3) * 2) local Hex5 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 4) * 2) local Hex6 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 5) * 2) local Hex7 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 6) * 2) local Hex8 = buffer.readu16(Lookup, buffer.readu8(Buffer, Index + 7) * 2) buffer.writeu16(Hex, HexCursor, Hex1) buffer.writeu16(Hex, HexCursor + 2, Hex2) buffer.writeu16(Hex, HexCursor + 4, Hex3) buffer.writeu16(Hex, HexCursor + 6, Hex4) buffer.writeu16(Hex, HexCursor + 8, Hex5) buffer.writeu16(Hex, HexCursor + 10, Hex6) buffer.writeu16(Hex, HexCursor + 12, Hex7) buffer.writeu16(Hex, HexCursor + 14, Hex8) HexCursor += 16 end for Index = Length - Leftover, Length - 1 do local HexPair = buffer.readu16(Lookup, buffer.readu8(Buffer, Index) * 2) buffer.writeu16(Hex, HexCursor, HexPair) HexCursor += 2 end return buffer.tostring(Hex) end function Conversions.FromHex(Hex: string | buffer): buffer local BufferHex = if type(Hex) == "string" then buffer.fromstring(Hex) else Hex local Length = buffer.len(BufferHex) if Length % 2 ~= 0 then error(`Length must be even, got {Length}`) end local Buffer = buffer.create(bit32.rshift(Length, 1)) local Leftover = Length % 16 local BufferCursor = 0 local Lookup = DECODE_LOOKUP for Index = 0, Length - Leftover - 1, 16 do local Pair1 = buffer.readu16(BufferHex, Index) local Pair2 = buffer.readu16(BufferHex, Index + 2) local Pair3 = buffer.readu16(BufferHex, Index + 4) local Pair4 = buffer.readu16(BufferHex, Index + 6) local Pair5 = buffer.readu16(BufferHex, Index + 8) local Pair6 = buffer.readu16(BufferHex, Index + 10) local Pair7 = buffer.readu16(BufferHex, Index + 12) local Pair8 = buffer.readu16(BufferHex, Index + 14) local Byte1 = buffer.readu16(Lookup, Pair1 * 2) local Byte2 = buffer.readu16(Lookup, Pair2 * 2) local Byte3 = buffer.readu16(Lookup, Pair3 * 2) local Byte4 = buffer.readu16(Lookup, Pair4 * 2) local Byte5 = buffer.readu16(Lookup, Pair5 * 2) local Byte6 = buffer.readu16(Lookup, Pair6 * 2) local Byte7 = buffer.readu16(Lookup, Pair7 * 2) local Byte8 = buffer.readu16(Lookup, Pair8 * 2) local Chunk1 = bit32.lshift(Byte4, 24) + bit32.lshift(Byte3, 16) + bit32.lshift(Byte2, 8) + Byte1 local Chunk2 = bit32.lshift(Byte8, 24) + bit32.lshift(Byte7, 16) + bit32.lshift(Byte6, 8) + Byte5 buffer.writeu32(Buffer, BufferCursor, Chunk1) buffer.writeu32(Buffer, BufferCursor + 4, Chunk2) BufferCursor += 8 end for Index = Length - Leftover, Length - 1, 2 do local Pair = buffer.readu16(BufferHex, Index) local Byte = buffer.readu16(Lookup, Pair * 2) buffer.writeu8(Buffer, BufferCursor, Byte) BufferCursor += 1 end return Buffer end return Conversions
1,625