Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use authenticated (AES GCM) for SecKeyPair export/import #69

Merged
merged 1 commit into from
May 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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