File: X25519Keys_boring.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 (136 lines) | stat: -rw-r--r-- 6,555 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019 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
//
//===----------------------------------------------------------------------===//
#if CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API
@_exported import CryptoKit
#else
@_implementationOnly import CCryptoBoringSSL
@_implementationOnly import CCryptoBoringSSLShims
import Foundation

extension Curve25519.KeyAgreement {
    @usableFromInline
    static let keySizeBytes = 32

    @usableFromInline
    struct OpenSSLCurve25519PublicKeyImpl {
        @usableFromInline
        var keyBytes: [UInt8]

        @inlinable
        init<D: ContiguousBytes>(rawRepresentation: D) throws {
            self.keyBytes = try rawRepresentation.withUnsafeBytes { dataPtr in
                guard dataPtr.count == Curve25519.KeyAgreement.keySizeBytes else {
                    throw CryptoKitError.incorrectKeySize
                }

                return Array(dataPtr)
            }
        }

        @usableFromInline
        init(_ keyBytes: [UInt8]) {
            self.keyBytes = keyBytes
        }

        @usableFromInline
        var rawRepresentation: Data {
            Data(self.keyBytes)
        }
    }

    @usableFromInline
    struct OpenSSLCurve25519PrivateKeyImpl {
        var key: SecureBytes

        @usableFromInline
        var publicKey: OpenSSLCurve25519PublicKeyImpl

        init() {
            var publicKey = Array(repeating: UInt8(0), count: Curve25519.KeyAgreement.keySizeBytes)

            self.key = SecureBytes(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { privateKeyBytes, privateKeySize in
                publicKey.withUnsafeMutableBytes { publicKeyBytes in
                    precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
                    precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
                    CCryptoBoringSSLShims_X25519_keypair(publicKeyBytes.baseAddress, privateKeyBytes.baseAddress)
                }
                privateKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing.
            }
            self.publicKey = .init(publicKey)

            // BoringSSL performs an "anti-mask" of the private key. That's well-motivated, but corecrypto doesn't
            // and we'd like to behave the same way. Undo the private key anti-mask.
            let firstByteIndex = self.key.startIndex
            let lastByteIndex = self.key.index(before: self.key.endIndex)
            self.key[firstByteIndex] &= 248
            self.key[lastByteIndex] &= 127
            self.key[lastByteIndex] |= 64
        }

        init<D: ContiguousBytes>(rawRepresentation: D) throws {
            let publicBytes: [UInt8] = try rawRepresentation.withUnsafeBytes { privatePointer in
                try OpenSSLCurve25519PrivateKeyImpl.validateX25519PrivateKeyData(rawRepresentation: privatePointer)

                return Array(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { publicKeyBytes, publicKeySize in
                    precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes)
                    CCryptoBoringSSLShims_X25519_public_from_private(publicKeyBytes.baseAddress, privatePointer.baseAddress)
                    publicKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing.
                }
            }

            self.key = SecureBytes(bytes: rawRepresentation)
            self.publicKey = .init(publicBytes)
        }

        @usableFromInline
        func sharedSecretFromKeyAgreement(with publicKeyShare: OpenSSLCurve25519PublicKeyImpl) throws -> SharedSecret {
            let sharedSecret = SecureBytes(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { secretPointer, secretSize in
                self.key.withUnsafeBytes { privateKeyPointer in
                    // We precondition on all of these sizes because bounds checking is cool.
                    // These are fatal instead of guards because we allocated the secret (so it must be right),
                    // we either allocated the private key or validated it on construction (so it must be right),
                    // and we validated the public key on construction (so it must be right).
                    precondition(secretPointer.count == Curve25519.KeyAgreement.keySizeBytes)
                    precondition(privateKeyPointer.count == Curve25519.KeyAgreement.keySizeBytes)
                    precondition(publicKeyShare.keyBytes.count == Curve25519.KeyAgreement.keySizeBytes)

                    // We don't check the return code here. This return code only validates that the generated secret is not the weak all-zero
                    // secret (it is not possible for BoringSSL's X25519 implementation to fail, which is nice). There is currently what I would
                    // politely describe as a "lack of consensus" as to whether crypto libraries should reject this secret. CryptoKit on Apple
                    // platforms currently does not, so for the sake of conformance with our peer implementation I will also refuse to check it.
                    // We may elect to revisit this decision if the security best-practice thinking changes.
                    CCryptoBoringSSLShims_X25519(secretPointer.baseAddress, privateKeyPointer.baseAddress, publicKeyShare.keyBytes)
                }

                secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it.
            }

            return SharedSecret(ss: sharedSecret)
        }

        @usableFromInline
        var rawRepresentation: Data {
            Data(self.key)
        }

        /// Validates whether the passed x25519 key representation is valid.
        /// - Parameter rawRepresentation: The provided key representation. Expected to be a valid 32-bytes private key.
        static func validateX25519PrivateKeyData(rawRepresentation: UnsafeRawBufferPointer) throws {
            guard rawRepresentation.count == 32 else {
                throw CryptoKitError.incorrectKeySize
            }
        }
    }
}
#endif // CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API