File: AES_GCM_SIV.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 (160 lines) | stat: -rw-r--r-- 7,323 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2022 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 Crypto
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
@_implementationOnly import CryptoBoringWrapper
import Foundation

/// Types associated with the AES GCM SIV algorithm
extension AES.GCM {
    /// AES in GCM SIV mode with 128-bit tags.
    public enum _SIV {
        static let tagByteCount = 16
        static let nonceByteCount = 12

        /// Encrypts and authenticates data using AES-GCM-SIV.
        ///
        /// - Parameters:
        ///   - message: The message to encrypt and authenticate
        ///   - key: An encryption key of 128 or 256 bits
        ///   - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce()
        ///   - authenticatedData: Data to authenticate as part of the seal
        /// - Returns: A sealed box returning the authentication tag (seal) and the ciphertext
        /// - Throws: CipherError errors
        public static func seal<Plaintext: DataProtocol, AuthenticatedData: DataProtocol>
            (_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil, authenticating authenticatedData: AuthenticatedData) throws -> SealedBox {
            return try OpenSSLAESGCMSIVImpl.seal(key: key, message: message, nonce: nonce, authenticatedData: authenticatedData)
        }

        /// Encrypts and authenticates data using AES-GCM-SIV.
        ///
        /// - Parameters:
        ///   - message: The message to encrypt and authenticate
        ///   - key: An encryption key of 128 or 256 bits
        ///   - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce()
        /// - Returns: A sealed box returning the authentication tag (seal) and the ciphertext
        /// - Throws: CipherError errors
        public static func seal<Plaintext: DataProtocol>
            (_ message: Plaintext, using key: SymmetricKey, nonce: Nonce? = nil) throws -> SealedBox {
            return try OpenSSLAESGCMSIVImpl.seal(key: key, message: message, nonce: nonce, authenticatedData: Data?.none)
        }

        /// Authenticates and decrypts data using AES-GCM-SIV.
        ///
        /// - Parameters:
        ///   - sealedBox: The sealed box to authenticate and decrypt
        ///   - key: An encryption key of 128 or 256 bits
        ///   - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
        ///   - authenticatedData: Data that was authenticated as part of the seal
        /// - Returns: The ciphertext if opening was successful
        /// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
        public static func open<AuthenticatedData: DataProtocol>
            (_ sealedBox: SealedBox, using key: SymmetricKey, authenticating authenticatedData: AuthenticatedData) throws -> Data {
            return try OpenSSLAESGCMSIVImpl.open(key: key, sealedBox: sealedBox, authenticatedData: authenticatedData)
        }

        /// Authenticates and decrypts data using AES-GCM-SIV.
        ///
        /// - Parameters:
        ///   - sealedBox: The sealed box to authenticate and decrypt
        ///   - key: An encryption key of 128 or 256 bits
        ///   - nonce: An Nonce for AES-GCM-SIV encryption. The nonce must be unique for every use of the key to seal data. It can be safely generated with AES.GCM.Nonce().
        /// - Returns: The ciphertext if opening was successful
        /// - Throws: CipherError errors. If the authentication of the sealed box failed, incorrectTag is thrown.
        public static func open(_ sealedBox: SealedBox, using key: SymmetricKey) throws -> Data {
            return try OpenSSLAESGCMSIVImpl.open(key: key, sealedBox: sealedBox, authenticatedData: Data?.none)
        }
    }
}

extension AES.GCM._SIV {
    public struct Nonce: ContiguousBytes, Sequence {
        let bytes: Data

        /// Generates a fresh random Nonce. Unless required by a specification to provide a specific Nonce, this is the recommended initializer.
        public init() {
            var data = Data(repeating: 0, count: AES.GCM._SIV.nonceByteCount)
            data.withUnsafeMutableBytes {
                assert($0.count == AES.GCM._SIV.nonceByteCount)
                $0.initializeWithRandomBytes(count: AES.GCM._SIV.nonceByteCount)
            }
            self.bytes = data
        }

        public init<D: DataProtocol>(data: D) throws {
            if data.count != AES.GCM._SIV.nonceByteCount {
                throw CryptoKitError.incorrectParameterSize
            }

            self.bytes = Data(data)
        }

        public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
            return try self.bytes.withUnsafeBytes(body)
        }

        public func makeIterator() -> Array<UInt8>.Iterator {
            self.withUnsafeBytes({ (buffPtr) in
                return Array(buffPtr).makeIterator()
            })
        }
    }
}

extension AES.GCM._SIV {
    public struct SealedBox {
        /// The combined representation ( nonce || ciphertext || tag)
        public let combined: Data
        /// The authentication tag
        public var tag: Data {
            return combined.suffix(AES.GCM._SIV.tagByteCount)
        }
        /// The ciphertext
        public var ciphertext: Data {
            return combined.dropFirst(AES.GCM._SIV.nonceByteCount).dropLast(AES.GCM._SIV.tagByteCount)
        }
        /// The Nonce
        public var nonce: AES.GCM._SIV.Nonce {
            return try! AES.GCM._SIV.Nonce(data: combined.prefix(AES.GCM._SIV.nonceByteCount))
        }

        @inlinable
        public init<D: DataProtocol>(combined: D) throws {
            // AES minimum nonce (12 bytes) + AES tag (16 bytes)
            // While we have these values in the internal APIs, we can't use it in inlinable code.
            let aesGCMOverhead = 12 + 16

            if combined.count < aesGCMOverhead {
                throw CryptoKitError.incorrectParameterSize
            }

            self.combined = Data(combined)
        }

        public init<C: DataProtocol, T: DataProtocol>(nonce: AES.GCM._SIV.Nonce, ciphertext: C, tag: T) throws {
            guard tag.count == AES.GCM._SIV.tagByteCount else {
                throw CryptoKitError.incorrectParameterSize
            }

            self.combined = Data(nonce) + ciphertext + tag
        }

        internal init(combined: Data, nonceByteCount: Int) {
            assert(nonceByteCount == AES.GCM._SIV.nonceByteCount)
            self.combined = combined
        }
    }
}