diff --git a/Package.resolved b/Package.resolved index 36c79bbd..5c722eef 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,70 +1,59 @@ { - "object": { - "pins": [ - { - "package": "AnyCodable", - "repositoryURL": "https://github.com/Flight-School/AnyCodable", - "state": { - "branch": null, - "revision": "862808b2070cd908cb04f9aafe7de83d35f81b05", - "version": "0.6.7" - } - }, - { - "package": "BigInt", - "repositoryURL": "https://github.com/attaswift/BigInt", - "state": { - "branch": null, - "revision": "0ed110f7555c34ff468e72e1686e59721f2b0da6", - "version": "5.3.0" - } - }, - { - "package": "CryptoSwift", - "repositoryURL": "https://github.com/krzyzanowskim/CryptoSwift", - "state": { - "branch": null, - "revision": "7892a123f7e8d0fe62f9f03728b17bbd4f94df5c", - "version": "1.8.1" - } - }, - { - "package": "curvelib.swift", - "repositoryURL": "https://github.com/tkey/curvelib.swift", - "state": { - "branch": null, - "revision": "7dad3bf1793de263f83406c08c18c9316abf082f", - "version": "0.1.2" - } - }, - { - "package": "FetchNodeDetails", - "repositoryURL": "https://github.com/torusresearch/fetch-node-details-swift.git", - "state": { - "branch": null, - "revision": "d591af500f32ce3c88d04af9bb74d746585acfea", - "version": "5.1.0" - } - }, - { - "package": "jwt-kit", - "repositoryURL": "https://github.com/vapor/jwt-kit", - "state": { - "branch": null, - "revision": "e05513b5aec24f88012b6e3034115b6bc915356a", - "version": "4.13.2" - } - }, - { - "package": "swift-crypto", - "repositoryURL": "https://github.com/apple/swift-crypto.git", - "state": { - "branch": null, - "revision": "f0525da24dc3c6cbb2b6b338b65042bc91cbc4bb", - "version": "3.3.0" - } + "pins" : [ + { + "identity" : "anycodable", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Flight-School/AnyCodable", + "state" : { + "revision" : "862808b2070cd908cb04f9aafe7de83d35f81b05", + "version" : "0.6.7" } - ] - }, - "version": 1 + }, + { + "identity" : "bigint", + "kind" : "remoteSourceControl", + "location" : "https://github.com/attaswift/BigInt", + "state" : { + "revision" : "0ed110f7555c34ff468e72e1686e59721f2b0da6", + "version" : "5.3.0" + } + }, + { + "identity" : "curvelib.swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/tkey/curvelib.swift", + "state" : { + "revision" : "2df9f638fd121b445ce3b410cd79ac4d0cfa94ed", + "version" : "1.0.0" + } + }, + { + "identity" : "fetch-node-details-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/torusresearch/fetch-node-details-swift", + "state" : { + "revision" : "bf2f0759da5c5c80765773b08c2756045edf608f", + "version" : "5.2.0" + } + }, + { + "identity" : "jwt-kit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/vapor/jwt-kit", + "state" : { + "revision" : "c2595b9ad7f512d7f334830b4df1fed6e917946a", + "version" : "4.13.4" + } + }, + { + "identity" : "swift-crypto", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-crypto.git", + "state" : { + "revision" : "f0525da24dc3c6cbb2b6b338b65042bc91cbc4bb", + "version" : "3.3.0" + } + } + ], + "version" : 2 } diff --git a/Package.swift b/Package.swift index 5ca19183..c0123670 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.3 +// swift-tools-version:5.7 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription @@ -11,12 +11,10 @@ let package = Package( targets: ["TorusUtils"]) ], dependencies: [ - .package(name: "curvelib.swift", url: "https://github.com/tkey/curvelib.swift", from: "0.1.2"), - .package(name:"FetchNodeDetails", url: "https://github.com/torusresearch/fetch-node-details-swift", from: "5.1.0"), - .package(name:"CryptoSwift", url: "https://github.com/krzyzanowskim/CryptoSwift",from: "1.5.1"), - .package(name:"jwt-kit", url: "https://github.com/vapor/jwt-kit", from: "4.0.0"), + .package(url: "https://github.com/tkey/curvelib.swift", from: "1.0.0"), + .package(url: "https://github.com/torusresearch/fetch-node-details-swift", from: "5.2.0"), + .package(url: "https://github.com/vapor/jwt-kit", from: "4.0.0"), .package( - name:"AnyCodable", url: "https://github.com/Flight-School/AnyCodable", from: "0.6.0" ), @@ -24,16 +22,14 @@ let package = Package( targets: [ .target( name: "TorusUtils", - dependencies: ["FetchNodeDetails", "CryptoSwift", "AnyCodable", + dependencies: ["AnyCodable", + .product(name: "FetchNodeDetails", package: "fetch-node-details-swift"), .product(name: "curveSecp256k1", package: "curvelib.swift"), - .product(name: "encryption_aes_cbc_sha512", package: "curvelib.swift"), - ] - ), + ]), .testTarget( name: "TorusUtilsTests", dependencies: ["TorusUtils", .product(name: "JWTKit", package: "jwt-kit")] ) - ], - swiftLanguageVersions: [.v5] + ] ) diff --git a/Sources/TorusUtils/AbstractTorusUtils.swift b/Sources/TorusUtils/AbstractTorusUtils.swift index 8d01ed79..ffcacf8a 100644 --- a/Sources/TorusUtils/AbstractTorusUtils.swift +++ b/Sources/TorusUtils/AbstractTorusUtils.swift @@ -1,5 +1,6 @@ -import BigInt +//import BigInt import CommonSources +import BigInt import FetchNodeDetails import Foundation diff --git a/Sources/TorusUtils/Extensions/Array+Extension.swift b/Sources/TorusUtils/Extensions/Array+Extension.swift new file mode 100644 index 00000000..10c61bcd --- /dev/null +++ b/Sources/TorusUtils/Extensions/Array+Extension.swift @@ -0,0 +1,82 @@ +// +// CryptoSwift +// +// Copyright (C) 2014-2022 Marcin Krzyżanowski +// This software is provided 'as-is', without any express or implied warranty. +// +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: +// +// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. +// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. +// - This notice may not be removed or altered from any source or binary distribution. +// + +extension Array { + @inlinable + init(reserveCapacity: Int) { + self = Array() + self.reserveCapacity(reserveCapacity) + } + + @inlinable + var slice: ArraySlice { + self[self.startIndex ..< self.endIndex] + } + + @inlinable + subscript (safe index: Index) -> Element? { + return indices.contains(index) ? self[index] : nil + } +} + +extension Array where Element == UInt8 { + public init(hex: String) { + self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount) + var buffer: UInt8? + var skip = hex.hasPrefix("0x") ? 2 : 0 + for char in hex.unicodeScalars.lazy { + guard skip == 0 else { + skip -= 1 + continue + } + guard char.value >= 48 && char.value <= 102 else { + removeAll() + return + } + let v: UInt8 + let c: UInt8 = UInt8(char.value) + switch c { + case let c where c <= 57: + v = c - 48 + case let c where c >= 65 && c <= 70: + v = c - 55 + case let c where c >= 97: + v = c - 87 + default: + removeAll() + return + } + if let b = buffer { + append(b << 4 | v) + buffer = nil + } else { + buffer = v + } + } + if let b = buffer { + append(b) + } + } + + public func toHexString() -> String { + `lazy`.reduce(into: "") { + var s = String($1, radix: 16) + if s.count == 1 { + s = "0" + s + } + $0 += s + } + } +} diff --git a/Sources/TorusUtils/Extensions/Data+Extension.swift b/Sources/TorusUtils/Extensions/Data+Extension.swift index 7878a496..5673b055 100755 --- a/Sources/TorusUtils/Extensions/Data+Extension.swift +++ b/Sources/TorusUtils/Extensions/Data+Extension.swift @@ -8,4 +8,16 @@ public extension Data { func addLeading0sForLength64() -> Data { Data(hex: hexString.addLeading0sForLength64()) } + + init(hex: String) { + self.init(Array(hex: hex)) + } + + var bytes: Array { + Array(self) + } + + func toHexString() -> String { + self.bytes.toHexString() + } } diff --git a/Sources/TorusUtils/Extensions/String+Extension.swift b/Sources/TorusUtils/Extensions/String+Extension.swift index 92b80d51..33c2f082 100755 --- a/Sources/TorusUtils/Extensions/String+Extension.swift +++ b/Sources/TorusUtils/Extensions/String+Extension.swift @@ -55,10 +55,12 @@ extension String { func toChecksumAddress() -> String { let lowerCaseAddress = stripHexPrefix().lowercased() let arr = Array(lowerCaseAddress) - let hash = Array(lowerCaseAddress.sha3(.keccak256)) + let hash = keccak256Data(lowerCaseAddress.data(using: .utf8) ?? Data() ).toHexString() + var result = String() for i in 0 ... lowerCaseAddress.count - 1 { - if let val = Int(String(hash[i]), radix: 16), val >= 8 { + let iIndex = hash.index(hash.startIndex, offsetBy: i) + if let val = hash[iIndex].hexDigitValue , val >= 8 { result.append(arr[i].uppercased()) } else { result.append(arr[i]) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 5ecdbf1d..333913a5 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -1,4 +1,3 @@ -import CryptoSwift import Foundation #if canImport(curveSecp256k1) import curveSecp256k1 @@ -10,14 +9,10 @@ import CryptoKit import FetchNodeDetails import OSLog + + extension TorusUtils { - // MARK: - utils - internal func ecdh_sha512(publicKey: PublicKey, privateKey: SecretKey) throws -> [UInt8] { - let shared = try ECDH.ecdhStandard(sk: privateKey, pk: publicKey) - let data = Data(hex: shared).dropFirst() - return data.bytes.sha512() - } internal func combinations(elements: ArraySlice, k: Int) -> [[T]] { if k == 0 { @@ -245,8 +240,9 @@ extension TorusUtils { // Hash the token from OAuth login let timestamp = String(Int(getTimestamp())) - let hashedToken = idToken.sha3(.keccak256) - + let hashedToken = keccak256Data(idToken.data(using: .utf8) ?? Data()).toHexString() + + let nodeSigs = try await commitmentRequest(endpoints: endpoints, verifier: verifier, pubKeyX: pubKeyX, pubKeyY: pubKeyY, timestamp: timestamp, tokenCommitment: hashedToken) os_log("retrieveShares - data after commitment request: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .info), type: .info, nodeSigs) var promiseArrRequest = [URLRequest]() @@ -653,7 +649,7 @@ extension TorusUtils { return BigUInt(message, radix: 16)! } - internal func decryptNodeData(eciesData: EciesHex, ciphertextHex: String, privKey: String, padding: Padding = .pkcs7) throws -> String { + internal func decryptNodeData(eciesData: EciesHex, ciphertextHex: String, privKey: String) throws -> String { let eciesOpts = ECIES( iv: eciesData.iv, ephemPublicKey: eciesData.ephemPublicKey, @@ -661,7 +657,7 @@ extension TorusUtils { mac: eciesData.mac ) - let decryptedSigBuffer = try decrypt(privateKey: privKey, opts: eciesOpts, padding: padding).hexString + let decryptedSigBuffer = try decrypt(privateKey: privKey, opts: eciesOpts).hexString return decryptedSigBuffer } @@ -684,24 +680,11 @@ extension TorusUtils { } public func encrypt(publicKey: String, msg: String, opts: Ecies? = nil) throws -> Ecies { - let ephemPrivateKey = SecretKey() - let ephemPublicKey = try ephemPrivateKey.toPublic() - - let sharedSecret = try ecdh_sha512(publicKey: PublicKey(hex: publicKey), privateKey: ephemPrivateKey) - - let encryptionKey = Array(sharedSecret[0 ..< 32]) - let macKey = Array(sharedSecret[32 ..< 64]) - let random = try randomBytes(ofLength: 16) - let iv: [UInt8] = (opts?.iv ?? random.toHexString()).hexa - - let aes = try AES(key: encryptionKey, blockMode: CBC(iv: iv), padding: .pkcs7) - let ciphertext = try aes.encrypt(msg.customBytes()) - var dataToMac: [UInt8] = iv - dataToMac.append(contentsOf: Data(hex: try ephemPublicKey.serialize(compressed: false))) - dataToMac.append(contentsOf: ciphertext) - let mac = try? HMAC(key: macKey, variant: .sha2(.sha256)).authenticate(dataToMac) - return .init(iv: iv.toHexString(), ephemPublicKey: try ephemPublicKey.serialize(compressed: false), - ciphertext: ciphertext.toHexString(), mac: mac?.toHexString() ?? "") + guard let data = msg.data(using: .utf8) else { + throw TorusUtilError.runtime("Encryption: Invalid utf8 string") + } + let curveMsg = try Encryption.encrypt(pk: PublicKey(hex: publicKey), plainText: data) + return try .init(iv: curveMsg.iv(), ephemPublicKey: curveMsg.ephemeralPublicKey().serialize(compressed: false), ciphertext: curveMsg.chipherText(), mac: curveMsg.mac()) } // MARK: - decrypt shares @@ -712,27 +695,16 @@ extension TorusUtils { for (_, el) in shares.enumerated() { let nodeIndex = el.key - let publicKeyHex = el.value.ephemPublicKey - let sharedSecret = try ecdh_sha512(publicKey: PublicKey(hex: publicKeyHex), privateKey: SecretKey(hex: privateKey)) - guard let data = Data(base64Encoded: el.value.share), - let share = String(data: data, encoding: .utf8)?.hexa + let share = String(data: data, encoding: .utf8) else { throw TorusUtilError.decryptionFailed } - - do { - // AES-CBCblock-256 - let aesKey = Array(sharedSecret[0 ..< 32]) - _ = Array(sharedSecret[32 ..< 64]) // TODO: check mac - let iv = el.value.iv.hexa - let aes = try AES(key: aesKey, blockMode: CBC(iv: iv), padding: .pkcs7) - let decryptData = try aes.decrypt(share) - result[nodeIndex] = decryptData.hexa - } catch let err { - result[nodeIndex] = TorusUtilError.decodingFailed(err.localizedDescription).debugDescription - } + + let ecies: ECIES = .init(iv: el.value.iv, ephemPublicKey: el.value.ephemPublicKey, ciphertext: share, mac: el.value.mac) + result[nodeIndex] = try decrypt(privateKey: privateKey, opts: ecies).toHexString() + if shares.count == result.count { return result } @@ -1347,17 +1319,11 @@ extension TorusUtils { return tupleElements } - public func decrypt(privateKey: String, opts: ECIES, padding: Padding = .pkcs7) throws -> Data { - let sharedSecret = try ecdh_sha512(publicKey: PublicKey(hex: opts.ephemPublicKey), privateKey: SecretKey(hex: privateKey)) - - let aesKey = Array(sharedSecret[0 ..< 32]) - _ = Array(sharedSecret[32 ..< 64]) // TODO: check mac - let iv = opts.iv.hexa - - let aes = try AES(key: aesKey, blockMode: CBC(iv: iv), padding: padding) - let plaintext = try aes.decrypt(opts.ciphertext.hexa) - let data = Data(plaintext) - return data + public func decrypt(privateKey: String, opts: ECIES) throws -> Data { + let secret = try SecretKey(hex: privateKey) + let msg = try EncryptedMessage(cipherText: opts.ciphertext, ephemeralPublicKey: PublicKey(hex: opts.ephemPublicKey), iv: opts.iv, mac: opts.mac) + let result = try Encryption.decrypt(sk: secret, encrypted: msg) + return result } } diff --git a/Sources/TorusUtils/Helpers/Common.swift b/Sources/TorusUtils/Helpers/Common.swift index 5e872761..bcb548d4 100644 --- a/Sources/TorusUtils/Helpers/Common.swift +++ b/Sources/TorusUtils/Helpers/Common.swift @@ -1,14 +1,17 @@ import BigInt import Foundation +import curveSecp256k1 + func keccak256Data(_ data: Data) -> Data { - return data.sha3(.keccak256) + let hash = try? keccak256(data: data) + return hash ?? Data([]) } func generateAddressFromPubKey(publicKeyX: String, publicKeyY: String) -> String { let publicKeyHex = publicKeyX.addLeading0sForLength64() + publicKeyY.addLeading0sForLength64() let publicKeyData = Data(hex: publicKeyHex) - let ethAddrData = publicKeyData.sha3(.keccak256).suffix(20) + let ethAddrData = keccak256Data(publicKeyData).suffix(20) let ethAddrlower = ethAddrData.toHexString().addHexPrefix() return ethAddrlower.toChecksumAddress() } diff --git a/Sources/TorusUtils/Models/RetrieveSharesResponseModel.swift b/Sources/TorusUtils/Models/RetrieveSharesResponseModel.swift index 9ec2d7d2..d1ccefff 100644 --- a/Sources/TorusUtils/Models/RetrieveSharesResponseModel.swift +++ b/Sources/TorusUtils/Models/RetrieveSharesResponseModel.swift @@ -17,12 +17,14 @@ public struct RetrieveDecryptAndReconstuctResponseModel { public let share: String public let pubKeyX: String public let pubKeyY: String + public let mac: String - public init(iv: String, ephemPublicKey: String, share: String, pubKeyX: String, pubKeyY: String) { + public init(iv: String, ephemPublicKey: String, share: String, pubKeyX: String, pubKeyY: String, mac: String) { self.iv = iv self.ephemPublicKey = ephemPublicKey self.share = share self.pubKeyX = pubKeyX self.pubKeyY = pubKeyY + self.mac = mac } } diff --git a/Sources/TorusUtils/TorusUtils.swift b/Sources/TorusUtils/TorusUtils.swift index da395eba..06ba7d2c 100644 --- a/Sources/TorusUtils/TorusUtils.swift +++ b/Sources/TorusUtils/TorusUtils.swift @@ -247,8 +247,8 @@ open class TorusUtils: AbstractTorusUtils { // Hash the token from OAuth login let timestamp = String(Int(getTimestamp())) - let hashedToken = idToken.sha3(.keccak256) + let hashedToken = keccak256Data(idToken.data(using: .utf8) ?? Data()).toHexString() var lookupPubkeyX: String = "" var lookupPubkeyY: String = "" do { @@ -436,7 +436,7 @@ open class TorusUtils: AbstractTorusUtils { let pointHex = PointHex(from: first.publicKey) shareResponses.append(pointHex) let metadata = first.metadata - let model = RetrieveDecryptAndReconstuctResponseModel(iv: metadata.iv, ephemPublicKey: metadata.ephemPublicKey, share: first.share, pubKeyX: pointHex.x, pubKeyY: pointHex.y) + let model = RetrieveDecryptAndReconstuctResponseModel(iv: metadata.iv, ephemPublicKey: metadata.ephemPublicKey, share: first.share, pubKeyX: pointHex.x, pubKeyY: pointHex.y, mac: metadata.mac) resultArray[i] = model } } else if let decodedResult = decoded.result as? LegacyShareRequestResult { @@ -448,7 +448,7 @@ open class TorusUtils: AbstractTorusUtils { let metadata = first.metadata X = pointHex.x Y = pointHex.y - let model = RetrieveDecryptAndReconstuctResponseModel(iv: metadata.iv, ephemPublicKey: metadata.ephemPublicKey, share: first.share, pubKeyX: pointHex.x, pubKeyY: pointHex.y) + let model = RetrieveDecryptAndReconstuctResponseModel(iv: metadata.iv, ephemPublicKey: metadata.ephemPublicKey, share: first.share, pubKeyX: pointHex.x, pubKeyY: pointHex.y, mac: metadata.mac) resultArray[i] = model } } else { diff --git a/Tests/TorusUtilsTests/AquaTest.swift b/Tests/TorusUtilsTests/AquaTest.swift index 721e69b8..930af24d 100644 --- a/Tests/TorusUtilsTests/AquaTest.swift +++ b/Tests/TorusUtilsTests/AquaTest.swift @@ -130,7 +130,8 @@ class AquaTest: XCTestCase { let verifierID: String = TORUS_TEST_EMAIL let verifierParams = VerifierParams(verifier_id: verifierID) let jwt = try! generateIdToken(email: TORUS_TEST_EMAIL) - let hashedIDToken = jwt.sha3(.keccak256) + let hashedIDToken = keccak256Data(jwt.data(using: .utf8) ?? Data()).toHexString(); + let extraParams = ["verifier_id": TORUS_TEST_EMAIL, "sub_verifier_ids": [TORUS_TEST_VERIFIER], "verify_params": [["verifier_id": TORUS_TEST_EMAIL, "idtoken": jwt]]] as [String: Codable] let nodeDetails = try await getFNDAndTUData(verifer: verifier, veriferID: verifierID) let data = try await tu.retrieveShares(endpoints: nodeDetails.getTorusNodeEndpoints(), torusNodePubs: nodeDetails.getTorusNodePub(), indexes: nodeDetails.getTorusIndexes(), verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken, extraParams: extraParams) @@ -144,10 +145,10 @@ class AquaTest: XCTestCase { XCTAssertEqual(data.oAuthKeyData?.privKey, "488d39ac548e15cfb0eaf161d86496e1645b09437df21311e24a56c4efd76355") XCTAssertEqual(data.sessionData?.sessionTokenData.count, 0) XCTAssertEqual(data.sessionData?.sessionAuthKey, "") - XCTAssertEqual(data.metadata?.pubNonce, nil) + XCTAssertEqual(data.metadata?.pubNonce == nil, true) XCTAssertEqual(data.metadata?.nonce, BigUInt(0)) - XCTAssertEqual(data.metadata?.typeOfUser, .v1) - XCTAssertEqual(data.metadata?.upgraded, nil) + XCTAssertEqual(data.metadata?.typeOfUser == UserType.v1, true) + XCTAssertEqual(data.metadata?.upgraded == nil, true) } } diff --git a/Tests/TorusUtilsTests/CyanTest.swift b/Tests/TorusUtilsTests/CyanTest.swift index 718dbe70..25df03f2 100644 --- a/Tests/TorusUtilsTests/CyanTest.swift +++ b/Tests/TorusUtilsTests/CyanTest.swift @@ -137,7 +137,7 @@ class CyanTest: XCTestCase { let verifierID: String = TORUS_TEST_EMAIL let jwt = try! generateIdToken(email: TORUS_TEST_EMAIL) let verifierParams = VerifierParams(verifier_id: verifierID) - let hashedIDToken = jwt.sha3(.keccak256) + let hashedIDToken = keccak256Data(jwt.data(using: .utf8) ?? Data() ).toHexString() let extraParams = ["verifier_id": TORUS_TEST_EMAIL, "sub_verifier_ids": [TORUS_TEST_VERIFIER], "verify_params": [["verifier_id": TORUS_TEST_EMAIL, "idtoken": jwt]]] as [String: Codable] let nodeDetails = try await getFNDAndTUData(verifer: verifier, veriferID: verifierID) let data = try await tu.retrieveShares(endpoints: nodeDetails.getTorusNodeEndpoints(), torusNodePubs: nodeDetails.getTorusNodePub(), indexes: nodeDetails.getTorusIndexes(), verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken, extraParams: extraParams) @@ -151,9 +151,9 @@ class CyanTest: XCTestCase { XCTAssertEqual(data.oAuthKeyData?.privKey, "45a5b62c4ff5490baa75d33bf4f03ba6c5b0095678b0f4055312eef7b780b7bf") XCTAssertEqual(data.sessionData?.sessionTokenData.count, 0) XCTAssertEqual(data.sessionData?.sessionAuthKey, "") - XCTAssertEqual(data.metadata?.pubNonce, nil) + XCTAssertEqual(data.metadata?.pubNonce == nil, true) XCTAssertEqual(data.metadata?.nonce, BigUInt(0)) - XCTAssertEqual(data.metadata?.typeOfUser, .v1) - XCTAssertEqual(data.metadata?.upgraded, nil) + XCTAssertEqual(data.metadata?.typeOfUser == UserType.v1, true) + XCTAssertEqual(data.metadata?.upgraded == nil, true) } } diff --git a/Tests/TorusUtilsTests/MainnetTest.swift b/Tests/TorusUtilsTests/MainnetTest.swift index e10d1c3b..d4b6fe37 100644 --- a/Tests/TorusUtilsTests/MainnetTest.swift +++ b/Tests/TorusUtilsTests/MainnetTest.swift @@ -150,7 +150,7 @@ class MainnetTests: XCTestCase { let verifier: String = TORUS_TEST_AGGREGATE_VERIFIER let verifierID: String = TORUS_TEST_EMAIL let jwt = try! generateIdToken(email: TORUS_TEST_EMAIL) - let hashedIDToken = jwt.sha3(.keccak256) + let hashedIDToken = keccak256Data(jwt.data(using: .utf8) ?? Data()).toHexString() let extraParams = ["verifier_id": TORUS_TEST_EMAIL, "sub_verifier_ids": [TORUS_TEST_VERIFIER], "verify_params": [["verifier_id": TORUS_TEST_EMAIL, "idtoken": jwt]]] as [String: Codable] let verifierParams = VerifierParams(verifier_id: verifierID) let nodeDetails = try await get_fnd_and_tu_data(verifer: verifier, veriferID: verifierID) diff --git a/Tests/TorusUtilsTests/SapphireTest.swift b/Tests/TorusUtilsTests/SapphireTest.swift index 05daf893..e8e6325a 100644 --- a/Tests/TorusUtilsTests/SapphireTest.swift +++ b/Tests/TorusUtilsTests/SapphireTest.swift @@ -2,10 +2,8 @@ import BigInt import FetchNodeDetails import JWTKit import XCTest - -import CommonSources import curveSecp256k1 -import encryption_aes_cbc_sha512 +import CommonSources @testable import TorusUtils @@ -123,7 +121,7 @@ final class SapphireTest: XCTestCase { XCTAssertNotEqual(data.sessionData?.sessionAuthKey, "") XCTAssertEqual(data.metadata?.pubNonce?.x, "5d03a0df9b3db067d3363733df134598d42873bb4730298a53ee100975d703cc") XCTAssertEqual(data.metadata?.pubNonce?.y, "279434dcf0ff22f077877a70bcad1732412f853c96f02505547f7ca002b133ed") - XCTAssertEqual(data.metadata?.nonce?.serialize().hexString, "b7d126751b68ecd09e371a23898e6819dee54708a5ead4f6fe83cdc79c0f1c4a") + XCTAssertEqual(data.metadata?.nonce?.serialize().toHexString(), "b7d126751b68ecd09e371a23898e6819dee54708a5ead4f6fe83cdc79c0f1c4a") XCTAssertEqual(data.metadata?.typeOfUser, .v2) XCTAssertEqual(data.metadata?.upgraded, false) } @@ -187,7 +185,7 @@ final class SapphireTest: XCTestCase { XCTAssertNotEqual(data.sessionData?.sessionAuthKey, "") XCTAssertEqual(data.metadata?.pubNonce?.x, "5d03a0df9b3db067d3363733df134598d42873bb4730298a53ee100975d703cc") XCTAssertEqual(data.metadata?.pubNonce?.y, "279434dcf0ff22f077877a70bcad1732412f853c96f02505547f7ca002b133ed") - XCTAssertEqual(data.metadata?.nonce?.serialize().hexString, "b7d126751b68ecd09e371a23898e6819dee54708a5ead4f6fe83cdc79c0f1c4a") + XCTAssertEqual(data.metadata?.nonce?.serialize().toHexString(), "b7d126751b68ecd09e371a23898e6819dee54708a5ead4f6fe83cdc79c0f1c4a") XCTAssertEqual(data.metadata?.typeOfUser, .v2) XCTAssertEqual(data.metadata?.upgraded, false) } @@ -290,7 +288,7 @@ final class SapphireTest: XCTestCase { XCTAssertNotEqual(result.sessionData?.sessionAuthKey, "") XCTAssertEqual(result.metadata?.pubNonce?.x, "5712d789f7ecf3435dd9bf1136c2daaa634f0222d64e289d2abe30a729a6a22b") XCTAssertEqual(result.metadata?.pubNonce?.y, "2d2b4586fd5fd9d15c22f66b61bc475742754a8b96d1edb7b2590e4c4f97b3f0") - XCTAssertEqual(result.metadata?.nonce?.serialize().hexString, "8e80e560ae59319938f7ef727ff2c5346caac1c7f5be96d3076e3342ad1d20b7") + XCTAssertEqual(result.metadata?.nonce?.serialize().toHexString(), "8e80e560ae59319938f7ef727ff2c5346caac1c7f5be96d3076e3342ad1d20b7") XCTAssertEqual(result.metadata?.typeOfUser, .v2) XCTAssertEqual(result.metadata?.upgraded, false) } @@ -299,7 +297,7 @@ final class SapphireTest: XCTestCase { let verifier: String = TORUS_TEST_AGGREGATE_VERIFIER let verifierID: String = email let jwt = try! generateIdToken(email: email) - let hashedIDToken = jwt.sha3(.keccak256) + let hashedIDToken = keccak256Data(jwt.data(using: .utf8) ?? Data()).toHexString() let extraParams = ["verifier_id": email, "sub_verifier_ids": [TORUS_TEST_VERIFIER], "verify_params": [["verifier_id": email, "idtoken": jwt]]] as [String: Codable] let nodeManager = NodeDetailManager(network: .sapphire(.SAPPHIRE_DEVNET)) @@ -313,7 +311,7 @@ final class SapphireTest: XCTestCase { XCTAssertNotNil(data.finalKeyData?.evmAddress) XCTAssertNotEqual(data.finalKeyData?.evmAddress, "") XCTAssertNotNil(data.oAuthKeyData?.evmAddress) - XCTAssertEqual(data.metadata?.typeOfUser, .v2) + XCTAssertEqual(data.metadata?.typeOfUser == UserType.v2, true) XCTAssertNotNil(data.metadata?.nonce) XCTAssertEqual(data.metadata?.upgraded, false) } @@ -360,31 +358,30 @@ final class SapphireTest: XCTestCase { } func testencryption() async throws { - let torus = TorusUtils(enableOneKey: true, network: .sapphire(.SAPPHIRE_MAINNET), clientId: "YOUR_CLIENT_ID") - - let pk = curveSecp256k1.SecretKey() - let pk_str = try pk.serialize() - - let msg = "hello test data" - let encryptData = try torus.encrypt(publicKey: pk.toPublic().serialize(compressed: false), msg: msg) -// let curveMsg = try Encryption.encrypt(pk: pk.toPublic(), data: msg.data(using: .utf8)!) - -// let em = try EncryptedMessage(cipherText: encryptData.ciphertext, ephemeralPublicKey: PublicKey(hex: encryptData.ephemPublicKey) , iv: encryptData.iv, mac: encryptData.mac) - - - let eciesData = ECIES(iv: encryptData.iv, ephemPublicKey: encryptData.ephemPublicKey, ciphertext: encryptData.ciphertext, mac: encryptData.mac) -// let emp = try curveMsg.ephemeralPublicKey().serialize(compressed: false); -// let eciesData2 = try ECIES(iv: curveMsg.iv(), ephemPublicKey: emp, ciphertext: curveMsg.chipherText(), mac: curveMsg.mac()) - - let decrypteData = try torus.decrypt(privateKey: pk_str, opts: eciesData) -// let decrypteData2 = try torus.decrypt(privateKey: pk_str, opts: eciesData2) - -// let result = try Encryption.decrypt(sk: pk, encrypted: em) -// let result2 = try Encryption.decrypt(sk: pk, encrypted: curveMsg) - - XCTAssertEqual(msg.data(using: .utf8)!, decrypteData) -// XCTAssertEqual(msg.data(using: .utf8)!, result2) + let torus = TorusUtils(enableOneKey: true, network: .sapphire(.SAPPHIRE_MAINNET), clientId: "YOUR_CLIENT_ID") - } + let pk = curveSecp256k1.SecretKey() + let pk_str = try pk.serialize() + + let msg = "hello test data" + let encryptData = try torus.encrypt(publicKey: pk.toPublic().serialize(compressed: false), msg: msg) + + let curveMsg = try Encryption.encrypt(pk: pk.toPublic(), plainText: msg.data(using: .utf8)!) + let em = try EncryptedMessage(cipherText: encryptData.ciphertext, ephemeralPublicKey: PublicKey(hex: encryptData.ephemPublicKey) , iv: encryptData.iv, mac: encryptData.mac) + + let eciesData = ECIES(iv: encryptData.iv, ephemPublicKey: encryptData.ephemPublicKey, ciphertext: encryptData.ciphertext, mac: encryptData.mac) + let emp = try curveMsg.ephemeralPublicKey().serialize(compressed: false); + let eciesData2 = try ECIES(iv: curveMsg.iv(), ephemPublicKey: emp, ciphertext: curveMsg.chipherText(), mac: curveMsg.mac()) + + _ = try torus.decrypt(privateKey: pk_str, opts: eciesData) + _ = try torus.decrypt(privateKey: pk_str, opts: eciesData2) + + let result = try Encryption.decrypt(sk: pk, encrypted: em) + let result2 = try Encryption.decrypt(sk: pk, encrypted: curveMsg) + + XCTAssertEqual(msg.data(using: .utf8)!, result) + XCTAssertEqual(msg.data(using: .utf8)!, result2) + + } } diff --git a/Tests/TorusUtilsTests/TestnetTest.swift b/Tests/TorusUtilsTests/TestnetTest.swift index 4b22da02..5d318ea7 100644 --- a/Tests/TorusUtilsTests/TestnetTest.swift +++ b/Tests/TorusUtilsTests/TestnetTest.swift @@ -105,7 +105,7 @@ class TestnetTest: XCTestCase { let verifierID: String = TORUS_TEST_EMAIL let verifierParams = VerifierParams(verifier_id: verifierID) let jwt = try! generateIdToken(email: TORUS_TEST_EMAIL) - let hashedIDToken = jwt.sha3(.keccak256) + let hashedIDToken = keccak256Data(jwt.data(using: .utf8) ?? Data() ).toHexString() let extraParams = ["verifier_id": TORUS_TEST_EMAIL, "sub_verifier_ids": [TORUS_TEST_VERIFIER], "verify_params": [["verifier_id": TORUS_TEST_EMAIL, "idtoken": jwt]]] as [String: Codable] let nodeDetails = try await getFNDAndTUData(verifer: verifier, veriferID: verifierID) let data = try await tu.retrieveShares(endpoints: nodeDetails.getTorusNodeEndpoints(), torusNodePubs: nodeDetails.getTorusNodePub(), indexes: nodeDetails.getTorusIndexes(), verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken, extraParams: extraParams) diff --git a/Tests/TorusUtilsTests/oneKeyTest.swift b/Tests/TorusUtilsTests/oneKeyTest.swift index b8c99234..7df55ed5 100644 --- a/Tests/TorusUtilsTests/oneKeyTest.swift +++ b/Tests/TorusUtilsTests/oneKeyTest.swift @@ -68,7 +68,7 @@ class OneKeyTest: XCTestCase { let verifierID: String = TORUS_TEST_EMAIL let jwt = try! generateIdToken(email: TORUS_TEST_EMAIL) let verifierParams = VerifierParams(verifier_id: verifierID) - let hashedIDToken = jwt.sha3(.keccak256) + let hashedIDToken = keccak256Data( jwt.data(using: .utf8) ?? Data() ).toHexString() let extraParams = ["verifier_id": TORUS_TEST_EMAIL, "sub_verifier_ids": [TORUS_TEST_VERIFIER], "verify_params": [["verifier_id": TORUS_TEST_EMAIL, "idtoken": jwt]]] as [String: Codable] let nodeDetails = try await getFNDAndTUData(verifer: verifier, veriferID: verifierID) let data = try await tu.retrieveShares(endpoints: nodeDetails.getTorusNodeEndpoints(), torusNodePubs: nodeDetails.getTorusNodePub(), indexes: nodeDetails.getTorusIndexes(), verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken, extraParams: extraParams)