Skip to content

Commit

Permalink
Merge pull request #69 from outfoxx/fix/keypair-export-import
Browse files Browse the repository at this point in the history
Use authenticated (AES GCM) for SecKeyPair export/import
  • Loading branch information
kdubb committed May 31, 2023
2 parents 142698c + 31278b7 commit fc754f9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
23 changes: 9 additions & 14 deletions Sources/ShieldSecurity/SecKeyPair.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
// Distributed under the MIT License, See LICENSE for details.
//

import CryptoKit
import Foundation
import PotentASN1
import Security
Expand Down Expand Up @@ -356,13 +357,12 @@ public struct SecKeyPair {
)

let keyMaterial = try encodedPrivateKey()
let encryptedKeyMaterial = try Cryptor.encrypt(
data: keyMaterial,
using: .aes,
options: [.pkcs7Padding],
key: exportKey,
iv: exportKeySalt
)

let encryptedKeyBox = try AES.GCM.seal(keyMaterial, using: SymmetricKey(data: exportKey))

guard let encryptedKeyMaterial = encryptedKeyBox.combined else {
fatalError("Combined sealed box should be available")
}

let keyType = try privateKey.keyType()

Expand Down Expand Up @@ -398,13 +398,8 @@ public struct SecKeyPair {
rounds: Int(info.exportKeyRounds)
)

let keyMaterial = try Cryptor.decrypt(
data: info.keyMaterial,
using: .aes,
options: .pkcs7Padding,
key: exportKey,
iv: info.exportKeySalt
)
let keyMaterial = try AES.GCM.open(AES.GCM.SealedBox(combined: info.keyMaterial),
using: SymmetricKey(data: exportKey))

return try Self(type: info.keyType, privateKeyData: keyMaterial)
}
Expand Down
2 changes: 2 additions & 0 deletions Tests/SecKeyPairTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ class SecKeyPairTests: XCTestCase {

let importedKeyPair = try SecKeyPair.import(fromData: exportedKeyData, withPassword: "123")

XCTAssertThrowsError(try SecKeyPair.import(fromData: exportedKeyData, withPassword: "456"))

let plainText = try Random.generate(count: 171)

let cipherText1 = try rsaKeyPair.publicKey.encrypt(plainText: plainText, padding: .oaep)
Expand Down

0 comments on commit fc754f9

Please sign in to comment.