From 390e927e34d8ac6bcb8d4d7d7723b166d0e310dc Mon Sep 17 00:00:00 2001 From: ieow Date: Fri, 5 Apr 2024 14:44:06 +0800 Subject: [PATCH 1/8] fix: encryption --- Package.swift | 5 +- .../Extensions/TorusUtils+extension.swift | 53 +++++++++---------- .../Models/RetrieveSharesResponseModel.swift | 4 +- Sources/TorusUtils/TorusUtils.swift | 4 +- Tests/TorusUtilsTests/SapphireTest.swift | 31 ++++++++++- 5 files changed, 65 insertions(+), 32 deletions(-) diff --git a/Package.swift b/Package.swift index 70975ef7..776efc9d 100644 --- a/Package.swift +++ b/Package.swift @@ -24,7 +24,10 @@ let package = Package( targets: [ .target( name: "TorusUtils", - dependencies: ["FetchNodeDetails", "CryptoSwift", "AnyCodable", .product(name: "curveSecp256k1", package: "curvelib.swift")]), + dependencies: ["FetchNodeDetails", "CryptoSwift", "AnyCodable", + .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")] diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 507c5a3c..4f9bb4c4 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -9,6 +9,7 @@ import CommonSources import CryptoKit import FetchNodeDetails import OSLog +import encryption_aes_cbc_sha512 extension TorusUtils { // MARK: - utils @@ -684,24 +685,27 @@ 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: ephemPublicKey, 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() ?? "") + let curveMsg = try Encryption.encrypt(pk: PublicKey(hex: publicKey), plainText: msg) + return try .init(iv: curveMsg.iv(), ephemPublicKey: curveMsg.ephemeralPublicKey().serialize(compressed: false), ciphertext: curveMsg.chipherText(), mac: curveMsg.mac()) + +// let ephemPrivateKey = SecretKey() +// let ephemPublicKey = try ephemPrivateKey.toPublic() +// +// let sharedSecret = try ecdh_sha512(publicKey: ephemPublicKey, 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() ?? "") } // MARK: - decrypt shares @@ -1348,15 +1352,10 @@ extension TorusUtils { } 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) + 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) + let data = result.data(using: .utf8) ?? Data() return data } } 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..f7d1628a 100644 --- a/Sources/TorusUtils/TorusUtils.swift +++ b/Sources/TorusUtils/TorusUtils.swift @@ -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/SapphireTest.swift b/Tests/TorusUtilsTests/SapphireTest.swift index 55474525..2d7f33c3 100644 --- a/Tests/TorusUtilsTests/SapphireTest.swift +++ b/Tests/TorusUtilsTests/SapphireTest.swift @@ -2,7 +2,8 @@ import BigInt import FetchNodeDetails import JWTKit import XCTest - +import curveSecp256k1 +import encryption_aes_cbc_sha512 import CommonSources @testable import TorusUtils @@ -356,5 +357,33 @@ 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(), plainText: msg) + 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) + +// print( result ) + print(String(data: decrypteData, encoding: .utf8)) + print(String(data: decrypteData2, encoding: .utf8)) + + } } From d88c724ed8ba43305f981e80aef7a872373867b4 Mon Sep 17 00:00:00 2001 From: ieow Date: Fri, 5 Apr 2024 18:09:31 +0800 Subject: [PATCH 2/8] fix: support non-utf8 data decryption --- Package.resolved | 132 +++++++++--------- Package.swift | 4 +- .../Extensions/TorusUtils+extension.swift | 27 +--- Tests/TorusUtilsTests/SapphireTest.swift | 7 +- 4 files changed, 75 insertions(+), 95 deletions(-) diff --git a/Package.resolved b/Package.resolved index 058df121..2e02f6f6 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,70 +1,68 @@ { - "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.git", - "state": { - "branch": null, - "revision": "32f641cf24fc7abc1c591a2025e9f2f572648b0f", - "version": "1.7.2" - } - }, - { - "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.git", - "state": { - "branch": null, - "revision": "9e929d925434b91857661bcd455d1bd53f00bf22", - "version": "4.13.0" - } - }, - { - "package": "swift-crypto", - "repositoryURL": "https://github.com/apple/swift-crypto.git", - "state": { - "branch": null, - "revision": "60f13f60c4d093691934dc6cfdf5f508ada1f894", - "version": "2.6.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" : "cryptoswift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/krzyzanowskim/CryptoSwift", + "state" : { + "revision" : "7892a123f7e8d0fe62f9f03728b17bbd4f94df5c", + "version" : "1.8.1" + } + }, + { + "identity" : "curvelib.swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/tkey/curvelib.swift", + "state" : { + "branch" : "feat/cocoapod", + "revision" : "3f1cce96e760c77930f00e79adab2437f3014a3c" + } + }, + { + "identity" : "fetch-node-details-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/torusresearch/fetch-node-details-swift.git", + "state" : { + "revision" : "d591af500f32ce3c88d04af9bb74d746585acfea", + "version" : "5.1.0" + } + }, + { + "identity" : "jwt-kit", + "kind" : "remoteSourceControl", + "location" : "https://github.com/vapor/jwt-kit", + "state" : { + "revision" : "e05513b5aec24f88012b6e3034115b6bc915356a", + "version" : "4.13.2" + } + }, + { + "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 776efc9d..ef30840b 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,7 +11,7 @@ let package = Package( targets: ["TorusUtils"]) ], dependencies: [ - .package(name: "curvelib.swift", url: "https://github.com/tkey/curvelib.swift", from: "0.1.2"), + .package(url: "https://github.com/tkey/curvelib.swift", branch: "feat/cocoapod"), .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"), diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 4f9bb4c4..b598e233 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -685,27 +685,11 @@ extension TorusUtils { } public func encrypt(publicKey: String, msg: String, opts: Ecies? = nil) throws -> Ecies { - let curveMsg = try Encryption.encrypt(pk: PublicKey(hex: publicKey), plainText: msg) + guard let data = msg.data(using: .utf8) else { + throw TorusUtilError.runtime("Encryption: Invalid utf8 string") + } + let curveMsg = try Encryption.encrypt(pk: PublicKey(hex: publicKey), data: data) return try .init(iv: curveMsg.iv(), ephemPublicKey: curveMsg.ephemeralPublicKey().serialize(compressed: false), ciphertext: curveMsg.chipherText(), mac: curveMsg.mac()) - -// let ephemPrivateKey = SecretKey() -// let ephemPublicKey = try ephemPrivateKey.toPublic() -// -// let sharedSecret = try ecdh_sha512(publicKey: ephemPublicKey, 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() ?? "") } // MARK: - decrypt shares @@ -1355,8 +1339,7 @@ extension TorusUtils { 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) - let data = result.data(using: .utf8) ?? Data() - return data + return result } } diff --git a/Tests/TorusUtilsTests/SapphireTest.swift b/Tests/TorusUtilsTests/SapphireTest.swift index 2d7f33c3..e5464ec6 100644 --- a/Tests/TorusUtilsTests/SapphireTest.swift +++ b/Tests/TorusUtilsTests/SapphireTest.swift @@ -367,7 +367,7 @@ final class SapphireTest: XCTestCase { 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) + 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) @@ -380,9 +380,8 @@ final class SapphireTest: XCTestCase { let result = try Encryption.decrypt(sk: pk, encrypted: em) let result2 = try Encryption.decrypt(sk: pk, encrypted: curveMsg) -// print( result ) - print(String(data: decrypteData, encoding: .utf8)) - print(String(data: decrypteData2, encoding: .utf8)) + XCTAssertEqual(msg.data(using: .utf8)!, result) + XCTAssertEqual(msg.data(using: .utf8)!, result2) } From f0bc69a27c2c4b3e787ab8523778fd11395b90ef Mon Sep 17 00:00:00 2001 From: ieow Date: Tue, 16 Apr 2024 14:11:26 +0800 Subject: [PATCH 3/8] feat: remove cryptoSwift --- Package.resolved | 21 ++--- Package.swift | 14 ++-- Sources/TorusUtils/AbstractTorusUtils.swift | 3 +- .../Extensions/Array+Extension.swift | 82 +++++++++++++++++++ .../Extensions/Data+Extension.swift | 14 +++- .../Extensions/String+Extension.swift | 7 +- .../Extensions/TorusUtils+extension.swift | 40 +++------ Sources/TorusUtils/Helpers/Common.swift | 9 +- Sources/TorusUtils/TorusUtils.swift | 3 +- Tests/TorusUtilsTests/AquaTest.swift | 9 +- Tests/TorusUtilsTests/CyanTest.swift | 8 +- Tests/TorusUtilsTests/MainnetTest.swift | 2 +- Tests/TorusUtilsTests/SapphireTest.swift | 4 +- Tests/TorusUtilsTests/TestnetTest.swift | 2 +- Tests/TorusUtilsTests/oneKeyTest.swift | 2 +- 15 files changed, 150 insertions(+), 70 deletions(-) create mode 100644 Sources/TorusUtils/Extensions/Array+Extension.swift diff --git a/Package.resolved b/Package.resolved index 2e02f6f6..b097bd90 100644 --- a/Package.resolved +++ b/Package.resolved @@ -18,31 +18,22 @@ "version" : "5.3.0" } }, - { - "identity" : "cryptoswift", - "kind" : "remoteSourceControl", - "location" : "https://github.com/krzyzanowskim/CryptoSwift", - "state" : { - "revision" : "7892a123f7e8d0fe62f9f03728b17bbd4f94df5c", - "version" : "1.8.1" - } - }, { "identity" : "curvelib.swift", "kind" : "remoteSourceControl", "location" : "https://github.com/tkey/curvelib.swift", "state" : { "branch" : "feat/cocoapod", - "revision" : "3f1cce96e760c77930f00e79adab2437f3014a3c" + "revision" : "282343f23790dcdf189d844eb65c485bbad3eb73" } }, { "identity" : "fetch-node-details-swift", "kind" : "remoteSourceControl", - "location" : "https://github.com/torusresearch/fetch-node-details-swift.git", + "location" : "https://github.com/torusresearch/fetch-node-details-swift", "state" : { - "revision" : "d591af500f32ce3c88d04af9bb74d746585acfea", - "version" : "5.1.0" + "branch" : "feat/commonSources", + "revision" : "8eb9018e35b3e97915d12887f226a58c013693f2" } }, { @@ -50,8 +41,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/vapor/jwt-kit", "state" : { - "revision" : "e05513b5aec24f88012b6e3034115b6bc915356a", - "version" : "4.13.2" + "revision" : "c2595b9ad7f512d7f334830b4df1fed6e917946a", + "version" : "4.13.4" } }, { diff --git a/Package.swift b/Package.swift index ef30840b..3e811848 100644 --- a/Package.swift +++ b/Package.swift @@ -12,9 +12,8 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/tkey/curvelib.swift", branch: "feat/cocoapod"), - .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(name:"FetchNodeDetails", url: "https://github.com/torusresearch/fetch-node-details-swift", branch: "feat/commonSources"), + .package(url: "https://github.com/vapor/jwt-kit", from: "4.0.0"), .package( name:"AnyCodable", url: "https://github.com/Flight-School/AnyCodable", @@ -24,15 +23,16 @@ let package = Package( targets: [ .target( name: "TorusUtils", - dependencies: ["FetchNodeDetails", "CryptoSwift", "AnyCodable", + dependencies: ["AnyCodable", "FetchNodeDetails", +// .product(name: "FetchNodeDetails", package: "FetchNodeDetails"), .product(name: "curveSecp256k1", package: "curvelib.swift"), - .product(name: "encryption_aes_cbc_sha512", package: "curvelib.swift") + .product(name: "encryption_aes_cbc_sha512", package: "curvelib.swift"), + .product(name: "curvelibSha3", 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..a304178c 100755 --- a/Sources/TorusUtils/Extensions/Data+Extension.swift +++ b/Sources/TorusUtils/Extensions/Data+Extension.swift @@ -1,5 +1,5 @@ import Foundation - +//import CryptoSwift public extension Data { var hexString: String { return map { String(format: "%02x", $0) }.joined() @@ -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..1148863d 100755 --- a/Sources/TorusUtils/Extensions/String+Extension.swift +++ b/Sources/TorusUtils/Extensions/String+Extension.swift @@ -55,10 +55,13 @@ 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() + + //Array(lowerCaseAddress.sha3(.keccak256)) 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 b598e233..3c86db5c 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 @@ -11,14 +10,9 @@ import FetchNodeDetails import OSLog import encryption_aes_cbc_sha512 + 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 { @@ -246,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]() @@ -654,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, @@ -662,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 } @@ -700,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 } @@ -1335,7 +1319,7 @@ extension TorusUtils { return tupleElements } - public func decrypt(privateKey: String, opts: ECIES, padding: Padding = .pkcs7) throws -> 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) diff --git a/Sources/TorusUtils/Helpers/Common.swift b/Sources/TorusUtils/Helpers/Common.swift index 5e872761..23d3172b 100644 --- a/Sources/TorusUtils/Helpers/Common.swift +++ b/Sources/TorusUtils/Helpers/Common.swift @@ -1,14 +1,19 @@ import BigInt import Foundation +//import CryptoSwift + +import curvelibSha3 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 = publicKeyData.sha3(.keccak256).suffix(20) + let ethAddrData = try keccak256Data(publicKeyData).suffix(20) let ethAddrlower = ethAddrData.toHexString().addHexPrefix() return ethAddrlower.toChecksumAddress() } diff --git a/Sources/TorusUtils/TorusUtils.swift b/Sources/TorusUtils/TorusUtils.swift index f7d1628a..aba322e0 100644 --- a/Sources/TorusUtils/TorusUtils.swift +++ b/Sources/TorusUtils/TorusUtils.swift @@ -247,8 +247,9 @@ 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() +// let hashedToken = idToken.sha3(.keccak256) var lookupPubkeyX: String = "" var lookupPubkeyY: String = "" do { 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 9ca4fe99..763c2e87 100644 --- a/Tests/TorusUtilsTests/SapphireTest.swift +++ b/Tests/TorusUtilsTests/SapphireTest.swift @@ -300,7 +300,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)) @@ -314,7 +314,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) } 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) From 423a56f52d2b1aa60730c6c4e2c87b67cc8a4d05 Mon Sep 17 00:00:00 2001 From: ieow Date: Tue, 16 Apr 2024 14:32:49 +0800 Subject: [PATCH 4/8] fix: update package.swift --- Package.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Package.swift b/Package.swift index 3e811848..a431e0ed 100644 --- a/Package.swift +++ b/Package.swift @@ -13,7 +13,7 @@ let package = Package( dependencies: [ .package(url: "https://github.com/tkey/curvelib.swift", branch: "feat/cocoapod"), .package(name:"FetchNodeDetails", url: "https://github.com/torusresearch/fetch-node-details-swift", branch: "feat/commonSources"), - .package(url: "https://github.com/vapor/jwt-kit", from: "4.0.0"), + .package(name:"jwt-kit", url: "https://github.com/vapor/jwt-kit", from: "4.0.0"), .package( name:"AnyCodable", url: "https://github.com/Flight-School/AnyCodable", @@ -24,7 +24,6 @@ let package = Package( .target( name: "TorusUtils", dependencies: ["AnyCodable", "FetchNodeDetails", -// .product(name: "FetchNodeDetails", package: "FetchNodeDetails"), .product(name: "curveSecp256k1", package: "curvelib.swift"), .product(name: "encryption_aes_cbc_sha512", package: "curvelib.swift"), .product(name: "curvelibSha3", package: "curvelib.swift") From 9082e322fb886381fea8b4e885603826e605b23a Mon Sep 17 00:00:00 2001 From: ieow Date: Tue, 16 Apr 2024 16:37:27 +0800 Subject: [PATCH 5/8] fix: update packages --- Package.resolved | 4 ++-- Package.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Package.resolved b/Package.resolved index b097bd90..27b6240f 100644 --- a/Package.resolved +++ b/Package.resolved @@ -32,8 +32,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/torusresearch/fetch-node-details-swift", "state" : { - "branch" : "feat/commonSources", - "revision" : "8eb9018e35b3e97915d12887f226a58c013693f2" + "revision" : "bf2f0759da5c5c80765773b08c2756045edf608f", + "version" : "5.2.0" } }, { diff --git a/Package.swift b/Package.swift index a431e0ed..a86b7849 100644 --- a/Package.swift +++ b/Package.swift @@ -12,7 +12,7 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/tkey/curvelib.swift", branch: "feat/cocoapod"), - .package(name:"FetchNodeDetails", url: "https://github.com/torusresearch/fetch-node-details-swift", branch: "feat/commonSources"), + .package(name:"FetchNodeDetails", url: "https://github.com/torusresearch/fetch-node-details-swift", from: "5.2.0"), .package(name:"jwt-kit", url: "https://github.com/vapor/jwt-kit", from: "4.0.0"), .package( name:"AnyCodable", From 8ea9262af6a83e44301542c511dbafaba076c152 Mon Sep 17 00:00:00 2001 From: ieow Date: Tue, 16 Apr 2024 19:04:29 +0800 Subject: [PATCH 6/8] fix: update curvelib --- Package.resolved | 4 ++-- Package.swift | 4 +--- .../TorusUtils/Extensions/TorusUtils+extension.swift | 4 ++-- Sources/TorusUtils/Helpers/Common.swift | 2 +- Tests/TorusUtilsTests/SapphireTest.swift | 11 ++++------- 5 files changed, 10 insertions(+), 15 deletions(-) diff --git a/Package.resolved b/Package.resolved index 27b6240f..5c722eef 100644 --- a/Package.resolved +++ b/Package.resolved @@ -23,8 +23,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/tkey/curvelib.swift", "state" : { - "branch" : "feat/cocoapod", - "revision" : "282343f23790dcdf189d844eb65c485bbad3eb73" + "revision" : "2df9f638fd121b445ce3b410cd79ac4d0cfa94ed", + "version" : "1.0.0" } }, { diff --git a/Package.swift b/Package.swift index a86b7849..8bdd9034 100644 --- a/Package.swift +++ b/Package.swift @@ -11,7 +11,7 @@ let package = Package( targets: ["TorusUtils"]) ], dependencies: [ - .package(url: "https://github.com/tkey/curvelib.swift", branch: "feat/cocoapod"), + .package(url: "https://github.com/tkey/curvelib.swift", from: "1.0.0"), .package(name:"FetchNodeDetails", url: "https://github.com/torusresearch/fetch-node-details-swift", from: "5.2.0"), .package(name:"jwt-kit", url: "https://github.com/vapor/jwt-kit", from: "4.0.0"), .package( @@ -25,8 +25,6 @@ let package = Package( name: "TorusUtils", dependencies: ["AnyCodable", "FetchNodeDetails", .product(name: "curveSecp256k1", package: "curvelib.swift"), - .product(name: "encryption_aes_cbc_sha512", package: "curvelib.swift"), - .product(name: "curvelibSha3", package: "curvelib.swift") ]), .testTarget( name: "TorusUtilsTests", diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 3c86db5c..333913a5 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -8,7 +8,7 @@ import CommonSources import CryptoKit import FetchNodeDetails import OSLog -import encryption_aes_cbc_sha512 + extension TorusUtils { @@ -683,7 +683,7 @@ extension TorusUtils { guard let data = msg.data(using: .utf8) else { throw TorusUtilError.runtime("Encryption: Invalid utf8 string") } - let curveMsg = try Encryption.encrypt(pk: PublicKey(hex: publicKey), data: data) + 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()) } diff --git a/Sources/TorusUtils/Helpers/Common.swift b/Sources/TorusUtils/Helpers/Common.swift index 23d3172b..30c2b51a 100644 --- a/Sources/TorusUtils/Helpers/Common.swift +++ b/Sources/TorusUtils/Helpers/Common.swift @@ -2,7 +2,7 @@ import BigInt import Foundation //import CryptoSwift -import curvelibSha3 +import curveSecp256k1 func keccak256Data(_ data: Data) -> Data { let hash = try? keccak256(data: data) diff --git a/Tests/TorusUtilsTests/SapphireTest.swift b/Tests/TorusUtilsTests/SapphireTest.swift index 763c2e87..5c155f28 100644 --- a/Tests/TorusUtilsTests/SapphireTest.swift +++ b/Tests/TorusUtilsTests/SapphireTest.swift @@ -3,10 +3,7 @@ import FetchNodeDetails import JWTKit import XCTest import curveSecp256k1 -import encryption_aes_cbc_sha512 import CommonSources -import curveSecp256k1 -import encryption_aes_cbc_sha512 @testable import TorusUtils @@ -124,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) } @@ -188,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) } @@ -291,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) } @@ -369,7 +366,7 @@ final class SapphireTest: XCTestCase { 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 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) From e66764b7044325a7d8008864871544654aaa481d Mon Sep 17 00:00:00 2001 From: metalurgical <97008724+metalurgical@users.noreply.github.com> Date: Wed, 17 Apr 2024 05:27:39 +0200 Subject: [PATCH 7/8] cleanup --- Package.swift | 8 ++++---- Sources/TorusUtils/Extensions/Data+Extension.swift | 2 +- Sources/TorusUtils/Helpers/Common.swift | 4 +--- Tests/TorusUtilsTests/SapphireTest.swift | 4 ++-- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/Package.swift b/Package.swift index 8bdd9034..c0123670 100644 --- a/Package.swift +++ b/Package.swift @@ -12,10 +12,9 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/tkey/curvelib.swift", from: "1.0.0"), - .package(name:"FetchNodeDetails", url: "https://github.com/torusresearch/fetch-node-details-swift", from: "5.2.0"), - .package(name:"jwt-kit", url: "https://github.com/vapor/jwt-kit", from: "4.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" ), @@ -23,7 +22,8 @@ let package = Package( targets: [ .target( name: "TorusUtils", - dependencies: ["AnyCodable", "FetchNodeDetails", + dependencies: ["AnyCodable", + .product(name: "FetchNodeDetails", package: "fetch-node-details-swift"), .product(name: "curveSecp256k1", package: "curvelib.swift"), ]), .testTarget( diff --git a/Sources/TorusUtils/Extensions/Data+Extension.swift b/Sources/TorusUtils/Extensions/Data+Extension.swift index a304178c..5673b055 100755 --- a/Sources/TorusUtils/Extensions/Data+Extension.swift +++ b/Sources/TorusUtils/Extensions/Data+Extension.swift @@ -1,5 +1,5 @@ import Foundation -//import CryptoSwift + public extension Data { var hexString: String { return map { String(format: "%02x", $0) }.joined() diff --git a/Sources/TorusUtils/Helpers/Common.swift b/Sources/TorusUtils/Helpers/Common.swift index 30c2b51a..bcb548d4 100644 --- a/Sources/TorusUtils/Helpers/Common.swift +++ b/Sources/TorusUtils/Helpers/Common.swift @@ -1,6 +1,5 @@ import BigInt import Foundation -//import CryptoSwift import curveSecp256k1 @@ -12,8 +11,7 @@ func keccak256Data(_ data: Data) -> 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 = try keccak256Data(publicKeyData).suffix(20) + let ethAddrData = keccak256Data(publicKeyData).suffix(20) let ethAddrlower = ethAddrData.toHexString().addHexPrefix() return ethAddrlower.toChecksumAddress() } diff --git a/Tests/TorusUtilsTests/SapphireTest.swift b/Tests/TorusUtilsTests/SapphireTest.swift index 5c155f28..e8e6325a 100644 --- a/Tests/TorusUtilsTests/SapphireTest.swift +++ b/Tests/TorusUtilsTests/SapphireTest.swift @@ -373,8 +373,8 @@ final class SapphireTest: XCTestCase { 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) + _ = 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) From 017cb4d37915fc1c9715c6f7d1aff87521fbb36b Mon Sep 17 00:00:00 2001 From: metalurgical <97008724+metalurgical@users.noreply.github.com> Date: Wed, 17 Apr 2024 05:40:03 +0200 Subject: [PATCH 8/8] cleanup --- Sources/TorusUtils/Extensions/String+Extension.swift | 1 - Sources/TorusUtils/TorusUtils.swift | 1 - 2 files changed, 2 deletions(-) diff --git a/Sources/TorusUtils/Extensions/String+Extension.swift b/Sources/TorusUtils/Extensions/String+Extension.swift index 1148863d..33c2f082 100755 --- a/Sources/TorusUtils/Extensions/String+Extension.swift +++ b/Sources/TorusUtils/Extensions/String+Extension.swift @@ -57,7 +57,6 @@ extension String { let arr = Array(lowerCaseAddress) let hash = keccak256Data(lowerCaseAddress.data(using: .utf8) ?? Data() ).toHexString() - //Array(lowerCaseAddress.sha3(.keccak256)) var result = String() for i in 0 ... lowerCaseAddress.count - 1 { let iIndex = hash.index(hash.startIndex, offsetBy: i) diff --git a/Sources/TorusUtils/TorusUtils.swift b/Sources/TorusUtils/TorusUtils.swift index aba322e0..06ba7d2c 100644 --- a/Sources/TorusUtils/TorusUtils.swift +++ b/Sources/TorusUtils/TorusUtils.swift @@ -249,7 +249,6 @@ open class TorusUtils: AbstractTorusUtils { let timestamp = String(Int(getTimestamp())) let hashedToken = keccak256Data(idToken.data(using: .utf8) ?? Data()).toHexString() -// let hashedToken = idToken.sha3(.keccak256) var lookupPubkeyX: String = "" var lookupPubkeyY: String = "" do {