File: AES-GCM-Runner.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (257 lines) | stat: -rw-r--r-- 11,788 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest

#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
import Crypto
#elseif !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
import CryptoKit
#else
import Crypto
#endif

struct AEADTestGroup: Codable {
    let ivSize: Int
    let keySize: UInt16
    let tagSize: UInt16
    let type: String
    let tests: [AESGCMTestVector]
}

struct AESGCMTestVector: Codable {
    let key: String
    let iv: String
    let aad: String
    let msg: String
    let ct: String
    let tag: String
    let result: String
}

class AESGCMTests: XCTestCase {
    func testPropertiesStayTheSameAfterFailedOpening() throws {
        let message = Data("this is a message".utf8)
        let sealed = try AES.GCM.seal(message, using: SymmetricKey(size: .bits128))

        // We copy the bytes of these fields out here to ensure they're saved.
        let originalCiphertext = Array(sealed.ciphertext)
        let originalNonce = Array(sealed.nonce)
        let originalTag = Array(sealed.tag)

        XCTAssertThrowsError(try AES.GCM.open(sealed, using: SymmetricKey(size: .bits128)))

        // The fields must all be unchanged.
        XCTAssertEqual(originalCiphertext, Array(sealed.ciphertext))
        XCTAssertEqual(originalNonce, Array(sealed.nonce))
        XCTAssertEqual(originalTag, Array(sealed.tag))
    }

    func testBadKeySize() {
        let plaintext: Data = "Some Super Secret Message".data(using: String.Encoding.utf8)!
        let key = SymmetricKey(size: .init(bitCount: 304))
        let nonce = AES.GCM.Nonce()

        XCTAssertThrowsError(try AES.GCM.seal(plaintext, using: key, nonce: nonce))
    }

    func testNonStandardNonceSizeCombinedRepresentation() throws {
        let ciphertext = Array("This is some weird ciphertext".utf8)
        let tag = Array(repeating: UInt8(0), count: 16)

        let regularNonce = try orFail { try AES.GCM.Nonce(data: Array(repeating: 0, count: 12)) }
        let longNonce = try orFail { try AES.GCM.Nonce(data: Array(repeating: 0, count: 13)) }

        XCTAssertNotNil(try AES.GCM.SealedBox(nonce: regularNonce, ciphertext: ciphertext, tag: tag).combined)
        XCTAssertNil(try AES.GCM.SealedBox(nonce: longNonce, ciphertext: ciphertext, tag: tag).combined)
    }

    func testEncryptDecrypt() throws {
        let plaintext: Data = "Some Super Secret Message".data(using: String.Encoding.utf8)!

        let key = SymmetricKey(size: .bits256)
        let nonce = AES.GCM.Nonce()

        let ciphertext = try orFail { try AES.GCM.seal(plaintext, using: key, nonce: nonce) }
        let recoveredPlaintext = try orFail { try AES.GCM.open(ciphertext, using: key, authenticating: Data()) }
        let recoveredPlaintextWithoutAAD = try orFail { try AES.GCM.open(ciphertext, using: key) }

        XCTAssertEqual(recoveredPlaintext, plaintext)
        XCTAssertEqual(recoveredPlaintextWithoutAAD, plaintext)
    }

    func testExtractingBytesFromNonce() throws {
        let nonce = AES.GCM.Nonce()
        XCTAssertEqual(Array(nonce), nonce.withUnsafeBytes { Array($0) })

        let testNonceBytes = Array(UInt8(0)..<UInt8(12))
        let (contiguousNonceBytes, discontiguousNonceBytes) = testNonceBytes.asDataProtocols()
        let nonceFromContiguous = try orFail { try AES.GCM.Nonce(data: contiguousNonceBytes) }
        let nonceFromDiscontiguous = try orFail { try AES.GCM.Nonce(data: discontiguousNonceBytes) }

        XCTAssertEqual(Array(nonceFromContiguous), testNonceBytes)
        XCTAssertEqual(Array(nonceFromDiscontiguous), testNonceBytes)

        XCTAssertThrowsError(try AES.GCM.Nonce(data: DispatchData.empty)) { error in
            guard case .some(.incorrectParameterSize) = error as? CryptoKitError else {
                XCTFail("Unexpected error")
                return
            }
        }
    }

    func testUserConstructedSealedBoxesCombined() throws {
        let ciphertext = Array("This pretty clearly isn't ciphertext, but sure why not".utf8)
        let (contiguousCiphertext, discontiguousCiphertext) = ciphertext.asDataProtocols()

        let contiguousSB = try orFail { try AES.GCM.SealedBox(combined: contiguousCiphertext) }
        let discontiguousSB = try orFail { try AES.GCM.SealedBox(combined: discontiguousCiphertext) }
        XCTAssertEqual(contiguousSB.combined, discontiguousSB.combined)
        XCTAssertEqual(Array(contiguousSB.nonce), Array(discontiguousSB.nonce))
        XCTAssertEqual(contiguousSB.ciphertext, discontiguousSB.ciphertext)
        XCTAssertEqual(contiguousSB.tag, discontiguousSB.tag)

        // Empty dispatchdatas don't work, they are too small.
        XCTAssertThrowsError(try AES.GCM.SealedBox(combined: DispatchData.empty)) { error in
            guard case .some(.incorrectParameterSize) = error as? CryptoKitError else {
                XCTFail("Unexpected error: \(error)")
                return
            }
        }
    }

