From a2acb6155f49f17e6bd58d9a70f6d4dda0bb50c2 Mon Sep 17 00:00:00 2001 From: Marcin Krzyzanowski Date: Mon, 19 Jan 2026 19:46:13 +0100 Subject: [PATCH] Refactor UInt128 initialization from byte array and clarify variable names in tests Replaces unsafe memory operations in UInt128 init with manual byte parsing to improve safety and readability. Updates variable names in RSASecKeyTests for clarity and safety. --- Sources/CryptoSwift/UInt128.swift | 10 ++++++---- Tests/CryptoSwiftTests/RSASecKeyTests.swift | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Sources/CryptoSwift/UInt128.swift b/Sources/CryptoSwift/UInt128.swift index 2c9ef30..7023620 100644 --- a/Sources/CryptoSwift/UInt128.swift +++ b/Sources/CryptoSwift/UInt128.swift @@ -25,10 +25,12 @@ struct UInt128: Equatable, ExpressibleByIntegerLiteral { } init(_ raw: Array) { - self = raw.prefix(MemoryLayout.stride).withUnsafeBytes({ (rawBufferPointer) -> UInt128 in - let arr = rawBufferPointer.bindMemory(to: UInt64.self) - return UInt128((arr[0].bigEndian, arr[1].bigEndian)) - }) + precondition(raw.count >= 16, "UInt128 requires at least 16 bytes") + let a = UInt64(raw[0]) << 56 | UInt64(raw[1]) << 48 | UInt64(raw[2]) << 40 | UInt64(raw[3]) << 32 | + UInt64(raw[4]) << 24 | UInt64(raw[5]) << 16 | UInt64(raw[6]) << 8 | UInt64(raw[7]) + let b = UInt64(raw[8]) << 56 | UInt64(raw[9]) << 48 | UInt64(raw[10]) << 40 | UInt64(raw[11]) << 32 | + UInt64(raw[12]) << 24 | UInt64(raw[13]) << 16 | UInt64(raw[14]) << 8 | UInt64(raw[15]) + self.init((a, b)) } init(_ raw: ArraySlice) { diff --git a/Tests/CryptoSwiftTests/RSASecKeyTests.swift b/Tests/CryptoSwiftTests/RSASecKeyTests.swift index 1a3cfcf..d53fee8 100644 --- a/Tests/CryptoSwiftTests/RSASecKeyTests.swift +++ b/Tests/CryptoSwiftTests/RSASecKeyTests.swift @@ -493,7 +493,7 @@ ) """ - private func initSecKey(rawRepresentation unsafe: Data) throws -> SecKey { + private func initSecKey(rawRepresentation rawKey: Data) throws -> SecKey { let attributes: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, @@ -502,7 +502,7 @@ ] var error: Unmanaged? - guard let secKey = SecKeyCreateWithData(unsafe as CFData, attributes as CFDictionary, &error) else { + guard let secKey = SecKeyCreateWithData(rawKey as CFData, attributes as CFDictionary, &error) else { throw NSError(domain: "Error constructing SecKey from raw key data: \(error.debugDescription)", code: 0, userInfo: nil) }