From 0382ed19664276967c90cdb58ce6105bb0999ba0 Mon Sep 17 00:00:00 2001 From: himanshu Date: Mon, 28 Aug 2023 18:52:57 +0800 Subject: [PATCH 01/11] fix legacy new users login --- .../Extensions/TorusUtils+extension.swift | 12 ++++- .../Interfaces/ShareRequestResult.swift | 6 ++- Sources/TorusUtils/TorusUtils.swift | 18 ++++--- Tests/TorusUtilsTests/SapphireTest.swift | 48 +++++++++++++++++++ 4 files changed, 71 insertions(+), 13 deletions(-) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index a6526d55..65929925 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -278,6 +278,7 @@ extension TorusUtils { var thresholdNonceData : GetOrSetNonceResult? var pubkeyArr = [KeyAssignment.PublicKey]() + var isNewKeyArr: [String] = [] var completeShareRequestResponseArr = [ShareRequestResult]() var thresholdPublicKey : KeyAssignment.PublicKey? @@ -314,6 +315,7 @@ extension TorusUtils { let decodedResult = decoded.result as? ShareRequestResult else { throw TorusUtilError.decodingFailed("ShareReqeust error decoding error : \(decoded), can't decode into shareRequestResult") } + isNewKeyArr.append(decodedResult.isNewKey) completeShareRequestResponseArr.append(decodedResult) let keyObj = decodedResult.keys if let first = keyObj.first { @@ -360,6 +362,7 @@ extension TorusUtils { throw TorusUtilError.thresholdError }) + // optimistically run lagrange interpolation once threshold number of shares have been received // this is matched against the user public key to ensure that shares are consistent // Note: no need of thresholdMetadataNonce for extended_verifier_id key @@ -373,6 +376,11 @@ extension TorusUtils { var nodeIndexes = [Int]() var sessionTokenData = [SessionToken?]() + guard let isNewKey = thresholdSame(arr: isNewKeyArr, threshold: threshold) + else { + os_log("retrieveShare - invalid result from nodes, threshold number of is_new_key results are not matching", log: getTorusLogger(log: TorusUtilsLogger.core, type: .error), type: .error) + throw TorusUtilError.thresholdError + } for currentShareResponse in completeShareRequestResponseArr { let sessionTokens = currentShareResponse.sessionTokens @@ -520,8 +528,8 @@ extension TorusUtils { finalPubKey = String(finalPubKey.suffix(128)) } else if case .legacy(_) = self.network { if (self.enableOneKey) { - // get nonce - let nonceResult = try await getOrSetNonce(x: oauthPubKeyX, y: oauthPubKeyY, privateKey: oAuthKey) + // get or set nonce based on isNewKey variable + let nonceResult = try await getOrSetNonce(x: oauthPubKeyX, y: oauthPubKeyY, privateKey: oAuthKey, getOnly: isNewKey == "false") // BigInt( Data(hex: nonceResult.nonce ?? "0")) metadataNonce = BigInt( nonceResult.nonce ?? "0", radix: 16)! let usertype = nonceResult.typeOfUser diff --git a/Sources/TorusUtils/Interfaces/ShareRequestResult.swift b/Sources/TorusUtils/Interfaces/ShareRequestResult.swift index eed40d78..41e0d79b 100644 --- a/Sources/TorusUtils/Interfaces/ShareRequestResult.swift +++ b/Sources/TorusUtils/Interfaces/ShareRequestResult.swift @@ -8,6 +8,7 @@ struct ShareRequestResult : Decodable { let sessionTokenSigMetadata: [EciesHex] let nodePubX: String let nodePubY: String + let isNewKey: String enum CodingKeys: CodingKey { case keys @@ -17,6 +18,7 @@ struct ShareRequestResult : Decodable { case session_token_sig_metadata case node_pubx case node_puby + case is_new_key } init(from decoder: Decoder) throws { @@ -24,7 +26,8 @@ struct ShareRequestResult : Decodable { self.keys = try container.decode([KeyAssignment].self, forKey: .keys) self.nodePubX = try container.decode(String.self, forKey: .node_pubx) self.nodePubY = try container.decode(String.self, forKey: .node_puby) - + self.isNewKey = try container.decode(String.self, forKey: .is_new_key) + if let sessionTokens = try? container.decodeIfPresent([String].self, forKey: .session_tokens) { self.sessionTokens = sessionTokens } else { @@ -48,6 +51,7 @@ struct ShareRequestResult : Decodable { } else { self.sessionTokenSigMetadata = [] } + } // public func encode(to encoder: Encoder) throws { diff --git a/Sources/TorusUtils/TorusUtils.swift b/Sources/TorusUtils/TorusUtils.swift index 954c3cb2..5d58dca0 100644 --- a/Sources/TorusUtils/TorusUtils.swift +++ b/Sources/TorusUtils/TorusUtils.swift @@ -55,10 +55,9 @@ open class TorusUtils: AbstractTorusUtils { // MARK: - getPublicAddress public func getPublicAddress(endpoints: [String], torusNodePubs: [TorusNodePubModel], verifier: String, verifierId: String, extendedVerifierId :String? = nil ) async throws -> TorusPublicKey { - switch network { - case .legacy(_) : + if (self.isLegacyNetwork()) { return try await getLegacyPublicAddress(endpoints: endpoints, torusNodePubs: torusNodePubs , verifier: verifier, verifierId: verifierId, enableOneKey: self.enableOneKey) - case .sapphire(_) : + } else { return try await getNewPublicAddress(endpoints: endpoints, verifier: verifier, verifierId: verifierId, extendedVerifierId: extendedVerifierId, enableOneKey: self.enableOneKey) } } @@ -74,11 +73,10 @@ open class TorusUtils: AbstractTorusUtils { extraParams: [String:Codable] = [:] ) async throws -> TorusKey { - switch network { - case .legacy(_) : + if (self.isLegacyNetwork()) { let result = try await legacyRetrieveShares(torusNodePubs: torusNodePubs, indexes: indexes, endpoints: endpoints, verifier: verifier, verifierId: verifierParams.verifier_id, idToken: idToken, extraParams: extraParams) return result - case .sapphire(_) : + } else { let result = try await retrieveShare( legacyMetadataHost: self.legacyMetadataHost, @@ -101,14 +99,14 @@ open class TorusUtils: AbstractTorusUtils { public func getUserTypeAndAddress(endpoints: [String], torusNodePubs: [TorusNodePubModel], verifier: String, verifierId: String, extendedVerifierId :String? = nil) async throws -> TorusPublicKey { - switch network { - case .legacy(_) : + if (self.isLegacyNetwork()) { return try await getLegacyPublicAddress(endpoints: endpoints, torusNodePubs: torusNodePubs, verifier: verifier, verifierId: verifierId, enableOneKey: true) - case .sapphire(_) : + } + else { return try await getNewPublicAddress(endpoints: endpoints, verifier: verifier, verifierId: verifierId, extendedVerifierId: extendedVerifierId, enableOneKey: true) } - } + } private func getNewPublicAddress(endpoints: [String], verifier: String, verifierId: String, extendedVerifierId :String? = nil, enableOneKey: Bool) async throws -> TorusPublicKey { diff --git a/Tests/TorusUtilsTests/SapphireTest.swift b/Tests/TorusUtilsTests/SapphireTest.swift index 279c5eb0..a180dbbb 100644 --- a/Tests/TorusUtilsTests/SapphireTest.swift +++ b/Tests/TorusUtilsTests/SapphireTest.swift @@ -174,6 +174,54 @@ final class SapphireTest: XCTestCase { } + + func testNewUserLogin() async throws { + let exp1 = XCTestExpectation(description: "Should be able to do a Login") + + let fakeEmail = generateRandomEmail(of: 6) + let verifierId = fakeEmail //faker random address + let token = try generateIdToken(email: verifierId) + + let verifierParams = VerifierParams(verifier_id: verifierId) + + do { + let nodeDetails = try await get_fnd_and_tu_data(verifer: TORUS_TEST_VERIFIER, veriferID: verifierId) + + let data = try await torus.retrieveShares( + endpoints: nodeDetails.getTorusNodeEndpoints(), + torusNodePubs: nodeDetails.getTorusNodePub(), + indexes: nodeDetails.getTorusIndexes(), + verifier: TORUS_TEST_VERIFIER, + verifierParams: verifierParams, + idToken: token + ) + + XCTAssertEqual(data.metadata?.typeOfUser, .v2) + XCTAssertEqual(data.metadata?.upgraded, false) + XCTAssertNotEqual(data.finalKeyData?.evmAddress, "") + XCTAssertNotEqual(data.finalKeyData?.X, "") + XCTAssertNotEqual(data.finalKeyData?.Y, "") + XCTAssertNotEqual(data.finalKeyData?.privKey, "") + XCTAssertNotEqual(data.oAuthKeyData?.evmAddress, "") + XCTAssertNotEqual(data.oAuthKeyData?.X, "") + XCTAssertNotEqual(data.oAuthKeyData?.Y, "") + XCTAssertNotEqual(data.oAuthKeyData?.privKey, "") + XCTAssertNotEqual(data.sessionData?.sessionTokenData.count, 0) + XCTAssertNotEqual(data.sessionData?.sessionAuthKey, "") + XCTAssertNotEqual(data.metadata?.pubNonce?.x, "") + XCTAssertNotEqual(data.metadata?.pubNonce?.y, "") + XCTAssertNotEqual(data.nodesData?.nodeIndexes.count, 0) + + exp1.fulfill() + } catch let error{ + XCTFail(error.localizedDescription) + exp1.fulfill() + } + + + } + + func testNodeDownAbleToLogin () async throws { let exp1 = XCTestExpectation(description: "should be able to login even when node is down") From dbbf43c30497dda5fc3e309da9a3d2b510997202 Mon Sep 17 00:00:00 2001 From: himanshu Date: Thu, 31 Aug 2023 14:42:46 +0800 Subject: [PATCH 02/11] test fixed --- Sources/TorusUtils/TorusUtils.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/TorusUtils/TorusUtils.swift b/Sources/TorusUtils/TorusUtils.swift index 5d58dca0..aa29bdae 100644 --- a/Sources/TorusUtils/TorusUtils.swift +++ b/Sources/TorusUtils/TorusUtils.swift @@ -429,8 +429,8 @@ open class TorusUtils: AbstractTorusUtils { throw TorusUtilError.decodingFailed(decoded.error?.data) } os_log("retrieveDecryptAndReconstuct: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .info), type: .info, "\(decoded)") - var X = lookupPubkeyX - var Y = lookupPubkeyY + var X = lookupPubkeyX.addLeading0sForLength64() + var Y = lookupPubkeyY.addLeading0sForLength64() if let decodedResult = decoded.result as? LegacyLookupResponse { // case non migration let keyObj = decodedResult.keys @@ -475,7 +475,7 @@ open class TorusUtils: AbstractTorusUtils { if filteredData.count < threshold { throw TorusUtilError.thresholdError } - let thresholdLagrangeInterpolationData = try thresholdLagrangeInterpolation(data: filteredData, endpoints: endpoints, lookupPubkeyX: X, lookupPubkeyY: Y) + let thresholdLagrangeInterpolationData = try thresholdLagrangeInterpolation(data: filteredData, endpoints: endpoints, lookupPubkeyX: X.addLeading0sForLength64(), lookupPubkeyY: Y.addLeading0sForLength64()) session.invalidateAndCancel() return thresholdLagrangeInterpolationData case .failure(let error): From ccfd739643bedff517f2692c7f8153a230a9d7eb Mon Sep 17 00:00:00 2001 From: himanshu Date: Thu, 31 Aug 2023 15:54:46 +0800 Subject: [PATCH 03/11] fix lagrange interpolation --- Sources/TorusUtils/Extensions/TorusUtils+extension.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 65929925..5241fdbe 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -495,7 +495,6 @@ extension TorusUtils { let decryptedPubKeyYBigInt = BigUInt(decryptedPubKeyY, radix: 16)! let thresholdPublicKeyXBigInt = BigUInt(thresholdPublicKey?.X ?? "0", radix: 16)! let thresholdPublicKeyYBigInt = BigUInt(thresholdPublicKey?.Y ?? "0", radix: 16)! - returnedKey = derivedPrivateKey if decryptedPubKeyXBigInt == thresholdPublicKeyXBigInt && decryptedPubKeyYBigInt == thresholdPublicKeyYBigInt { returnedKey = derivedPrivateKey break From b858babd4147e1d4d79e0d5d94b32599c8da224a Mon Sep 17 00:00:00 2001 From: himanshu Date: Thu, 31 Aug 2023 18:36:59 +0800 Subject: [PATCH 04/11] fix pub key x derivation --- Sources/TorusUtils/Extensions/TorusUtils+extension.swift | 8 +++++++- Tests/TorusUtilsTests/SapphireTest.swift | 3 ++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 5241fdbe..65ec8e76 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -489,7 +489,7 @@ extension TorusUtils { } let decryptedPubKey = SECP256K1.privateToPublic(privateKey: Data(hex: derivedPrivateKey) )?.toHexString() - let decryptedPubKeyX = String(decryptedPubKey!.prefix(64)) + let decryptedPubKeyX = String(decryptedPubKey!.suffix(128).prefix(64)) let decryptedPubKeyY = String(decryptedPubKey!.suffix(64)) let decryptedPubKeyXBigInt = BigUInt(decryptedPubKeyX, radix: 16)! let decryptedPubKeyYBigInt = BigUInt(decryptedPubKeyY, radix: 16)! @@ -500,10 +500,16 @@ extension TorusUtils { break } } + + guard let oAuthKey = returnedKey else { throw TorusUtilError.privateKeyDeriveFailed } +// let decryptedPubKey = SECP256K1.privateToPublic(privateKey: Data(hex: oAuthKey) )?.toHexString() + +// print("decryptedPubKey", returnedKey, decryptedPubKey, thresholdPublicKey) + let oAuthKeyBigInt = BigInt(oAuthKey , radix: 16)! guard let derivedPrivateKeyData = Data(hexString: oAuthKey) else { diff --git a/Tests/TorusUtilsTests/SapphireTest.swift b/Tests/TorusUtilsTests/SapphireTest.swift index a180dbbb..f7ab8419 100644 --- a/Tests/TorusUtilsTests/SapphireTest.swift +++ b/Tests/TorusUtilsTests/SapphireTest.swift @@ -416,7 +416,8 @@ final class SapphireTest: XCTestCase { func testAggregrateLogin() async throws { let exp1 = XCTestExpectation(description: "Should be able to aggregate login") - let email = generateRandomEmail(of: 6) + let email = "hEJTRg@gmail.com" + print("email", email) let verifier: String = TORUS_TEST_AGGREGATE_VERIFIER let verifierID: String = email let jwt = try! generateIdToken(email: email) From 51eef07de7c92e2f4e6145732ea6a5449506d5d0 Mon Sep 17 00:00:00 2001 From: himanshu Date: Thu, 31 Aug 2023 20:35:43 +0800 Subject: [PATCH 05/11] fix padding issues for decryption --- .../Extensions/TorusUtils+extension.swift | 25 +++++++------------ 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 65ec8e76..21286eaf 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -178,7 +178,7 @@ extension TorusUtils { private func getShareOrKeyAssign(endpoints: [String], nodeSigs: [CommitmentRequestResponse], verifier: String, verifierParams: VerifierParams, idToken: String, extraParams: [String: Any] = [:]) async throws -> [URLRequest] { let session = createURLSession() - let threshold = Int(endpoints.count / 2) + 1 + let threshold = Int(endpoints.count / 2) + 1 var rpcdata: Data = Data() let loadedStrings = extraParams @@ -416,8 +416,8 @@ extension TorusUtils { let data = Data(base64Encoded: latestKey.share, options: [] )! let binaryString = String(data: data, encoding: .ascii) ?? "" let paddedBinaryString = binaryString.padding(toLength: 64, withPad: "0", startingAt: 0) - - sharePromises.append(try decryptNodeData(eciesData: latestKey.shareMetadata, ciphertextHex: paddedBinaryString, privKey: sessionAuthKey).padLeft(padChar: "0", count: 64)) + let decryptedShare = try decryptNodeData(eciesData: latestKey.shareMetadata, ciphertextHex: paddedBinaryString, privKey: sessionAuthKey).addLeading0sForLength64() + sharePromises.append(decryptedShare) } else { os_log("retrieveShare - 0 keys returned from nodes", log: getTorusLogger(log: TorusUtilsLogger.core, type: .error), type: .error) @@ -470,7 +470,7 @@ extension TorusUtils { } // run lagrange interpolation on all subsets, faster in the optimistic scenario than berlekamp-welch due to early exit - let allCombis = kCombinations(s: decryptedShares.count, k: threshold) + let allCombis = kCombinations(s: decryptedShares.count, k: 3) var returnedKey: String? = nil for j in 0.. Date: Thu, 31 Aug 2023 20:36:14 +0800 Subject: [PATCH 06/11] test fixe --- Tests/TorusUtilsTests/SapphireTest.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/TorusUtilsTests/SapphireTest.swift b/Tests/TorusUtilsTests/SapphireTest.swift index f7ab8419..d33ffd96 100644 --- a/Tests/TorusUtilsTests/SapphireTest.swift +++ b/Tests/TorusUtilsTests/SapphireTest.swift @@ -416,7 +416,7 @@ final class SapphireTest: XCTestCase { func testAggregrateLogin() async throws { let exp1 = XCTestExpectation(description: "Should be able to aggregate login") - let email = "hEJTRg@gmail.com" + let email = generateRandomEmail(of: 6) print("email", email) let verifier: String = TORUS_TEST_AGGREGATE_VERIFIER let verifierID: String = email From b2150a924f8d068d31693b06490fdc501b3a623c Mon Sep 17 00:00:00 2001 From: himanshu Date: Thu, 31 Aug 2023 20:54:18 +0800 Subject: [PATCH 07/11] revert to pkcs7 --- Sources/TorusUtils/Extensions/TorusUtils+extension.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 21286eaf..0ef4133d 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -782,7 +782,7 @@ extension TorusUtils { let macKey = Array(hash.suffix(32)) do { // AES-CBCblock-256 - let aes = try AES(key: encryptionKey, blockMode: CBC(iv: iv), padding: .zeroPadding) + let aes = try AES(key: encryptionKey, blockMode: CBC(iv: iv), padding: .pkcs7) let encrypt = try aes.encrypt(msg.customBytes()) let data = Data(encrypt) @@ -840,7 +840,7 @@ extension TorusUtils { do { // AES-CBCblock-256 - let aes = try AES(key: AesEncryptionKey.hexa, blockMode: CBC(iv: iv), padding: .zeroPadding) + let aes = try AES(key: AesEncryptionKey.hexa, blockMode: CBC(iv: iv), padding: .pkcs7) let decrypt = try aes.decrypt(share) result[nodeIndex] = decrypt.hexa } catch let err { @@ -1544,7 +1544,7 @@ extension TorusUtils { let aesEncryptionKey = hash.prefix(64) do { // AES-CBCblock-256 - let aes = try AES(key: aesEncryptionKey.hexa, blockMode: CBC(iv: iv), padding: .zeroPadding) + let aes = try AES(key: aesEncryptionKey.hexa, blockMode: CBC(iv: iv), padding: .pkcs7) let decrypt = try aes.decrypt(opts.ciphertext.hexa) let data = Data(decrypt) return data From 372b4c9eaaf13dac50cd56b65367d53228d8465e Mon Sep 17 00:00:00 2001 From: ieow Date: Thu, 31 Aug 2023 21:18:20 +0800 Subject: [PATCH 08/11] fix: fallback decrypt --- .../Extensions/TorusUtils+extension.swift | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 0ef4133d..64a235c0 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -416,7 +416,10 @@ extension TorusUtils { let data = Data(base64Encoded: latestKey.share, options: [] )! let binaryString = String(data: data, encoding: .ascii) ?? "" let paddedBinaryString = binaryString.padding(toLength: 64, withPad: "0", startingAt: 0) - let decryptedShare = try decryptNodeData(eciesData: latestKey.shareMetadata, ciphertextHex: paddedBinaryString, privKey: sessionAuthKey).addLeading0sForLength64() + var decryptedShare = try decryptNodeData(eciesData: latestKey.shareMetadata, ciphertextHex: paddedBinaryString, privKey: sessionAuthKey) + if ( decryptedShare.count < 64 ) { + decryptedShare = try decryptNodeData(eciesData: latestKey.shareMetadata, ciphertextHex: paddedBinaryString, privKey: sessionAuthKey, padding: .zeroPadding).addLeading0sForLength64() + } sharePromises.append(decryptedShare) } else { @@ -729,7 +732,7 @@ extension TorusUtils { return BigUInt(message, radix: 16)! } - internal func decryptNodeData(eciesData: EciesHex, ciphertextHex: String, privKey: String) throws -> String { + internal func decryptNodeData(eciesData: EciesHex, ciphertextHex: String, privKey: String, padding: Padding = .pkcs7) throws -> String { let eciesOpts = ECIES( iv: eciesData.iv, @@ -738,7 +741,7 @@ extension TorusUtils { mac: eciesData.mac ) - let decryptedSigBuffer = try decrypt(privateKey: privKey, opts: eciesOpts).toHexString() + let decryptedSigBuffer = try decrypt(privateKey: privKey, opts: eciesOpts, padding: padding).toHexString() return decryptedSigBuffer } @@ -841,8 +844,8 @@ extension TorusUtils { do { // AES-CBCblock-256 let aes = try AES(key: AesEncryptionKey.hexa, blockMode: CBC(iv: iv), padding: .pkcs7) - let decrypt = try aes.decrypt(share) - result[nodeIndex] = decrypt.hexa + let decryptData = try aes.decrypt(share) + result[nodeIndex] = decryptData.hexa } catch let err { result[nodeIndex] = TorusUtilError.decodingFailed(err.localizedDescription).debugDescription } @@ -1519,7 +1522,7 @@ extension TorusUtils { return tupleElements } - public func decrypt(privateKey: String, opts: ECIES) throws -> Data { + public func decrypt(privateKey: String, opts: ECIES, padding: Padding = .pkcs7) throws -> Data { let ephermalPublicKey = opts.ephemPublicKey.strip04Prefix() let ephermalPublicKeyBytes = ephermalPublicKey.hexa var ephermOne = ephermalPublicKeyBytes.prefix(32) @@ -1544,9 +1547,9 @@ extension TorusUtils { let aesEncryptionKey = hash.prefix(64) do { // AES-CBCblock-256 - let aes = try AES(key: aesEncryptionKey.hexa, blockMode: CBC(iv: iv), padding: .pkcs7) - let decrypt = try aes.decrypt(opts.ciphertext.hexa) - let data = Data(decrypt) + let aes = try AES(key: aesEncryptionKey.hexa, blockMode: CBC(iv: iv), padding: padding) + let decryptData = try aes.decrypt(opts.ciphertext.hexa) + let data = Data(decryptData) return data From 49561a1c76df759b89a9eea7c8e01e40c5997eaa Mon Sep 17 00:00:00 2001 From: ieow Date: Thu, 31 Aug 2023 21:54:24 +0800 Subject: [PATCH 09/11] fix: reduce the threshold fallback --- Sources/TorusUtils/Extensions/TorusUtils+extension.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 64a235c0..549be753 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -417,7 +417,10 @@ extension TorusUtils { let binaryString = String(data: data, encoding: .ascii) ?? "" let paddedBinaryString = binaryString.padding(toLength: 64, withPad: "0", startingAt: 0) var decryptedShare = try decryptNodeData(eciesData: latestKey.shareMetadata, ciphertextHex: paddedBinaryString, privKey: sessionAuthKey) - if ( decryptedShare.count < 64 ) { + + // temporary workaround on decrypt padding issue + if ( decryptedShare.count < 58 ) { + print(decryptedShare) decryptedShare = try decryptNodeData(eciesData: latestKey.shareMetadata, ciphertextHex: paddedBinaryString, privKey: sessionAuthKey, padding: .zeroPadding).addLeading0sForLength64() } sharePromises.append(decryptedShare) From edd4d2c122332a079bcaf8d00490cca2f42ed54a Mon Sep 17 00:00:00 2001 From: ieow Date: Thu, 31 Aug 2023 22:19:58 +0800 Subject: [PATCH 10/11] fix: remove logging --- Sources/TorusUtils/Extensions/TorusUtils+extension.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 549be753..45dee324 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -420,7 +420,6 @@ extension TorusUtils { // temporary workaround on decrypt padding issue if ( decryptedShare.count < 58 ) { - print(decryptedShare) decryptedShare = try decryptNodeData(eciesData: latestKey.shareMetadata, ciphertextHex: paddedBinaryString, privKey: sessionAuthKey, padding: .zeroPadding).addLeading0sForLength64() } sharePromises.append(decryptedShare) From d05ee80b346ade0a991d8b6c7b25830e3d40541c Mon Sep 17 00:00:00 2001 From: himanshu Date: Fri, 1 Sep 2023 13:11:09 +0800 Subject: [PATCH 11/11] use both zeropadding and pkcs7 decryption --- .../Extensions/TorusUtils+extension.swift | 86 ++++++++++++------- Tests/TorusUtilsTests/SapphireTest.swift | 3 +- 2 files changed, 57 insertions(+), 32 deletions(-) diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index 45dee324..989ccbe2 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -230,6 +230,40 @@ extension TorusUtils { + private func reconstructKey(decryptedShares: [Int: String], thresholdPublicKey: KeyAssignment.PublicKey) throws -> String? { + + // run lagrange interpolation on all subsets, faster in the optimistic scenario than berlekamp-welch due to early exit + let allCombis = kCombinations(s: decryptedShares.count, k: 3) + var returnedKey: String? = nil + + for j in 0..