    func testUserConstructedSealedBoxesSplit() throws {
        let tag = Array(repeating: UInt8(0), count: 16)
        let ciphertext = Array("This pretty clearly isn't ciphertext, but sure why not".utf8)
        let nonce = AES.GCM.Nonce()

        let (contiguousCiphertext, discontiguousCiphertext) = ciphertext.asDataProtocols()
        let (contiguousTag, discontiguousTag) = tag.asDataProtocols()

        // Two separate data protocol inputs means we end up with 4 boxes.
        let contiguousContiguous = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: contiguousTag) }
        let discontiguousContiguous = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: contiguousTag) }
        let contiguousDiscontiguous = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: discontiguousTag) }
        let discontiguousDiscontiguous = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: discontiguousTag) }

        // To avoid the comparison count getting too nuts, we use the combined representation. By the transitive
        // property we only need three comparisons.
        XCTAssertEqual(contiguousContiguous.combined, discontiguousContiguous.combined)
        XCTAssertEqual(discontiguousContiguous.combined, contiguousDiscontiguous.combined)
        XCTAssertEqual(contiguousDiscontiguous.combined, discontiguousDiscontiguous.combined)

        // Empty dispatchdatas for the tag don't work, they are too small.
        XCTAssertThrowsError(try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: DispatchData.empty)) { error in
            guard case .some(.incorrectParameterSize) = error as? CryptoKitError else {
                XCTFail("Unexpected error: \(error)")
                return
            }
        }

        // They work fine for the ciphertext though.
        let weirdBox = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: DispatchData.empty, tag: tag) }
        XCTAssertEqual(weirdBox.ciphertext, Data())
    }

    func testRoundTripDataProtocols() throws {
        func roundTrip<Message: DataProtocol, AAD: DataProtocol>(message: Message, aad: AAD, file: StaticString = (#file), line: UInt = #line) throws {
            let key = SymmetricKey(size: .bits256)
            let nonce = AES.GCM.Nonce()
            let ciphertext = try orFail(file: file, line: line) { try AES.GCM.seal(message, using: key, nonce: nonce, authenticating: aad) }
            let recoveredPlaintext = try orFail(file: file, line: line) { try AES.GCM.open(ciphertext, using: key, authenticating: aad) }

            XCTAssertEqual(Array(recoveredPlaintext), Array(message), file: file, line: line)
        }

        let message = Array("Hello, world, it's AES-GCM!".utf8)
        let aad = Array("I heard you like Counter Mode, so I put a Galois on it".utf8)
        let (contiguousMessage, discontiguousMessage) = message.asDataProtocols()
        let (contiguousAad, discontiguousAad) = aad.asDataProtocols()

        _ = try orFail { try roundTrip(message: contiguousMessage, aad: contiguousAad) }
        _ = try orFail { try roundTrip(message: discontiguousMessage, aad: contiguousAad) }
        _ = try orFail { try roundTrip(message: contiguousMessage, aad: discontiguousAad) }
        _ = try orFail { try roundTrip(message: discontiguousMessage, aad: discontiguousAad) }
    }

    func testWycheproof() throws {
        try orFail {
            try wycheproofTest(
                bundleType: self,
                jsonName: "aes_gcm_test",
                testFunction: { (group: AEADTestGroup) in
                    for testVector in group.tests {
                        var msg = Data()
                        var aad = Data()
                        var ct: [UInt8] = []
                        var tag: [UInt8] = []

                        do {
                            let key = try SymmetricKey(data: Array(hexString: testVector.key))
                            XCTAssertNotNil(key)

                            let nonceData = try Array(hexString: testVector.iv)

                            let nonce: AES.GCM.Nonce
                            do {
                                nonce = try AES.GCM.Nonce(data: nonceData)
                            } catch {
                                XCTAssertLessThan(nonceData.count, 12)
                                continue
                            }

                            if testVector.ct.count > 0 {
                                ct = try Array(hexString: testVector.ct)
                            }

                            if testVector.msg.count > 0 {
                                msg = try Data(hexString: testVector.msg)
                            }

                            if testVector.aad.count > 0 {
                                aad = try Data(hexString: testVector.aad)
                            }

                            if testVector.tag.count > 0 {
                                tag = try Array(hexString: testVector.tag)
                            }

                            let sb = try AES.GCM.seal(msg, using: key, nonce: nonce, authenticating: aad)

                            XCTAssertEqual(Data(ct), sb.ciphertext)

                            if testVector.result == "valid" {
                                XCTAssertEqual(Data(tag), sb.tag)
                            }

                            do {
                                let recovered_pt = try AES.GCM.open(AES.GCM.SealedBox(nonce: nonce, ciphertext: ct, tag: tag), using: key, authenticating: aad)

                                if testVector.result == "valid" || testVector.result == "acceptable" {
                                    XCTAssertEqual(recovered_pt, msg)
                                } else {
                                    XCTFail()
                                }
                            } catch {
                                XCTAssertEqual(testVector.result, "invalid")
                            }
                        } catch {
                            XCTAssert(testVector.result == "invalid" || testVector.iv == "")
                            return
                        }
                    }
                })
        }
    }
}