Browse Source

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.
Marcin Krzyzanowski 4 days ago
parent
commit
a2acb6155f

+ 6 - 4
Sources/CryptoSwift/UInt128.swift

@@ -25,10 +25,12 @@ struct UInt128: Equatable, ExpressibleByIntegerLiteral {
   }
   }
 
 
   init(_ raw: Array<UInt8>) {
   init(_ raw: Array<UInt8>) {
-    self = raw.prefix(MemoryLayout<UInt128>.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<UInt8>) {
   init(_ raw: ArraySlice<UInt8>) {

+ 2 - 2
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] = [
       let attributes: [String: Any] = [
         kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
         kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
         kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
         kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
@@ -502,7 +502,7 @@
       ]
       ]
 
 
       var error: Unmanaged<CFError>?
       var error: Unmanaged<CFError>?
-      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)
         throw NSError(domain: "Error constructing SecKey from raw key data: \(error.debugDescription)", code: 0, userInfo: nil)
       }
       }