Skip to content

Commit

Permalink
IOS-8949 Ability to enable encryption for specific commands
Browse files Browse the repository at this point in the history
  • Loading branch information
tureck1y committed Jan 23, 2025
1 parent 23cdd76 commit 0f254a4
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 7 deletions.
13 changes: 9 additions & 4 deletions Example/TangemSdkExample/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,18 @@ class AppModel: ObservableObject {
config.handleErrors = self.handleErrors
config.filter.allowedCardTypes = FirmwareVersion.FirmwareType.allCases
config.accessCodeRequestPolicy = accessCodeRequestPolicy

var loggers: [TangemSdkLogger] = [ConsoleLogger()]

if displayLogs {
config.logConfig = .custom(logLevel: Log.Level.allCases,
loggers: [ConsoleLogger(), logger])
} else {
config.logConfig = .verbose
loggers.append(logger)
}

config.logConfig = .custom(
logLevel: Log.Level.allCases,
loggers: [ConsoleLogger(), logger]
)

config.defaultDerivationPaths = [
.secp256k1: [try! DerivationPath(rawPath: "m/0'/1")],
.secp256r1: [try! DerivationPath(rawPath: "m/0'/1")],
Expand Down
3 changes: 3 additions & 0 deletions TangemSdk/TangemSdk/Common/APDU/CommandApdu.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,12 @@ public struct CommandApdu: Equatable {
guard let encryptionKey = encryptionKey, p1 == EncryptionMode.none.byteValue else { //skip if already encrypted or empty encryptionKey
return self
}

let crc = data.crc16()
let tlvDataToEncrypt = data.count.bytes2 + crc + data
let encryptedPayload = try tlvDataToEncrypt.encrypt(with: encryptionKey)
Log.apdu("C-APDU encrypted")

return CommandApdu(cla: self.cla, ins: self.ins, p1: encryptionMode.byteValue, p2: self.p2, le: self.le, tlv: Data(encryptedPayload))
}

Expand Down
7 changes: 6 additions & 1 deletion TangemSdk/TangemSdk/Common/Core/CardSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,7 @@ public class CardSession {
/// - completion: Completion handler. Invoked by nfc-reader
public final func send(apdu: CommandApdu, completion: @escaping CompletionResult<ResponseApdu>) {
Log.session("Send")

guard sendSubscription.isEmpty else {
Log.error(TangemSdkError.busy)
completion(.failure(.busy))
Expand Down Expand Up @@ -360,8 +361,10 @@ public class CardSession {
private func prepareSession<T: CardSessionRunnable>(for runnable: T, completion: @escaping CompletionResult<Void>) {
Log.session("Prepare card session")
preflightReadMode = runnable.preflightReadMode
environment.encryptionMode = runnable.encryptionMode

Log.session("Current policy is \(environment.config.accessCodeRequestPolicy)")
Log.session("Access code policy is \(environment.config.accessCodeRequestPolicy)")
Log.session("Encryption mode is \(environment.encryptionMode)")

guard runnable.shouldAskForAccessCode else {
Log.session("Skip an access codes request")
Expand Down Expand Up @@ -476,6 +479,8 @@ public class CardSession {
let secret = try encryptionHelper.generateSecret(keyB: response.sessionKeyB)
let sessionKey = (secret + protocolKey).getSha256()
self.environment.encryptionKey = sessionKey

Log.session("The encryption established")
return ()
}
.mapError{$0.toTangemSdkError()}
Expand Down
9 changes: 7 additions & 2 deletions TangemSdk/TangemSdk/Common/Core/CardSessionRunnable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ public protocol CardSessionRunnable {

/// Allow SDK to fetch access code from the local encrypted repository when running the command
var shouldAskForAccessCode: Bool { get }


/// An enforced encryption mode. Managed by a card if none. None by default.
var encryptionMode: EncryptionMode { get }

/// Simple interface for responses received after sending commands to Tangem cards.
associatedtype Response

Expand All @@ -36,7 +39,9 @@ extension CardSessionRunnable {
public var preflightReadMode: PreflightReadMode { .fullCardRead }

public var shouldAskForAccessCode: Bool { true }


public var encryptionMode: EncryptionMode { .none }

public func prepare(_ session: CardSession, completion: @escaping CompletionResult<Void>) {
completion(.success(()))
}
Expand Down
4 changes: 4 additions & 0 deletions TangemSdk/TangemSdk/Operations/Wallet/CreateWalletTask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ import Foundation
* RemainingSignature is set to MaxSignatures.
*/
public class CreateWalletTask: CardSessionRunnable {
public var encryptionMode: EncryptionMode {
privateKey == nil ? .none : .strong
}

private let curve: EllipticCurve
private let privateKey: ExtendedPrivateKey?
private var derivationTask: DeriveWalletPublicKeysTask? = nil
Expand Down

0 comments on commit 0f254a4

Please sign in to comment.