Skip to content

Commit

Permalink
fix: encryption
Browse files Browse the repository at this point in the history
  • Loading branch information
ieow committed Apr 5, 2024
1 parent 04c62fd commit 390e927
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 32 deletions.
5 changes: 4 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down
53 changes: 26 additions & 27 deletions Sources/TorusUtils/Extensions/TorusUtils+extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import CommonSources
import CryptoKit
import FetchNodeDetails
import OSLog
import encryption_aes_cbc_sha512

extension TorusUtils {
// MARK: - utils
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
Expand Down
4 changes: 3 additions & 1 deletion Sources/TorusUtils/Models/RetrieveSharesResponseModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
4 changes: 2 additions & 2 deletions Sources/TorusUtils/TorusUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down
31 changes: 30 additions & 1 deletion Tests/TorusUtilsTests/SapphireTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import BigInt
import FetchNodeDetails
import JWTKit
import XCTest

import curveSecp256k1
import encryption_aes_cbc_sha512
import CommonSources

@testable import TorusUtils
Expand Down Expand Up @@ -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))

}

}

0 comments on commit 390e927

Please sign in to comment.