File: CryptoKitShim.swift

package info (click to toggle)
webkit2gtk 2.51.3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 477,912 kB
  • sloc: cpp: 3,898,343; javascript: 198,215; ansic: 165,229; python: 50,371; asm: 21,819; ruby: 18,095; perl: 16,953; xml: 4,623; sh: 2,398; yacc: 2,356; java: 2,019; lex: 1,358; pascal: 372; makefile: 197
file content (933 lines) | stat: -rw-r--r-- 36,259 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
// Copyright (C) 2024 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.

#if swift(>=5.9)

import CryptoKit
import Foundation
import PALSwift
import PALSwift.CryptoDigestHashFunction

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public typealias CryptoOperationReturnValue = Cpp.CryptoOperationReturnValue

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public typealias ErrorCodes = Cpp.ErrorCodes

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public typealias VectorUInt8 = Cpp.VectorUInt8

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public typealias SpanConstUInt8 = Cpp.SpanConstUInt8

private enum LocalErrors: Error {
    case invalidArgument
}

private class Utils {
    static let zeroArray = [UInt8](repeating: 0, count: 0)
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public class AesGcm {
    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func encrypt(
        key: SpanConstUInt8,
        iv: SpanConstUInt8,
        ad: SpanConstUInt8,
        message: SpanConstUInt8,
        desiredTagLengthInBytes: Int
    ) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            if iv.size() == 0 {
                returnValue.errorCode = .InvalidArgument
                return returnValue
            }
            let sealedBox: AES.GCM.SealedBox = try AES.GCM.seal(message, key: key, iv: iv, ad: ad)
            if desiredTagLengthInBytes > sealedBox.tag.count {
                returnValue.errorCode = .InvalidArgument
                return returnValue
            }
            var result = sealedBox.ciphertext
            result.append(
                sealedBox.tag[
                    sealedBox.tag.startIndex..<(sealedBox.tag.startIndex + desiredTagLengthInBytes)
                ]
            )
            returnValue.errorCode = .Success
            returnValue.result = result.copyToVectorUInt8()
            return returnValue
        } catch {
            returnValue.errorCode = .EncryptionFailed
        }
        return returnValue
    }
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public class AesKw {
    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func wrap(keyToWrap: SpanConstUInt8, using: SpanConstUInt8) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            let result = try AES.KeyWrap.wrap(keyToWrap, using: using)
            returnValue.errorCode = .Success
            returnValue.result = result
        } catch {
            returnValue.errorCode = .EncryptionFailed
        }
        return returnValue
    }

    public static func unwrap(wrappedKey: SpanConstUInt8, using: SpanConstUInt8) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            let result = try AES.KeyWrap.unwrap(
                wrappedKey,
                using: using
            )
            returnValue.errorCode = .Success
            returnValue.result = result.copyToVectorUInt8()
        } catch {
            returnValue.errorCode = .EncryptionFailed
        }
        return returnValue
    }
} // AesKw

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public class Digest {
    var ctx: any CryptoKit.HashFunction

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public required init<T: CryptoKit.HashFunction>(_: T.Type) {
        ctx = T()
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sha1Init() -> Digest {
        Self(Insecure.SHA1.self)
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sha256Init() -> Digest {
        Self(SHA256.self)
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sha384Init() -> Digest {
        Self(SHA384.self)
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sha512Init() -> Digest {
        Self(SHA512.self)
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public func update(_ data: SpanConstUInt8) {
        ctx.update(data: data)
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public func finalize() -> VectorUInt8 {
        ctx.finalize().copyToVectorUInt8()
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sha1(_ data: SpanConstUInt8) -> VectorUInt8 {
        digest(data, t: Insecure.SHA1.self)
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sha256(_ data: SpanConstUInt8) -> VectorUInt8 {
        digest(data, t: SHA256.self)
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sha384(_ data: SpanConstUInt8) -> VectorUInt8 {
        digest(data, t: SHA384.self)
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sha512(_ data: SpanConstUInt8) -> VectorUInt8 {
        digest(data, t: SHA512.self)
    }

    fileprivate static func digest<T: CryptoKit.HashFunction>(_ data: SpanConstUInt8, _: T.Type) -> T.Digest {
        var hasher = T()
        hasher.update(data: data)
        return hasher.finalize()
    }

    fileprivate static func digest<T: CryptoKit.HashFunction>(_ data: SpanConstUInt8, t: T.Type) -> VectorUInt8 {
        Self.digest(data, t).copyToVectorUInt8()
    }

    fileprivate static func digest(_ data: SpanConstUInt8, hashFunction: PAL.CryptoDigestHashFunction) -> any CryptoKit.Digest {
        switch hashFunction {
        case .SHA_256:
            return digest(data, SHA256.self)
        case .SHA_384:
            return digest(data, SHA384.self)
        case .SHA_512:
            return digest(data, SHA512.self)
        case .SHA_1:
            return digest(data, Insecure.SHA1.self)
        case .DEPRECATED_SHA_224:
            fatalError("DEPRECATED_SHA_224 is not supported")
        @unknown default:
            fatalError("Unknown PAL.CryptoDigestHashFunction enum case value: \(hashFunction.rawValue)")
        }
    }
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public enum ECCurve {
    case p256
    case p384
    case p521
}

enum ECPrivateKey {
    case p256(P256.Signing.PrivateKey)
    case p384(P384.Signing.PrivateKey)
    case p521(P521.Signing.PrivateKey)
}

enum ECPublicKey {
    case p256(P256.Signing.PublicKey)
    case p384(P384.Signing.PublicKey)
    case p521(P521.Signing.PublicKey)
}

enum ECKeyInternal {
    case privateKey(ECPrivateKey)
    case publicKey(ECPublicKey)
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public enum ECImportReturnCode {
    case defaultValue
    case success
    case importFailed
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public struct ECImportReturnValue {
    public var errorCode: ECImportReturnCode = .defaultValue
    public var key: ECKey? = nil
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public struct ECKey {
    let key: ECKeyInternal

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public init(curve: ECCurve) {
        switch curve {
        case .p256:
            key = .privateKey(.p256(P256.Signing.PrivateKey(compactRepresentable: true)))
        case .p384:
            key = .privateKey(.p384(P384.Signing.PrivateKey(compactRepresentable: true)))
        case .p521:
            key = .privateKey(.p521(P521.Signing.PrivateKey(compactRepresentable: true)))
        }
    }

    private init(publicKey: ECPublicKey) {
        key = .publicKey(publicKey)
    }

    private init(privateKey: ECPrivateKey) {
        key = .privateKey(privateKey)
    }

    private init(internalKey: ECKeyInternal) {
        key = internalKey
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public func toPub() -> ECKey {
        switch key {
        case .publicKey:
            return self
        case .privateKey(let v):
            switch v {
            case .p256(let u):
                return ECKey(publicKey: .p256(u.publicKey))
            case .p384(let u):
                return ECKey(publicKey: .p384(u.publicKey))
            case .p521(let u):
                return ECKey(publicKey: .p521(u.publicKey))
            }
        }
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func importX963Pub(data: SpanConstUInt8, curve: ECCurve) -> ECImportReturnValue {
        var returnValue = ECImportReturnValue()
        do {
            switch curve {
            case .p256:
                returnValue.key = ECKey(internalKey: .publicKey(.p256(try P256.Signing.PublicKey(span: data))))
            case .p384:
                returnValue.key = ECKey(internalKey: .publicKey(.p384(try P384.Signing.PublicKey(span: data))))
            case .p521:
                returnValue.key = ECKey(internalKey: .publicKey(.p521(try P521.Signing.PublicKey(span: data))))
            }
            returnValue.errorCode = .success
        } catch {
            returnValue.errorCode = .importFailed
        }
        return returnValue
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public func exportX963Pub() -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            switch try getInternalPublic() {
            case .p256(let k):
                returnValue.result = k.x963Representation.copyToVectorUInt8()
            case .p384(let k):
                returnValue.result = k.x963Representation.copyToVectorUInt8()
            case .p521(let k):
                returnValue.result = k.x963Representation.copyToVectorUInt8()
            }
            returnValue.errorCode = .Success
        } catch {
            returnValue.errorCode = .FailedToExport
        }
        return returnValue
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func importCompressedPub(data: SpanConstUInt8, curve: ECCurve) -> ECImportReturnValue {
        var returnValue = ECImportReturnValue()
        do {
            switch curve {
            case .p256:
                returnValue.key = ECKey(publicKey: .p256(try P256.Signing.PublicKey(spanCompressed: data)))
            case .p384:
                returnValue.key = ECKey(publicKey: .p384(try P384.Signing.PublicKey(spanCompressed: data)))
            case .p521:
                returnValue.key = ECKey(publicKey: .p521(try P521.Signing.PublicKey(spanCompressed: data)))
            }
            returnValue.errorCode = .success
        } catch {
            returnValue.errorCode = .importFailed
        }
        return returnValue
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func importX963Private(data: SpanConstUInt8, curve: ECCurve) -> ECImportReturnValue {
        var returnValue = ECImportReturnValue()
        do {
            switch curve {
            case .p256:
                returnValue.key = ECKey(privateKey: .p256(try P256.Signing.PrivateKey(span: data)))
            case .p384:
                returnValue.key = ECKey(privateKey: .p384(try P384.Signing.PrivateKey(span: data)))
            case .p521:
                returnValue.key = ECKey(privateKey: .p521(try P521.Signing.PrivateKey(span: data)))
            }
            returnValue.errorCode = .success
        } catch {
            returnValue.errorCode = .importFailed
        }
        return returnValue
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public func exportX963Private() -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            switch try getInternalPrivate() {
            case .p256(let k):
                returnValue.result = k.x963Representation.copyToVectorUInt8()
            case .p384(let k):
                returnValue.result = k.x963Representation.copyToVectorUInt8()
            case .p521(let k):
                returnValue.result = k.x963Representation.copyToVectorUInt8()
            }
            returnValue.errorCode = .Success
        } catch {
            returnValue.errorCode = .FailedToExport
        }
        return returnValue
    }

    // FIXME: `hashFunction` should not be a raw value, but compilers < 6.0 do not understand C++ enums as parameters.
    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public func sign(
        message: SpanConstUInt8,
        hashFunction hashFunctionRawValue: PAL.CryptoDigestHashFunction.RawValue
    ) -> CryptoOperationReturnValue {
        // FIXME: This is safe because all callers use the enum type itself, and this is only temporary.
        // swift-format-ignore: NeverForceUnwrap
        let hashFunction = PAL.CryptoDigestHashFunction(rawValue: hashFunctionRawValue)!

        var returnValue = CryptoOperationReturnValue()
        do {
            switch try getInternalPrivate() {
            case .p256(let cryptoKey):
                returnValue.result =
                    try cryptoKey.signature(for: Digest.digest(message, hashFunction: hashFunction))
                    .rawRepresentation.copyToVectorUInt8()
            case .p384(let cryptoKey):
                returnValue.result =
                    try cryptoKey.signature(for: Digest.digest(message, hashFunction: hashFunction))
                    .rawRepresentation.copyToVectorUInt8()
            case .p521(let cryptoKey):
                returnValue.result =
                    try cryptoKey.signature(for: Digest.digest(message, hashFunction: hashFunction))
                    .rawRepresentation.copyToVectorUInt8()
            }
            returnValue.errorCode = .Success
        } catch {
            returnValue.errorCode = .FailedToSign
        }
        return returnValue
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public func verify(
        message: SpanConstUInt8,
        signature: SpanConstUInt8,
        hashFunction hashFunctionRawValue: PAL.CryptoDigestHashFunction.RawValue
    ) -> CryptoOperationReturnValue {
        // FIXME: This is safe because all callers use the enum type itself, and this is only temporary.
        // swift-format-ignore: NeverForceUnwrap
        let hashFunction = PAL.CryptoDigestHashFunction(rawValue: hashFunctionRawValue)!

        var returnValue = CryptoOperationReturnValue()
        do {
            let internalPublic = try getInternalPublic()
            switch internalPublic {
            case .p256(let cryptoKey):
                returnValue.errorCode =
                    cryptoKey.isValidSignature(
                        try P256.Signing.ECDSASignature(span: signature),
                        for: Digest.digest(message, hashFunction: hashFunction)
                    )
                    ? .Success : .FailedToVerify
            case .p384(let cryptoKey):
                returnValue.errorCode =
                    cryptoKey.isValidSignature(
                        try P384.Signing.ECDSASignature(span: signature),
                        for: Digest.digest(message, hashFunction: hashFunction)
                    )
                    ? .Success : .FailedToVerify
            case .p521(let cryptoKey):
                returnValue.errorCode =
                    cryptoKey.isValidSignature(
                        try P521.Signing.ECDSASignature(span: signature),
                        for: Digest.digest(message, hashFunction: hashFunction)
                    )
                    ? .Success : .FailedToVerify
            }
        } catch {
            returnValue.errorCode = .FailedToVerify
        }
        return returnValue
    }

    private func getInternalPrivate() throws -> ECPrivateKey {
        switch key {
        case .publicKey:
            throw LocalErrors.invalidArgument
        case .privateKey(let privateKey):
            return privateKey
        }
    }

    private func getInternalPublic() throws -> ECPublicKey {
        switch key {
        case .privateKey:
            throw LocalErrors.invalidArgument
        case .publicKey(let publicKey):
            return publicKey
        }
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public func deriveBits(publicKey: ECKey) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            let internalPrivate = try getInternalPrivate()
            let internalPub = try publicKey.getInternalPublic()
            switch internalPrivate {
            case .p256(let signing):
                let scalar = try P256.KeyAgreement.PrivateKey(
                    rawRepresentation: signing.rawRepresentation
                )
                if case .p256(let publicKey) = internalPub {
                    let derived = try scalar.sharedSecretFromKeyAgreement(
                        with: try P256.KeyAgreement.PublicKey(
                            rawRepresentation: publicKey.rawRepresentation
                        )
                    )
                    returnValue.result = derived.copyToVectorUInt8()
                    break
                }
                returnValue.errorCode = .InvalidArgument
            case .p384(let signing):
                let scalar = try P384.KeyAgreement.PrivateKey(
                    rawRepresentation: signing.rawRepresentation
                )
                if case .p384(let publicKey) = internalPub {
                    let derived = try scalar.sharedSecretFromKeyAgreement(
                        with: try P384.KeyAgreement.PublicKey(
                            rawRepresentation: publicKey.rawRepresentation
                        )
                    )
                    returnValue.result = derived.copyToVectorUInt8()
                    break
                }
                returnValue.errorCode = .InvalidArgument
            case .p521(let signing):
                let scalar = try P521.KeyAgreement.PrivateKey(
                    rawRepresentation: signing.rawRepresentation
                )
                if case .p521(let publicKey) = internalPub {
                    let derived = try scalar.sharedSecretFromKeyAgreement(
                        with: try P521.KeyAgreement.PublicKey(
                            rawRepresentation: publicKey.rawRepresentation
                        )
                    )
                    returnValue.result = derived.copyToVectorUInt8()
                    break
                }
                returnValue.errorCode = .InvalidArgument
            }
            returnValue.errorCode = .Success
        } catch {
            returnValue.errorCode = .FailedToDerive
        }
        return returnValue
    }
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public enum EdSigningAlgorithm {
    case ed25519
    case ed448
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public enum EdKeyAgreementAlgorithm {
    case x25519
    case x448
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public class EdKey {
    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func generatePrivateKey(algo: EdSigningAlgorithm) -> VectorUInt8 {
        switch algo {
        case .ed25519:
            return Curve25519.Signing.PrivateKey().rawRepresentation.copyToVectorUInt8()
        case .ed448:
            return Data(count: 0).copyToVectorUInt8()
        }
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func generatePrivateKeyKeyAgreement(algo: EdKeyAgreementAlgorithm) -> VectorUInt8 {
        switch algo {
        case .x25519:
            return Curve25519.KeyAgreement.PrivateKey().rawRepresentation.copyToVectorUInt8()
        case .x448:
            return Data(count: 0).copyToVectorUInt8()
        }
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func privateToPublic(algo: EdSigningAlgorithm, privateKey: SpanConstUInt8) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            if privateKey.size() != 32 {
                throw LocalErrors.invalidArgument
            }
            switch algo {
            case .ed25519:
                returnValue.result = try Curve25519.Signing.PrivateKey(span: privateKey).publicKey
                    .rawRepresentation.copyToVectorUInt8()
                if returnValue.result.size() != 32 {
                    throw LocalErrors.invalidArgument
                }
                returnValue.errorCode = .Success
            case .ed448:
                returnValue.errorCode = .UnsupportedAlgorithm
            }
        } catch {
            returnValue.errorCode = .FailedToImport
        }
        return returnValue
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func privateToPublicKeyAgreement(
        algo: EdKeyAgreementAlgorithm,
        privateKey: SpanConstUInt8
    ) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            if privateKey.size() != 32 {
                throw LocalErrors.invalidArgument
            }
            switch algo {
            case .x25519:
                returnValue.result = try Curve25519.KeyAgreement.PrivateKey(span: privateKey).publicKey
                    .rawRepresentation.copyToVectorUInt8()
                if returnValue.result.size() != 32 {
                    throw LocalErrors.invalidArgument
                }
                returnValue.errorCode = .Success
            case .x448:
                returnValue.errorCode = .UnsupportedAlgorithm
            }
        } catch {
            returnValue.errorCode = .FailedToImport
        }
        return returnValue
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func validateKeyPair(algo: EdSigningAlgorithm, privateKey: SpanConstUInt8, publicKey: SpanConstUInt8) -> Bool {
        do {
            if privateKey.size() != 32 || publicKey.size() != 32 {
                throw LocalErrors.invalidArgument
            }
            switch algo {
            case .ed25519:
                let derivedPublicKey = try Curve25519.Signing.PrivateKey(span: privateKey).publicKey.rawRepresentation
                let importedPublicKey = try Curve25519.Signing.PublicKey(span: publicKey).rawRepresentation
                return derivedPublicKey == importedPublicKey
            case .ed448:
                return false
            }
        } catch {
            return false
        }
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func validateKeyPairKeyAgreement(
        algo: EdKeyAgreementAlgorithm,
        privateKey: SpanConstUInt8,
        publicKey: SpanConstUInt8
    ) -> Bool {
        do {
            if privateKey.size() != 32 || publicKey.size() != 32 {
                throw LocalErrors.invalidArgument
            }
            switch algo {
            case .x25519:
                let derivedPublicKey = try Curve25519.KeyAgreement.PrivateKey(span: privateKey).publicKey.rawRepresentation
                let importedPublicKey = try Curve25519.KeyAgreement.PublicKey(span: publicKey).rawRepresentation
                return derivedPublicKey == importedPublicKey
            case .x448:
                return false
            }
        } catch {
            return false
        }
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sign(algo: EdSigningAlgorithm, privateKey: SpanConstUInt8, data: SpanConstUInt8) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            switch algo {
            case .ed25519:
                let privateKeyImported = try Curve25519.Signing.PrivateKey(span: privateKey)
                returnValue.result = try privateKeyImported.signature(span: data)
                returnValue.errorCode = .Success
            case .ed448:
                returnValue.errorCode = .UnsupportedAlgorithm
            }
        } catch {
            returnValue.errorCode = .FailedToSign
        }
        return returnValue
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func verify(
        algo: EdSigningAlgorithm,
        publicKey: SpanConstUInt8,
        signature: SpanConstUInt8,
        data: SpanConstUInt8
    ) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            switch algo {
            case .ed25519:
                let publicKeyImported = try Curve25519.Signing.PublicKey(span: publicKey)
                returnValue.errorCode =
                    publicKeyImported.isValidSignature(signature: signature, data: data)
                    ? .Success : .FailedToVerify
            case .ed448:
                returnValue.errorCode = .UnsupportedAlgorithm
            }
        } catch {
            returnValue.errorCode = .FailedToSign
        }
        return returnValue
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func deriveBits(
        algo: EdKeyAgreementAlgorithm,
        privateKey: SpanConstUInt8,
        publicKey: SpanConstUInt8
    ) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        do {
            switch algo {
            case .x25519:
                let privateKeyImported = try Curve25519.KeyAgreement.PrivateKey(span: privateKey)
                returnValue.result = try privateKeyImported.sharedSecretFromKeyAgreement(pubSpan: publicKey)
                returnValue.errorCode = .Success
            case .x448:
                returnValue.errorCode = .UnsupportedAlgorithm
            }
        } catch {
            returnValue.errorCode = .FailedToDerive
        }
        return returnValue
    }
}

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public class HMAC {
    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func sign(
        key: SpanConstUInt8,
        data: SpanConstUInt8,
        hashFunction hashFunctionRawValue: PAL.CryptoDigestHashFunction.RawValue
    ) -> VectorUInt8 {
        // FIXME: This is safe because all callers use the enum type itself, and this is only temporary.
        // swift-format-ignore: NeverForceUnwrap
        let hashFunction = PAL.CryptoDigestHashFunction(rawValue: hashFunctionRawValue)!

        switch hashFunction {
        case .SHA_1:
            return CryptoKit.HMAC<Insecure.SHA1>.authenticationCode(data: data, key: key)
        case .SHA_256:
            return CryptoKit.HMAC<SHA256>.authenticationCode(data: data, key: key)
        case .SHA_384:
            return CryptoKit.HMAC<SHA384>.authenticationCode(data: data, key: key)
        case .SHA_512:
            return CryptoKit.HMAC<SHA512>.authenticationCode(data: data, key: key)
        case .DEPRECATED_SHA_224:
            fatalError("DEPRECATED_SHA_224 is not supported")
        @unknown default:
            fatalError("Unknown PAL.CryptoDigestHashFunction enum case value: \(hashFunction.rawValue)")
        }
    }

    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func verify(
        mac: SpanConstUInt8,
        key: SpanConstUInt8,
        data: SpanConstUInt8,
        hashFunction hashFunctionRawValue: PAL.CryptoDigestHashFunction.RawValue
    ) -> Bool {
        // FIXME: This is safe because all callers use the enum type itself, and this is only temporary.
        // swift-format-ignore: NeverForceUnwrap
        let hashFunction = PAL.CryptoDigestHashFunction(rawValue: hashFunctionRawValue)!

        switch hashFunction {
        case .SHA_1:
            return CryptoKit.HMAC<Insecure.SHA1>
                .isValidAuthenticationCode(
                    mac: mac,
                    data: data,
                    key: key
                )
        case .SHA_256:
            return CryptoKit.HMAC<SHA256>.isValidAuthenticationCode(mac: mac, data: data, key: key)
        case .SHA_384:
            return CryptoKit.HMAC<SHA384>.isValidAuthenticationCode(mac: mac, data: data, key: key)
        case .SHA_512:
            return CryptoKit.HMAC<SHA512>.isValidAuthenticationCode(mac: mac, data: data, key: key)
        case .DEPRECATED_SHA_224:
            fatalError("DEPRECATED_SHA_224 is not supported")
        @unknown default:
            fatalError("Unknown PAL.CryptoDigestHashFunction enum case value: \(hashFunction.rawValue)")
        }
    }
}

// https://www.ietf.org/rfc/rfc5869.txt
private let hkdfInputSizeLimitSHA1 = 255 * Insecure.SHA1.byteCount * 8
private let hkdfInputSizeLimitSHA256 = 255 * SHA256.byteCount * 8
private let hkdfInputSizeLimitSHA384 = 255 * SHA384.byteCount * 8
private let hkdfInputSizeLimitSHA512 = 255 * SHA512.byteCount * 8

// FIXME: PALSwift should have no public symbols.
// swift-format-ignore: AllPublicDeclarationsHaveDocumentation
public class HKDF {
    // FIXME: PALSwift should have no public symbols.
    // swift-format-ignore: AllPublicDeclarationsHaveDocumentation
    public static func deriveBits(
        key: SpanConstUInt8,
        salt: SpanConstUInt8,
        info: SpanConstUInt8,
        outputBitCount: Int,
        hashFunction hashFunctionRawValue: PAL.CryptoDigestHashFunction.RawValue
    ) -> CryptoOperationReturnValue {
        // FIXME: This is safe because all callers use the enum type itself, and this is only temporary.
        // swift-format-ignore: NeverForceUnwrap
        let hashFunction = PAL.CryptoDigestHashFunction(rawValue: hashFunctionRawValue)!

        var returnValue = CryptoOperationReturnValue()
        if outputBitCount <= 0 || outputBitCount % 8 != 0 {
            returnValue.errorCode = .InvalidArgument
            return returnValue
        } else {
            returnValue.errorCode = .Success
        }
        switch hashFunction {
        case .SHA_1:
            if outputBitCount > hkdfInputSizeLimitSHA1 {
                returnValue.errorCode = .InvalidArgument
                break
            }
            returnValue.result =
                CryptoKit.HKDF<Insecure.SHA1>
                .deriveKey(
                    inputKeyMaterial: key,
                    salt: salt,
                    info: info,
                    outputByteCount: outputBitCount / 8
                )

        case .SHA_256:
            if outputBitCount > hkdfInputSizeLimitSHA256 {
                returnValue.errorCode = .InvalidArgument
                break
            }
            returnValue.result =
                CryptoKit.HKDF<SHA256>
                .deriveKey(
                    inputKeyMaterial: key,
                    salt: salt,
                    info: info,
                    outputByteCount: outputBitCount / 8
                )

        case .SHA_384:
            if outputBitCount > hkdfInputSizeLimitSHA384 {
                returnValue.errorCode = .InvalidArgument
                break
            }
            returnValue.result =
                CryptoKit.HKDF<SHA384>
                .deriveKey(
                    inputKeyMaterial: key,
                    salt: salt,
                    info: info,
                    outputByteCount: outputBitCount / 8
                )

        case .SHA_512:
            if outputBitCount > hkdfInputSizeLimitSHA512 {
                returnValue.errorCode = .InvalidArgument
                break
            }
            returnValue.result =
                CryptoKit.HKDF<SHA512>
                .deriveKey(
                    inputKeyMaterial: key,
                    salt: salt,
                    info: info,
                    outputByteCount: outputBitCount / 8
                )

        case .DEPRECATED_SHA_224:
            fatalError("DEPRECATED_SHA_224 is not supported")

        @unknown default:
            fatalError("Unknown PAL.CryptoDigestHashFunction enum case value: \(hashFunction.rawValue)")
        }

        return returnValue
    }
}

#endif