From 053ec65d4889190ee7de770bae69a3cc84c24d55 Mon Sep 17 00:00:00 2001 From: Dmitry Bespalov Date: Wed, 4 Sep 2019 14:22:50 +0200 Subject: [PATCH] padding --- Sources/Keycard/Crypto.swift | 10 +++++++--- Sources/Keycard/SecureChannel.swift | 5 +++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/Sources/Keycard/Crypto.swift b/Sources/Keycard/Crypto.swift index ea5d5c2..b3021dd 100644 --- a/Sources/Keycard/Crypto.swift +++ b/Sources/Keycard/Crypto.swift @@ -21,11 +21,15 @@ class Crypto { } func aes256Enc(data: [UInt8], iv: [UInt8], key: [UInt8]) -> [UInt8] { - try! AES(key: key, blockMode: CBC(iv: iv), padding: .zeroPadding).encrypt(data) + let result = try! AES(key: key, blockMode: CBC(iv: iv), padding: .zeroPadding).encrypt(data) + Logger.shared.log("aes256Enc(data=\(Data(data).toHexString()) iv=\(Data(iv).toHexString()) key=\(Data(key).toHexString())) => \(Data(result).toHexString())") + return result } func aes256Dec(data: [UInt8], iv: [UInt8], key: [UInt8]) -> [UInt8] { - try! AES(key: key, blockMode: CBC(iv: iv), padding: .zeroPadding).decrypt(data) + let result = try! AES(key: key, blockMode: CBC(iv: iv), padding: .zeroPadding).decrypt(data) + Logger.shared.log("aes256Dec(data=\(Data(data).toHexString()) iv=\(Data(iv).toHexString()) key=\(Data(key).toHexString())) => \(Data(result).toHexString())") + return result } func aes256CMac(data: [UInt8], key: [UInt8]) -> [UInt8] { @@ -135,7 +139,7 @@ class Crypto { repeat { secretKey = random(count: 32) } while secp256k1_ec_seckey_verify(secp256k1Ctx, &secretKey) != Int32(1) - + return (secretKey, secp256k1PublicFromPrivate(secretKey)) } diff --git a/Sources/Keycard/SecureChannel.swift b/Sources/Keycard/SecureChannel.swift index 736e8f7..c647c37 100644 --- a/Sources/Keycard/SecureChannel.swift +++ b/Sources/Keycard/SecureChannel.swift @@ -162,10 +162,11 @@ class SecureChannel { func oneShotEncrypt(data: [UInt8]) -> [UInt8] { self.iv = Crypto.shared.random(count: SecureChannel.blockLength) - let encrypted = Crypto.shared.aes256Enc(data: data, iv: iv, key: secret!) + let paddedData = Crypto.shared.iso7816_4Pad(data: data, blockSize: SecureChannel.blockLength) + let encrypted = Crypto.shared.aes256Enc(data: paddedData, iv: iv, key: secret!) let result = [UInt8(self.publicKey!.count)] + publicKey! + iv + encrypted - Logger.shared.log("oneShotEncrypt: iv=\(Data(iv).toHexString()) secret=\(Data(secret!).toHexString()) encrypted=\(Data(encrypted).toHexString()) ==> \(Data(result).toHexString())") + Logger.shared.log("oneShotEncrypt: iv=\(Data(iv).toHexString()) secret=\(Data(secret!).toHexString()) padded=\(Data(paddedData).toHexString()) encrypted=\(Data(encrypted).toHexString()) ==> \(Data(result).toHexString())") return result }