File: CryptoKitShim.swift

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (744 lines) | stat: -rw-r--r-- 27,149 bytes parent folder | download | duplicates (6)
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
/*
* 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

public typealias CryptoOperationReturnValue = Cpp.CryptoOperationReturnValue
public typealias ErrorCodes = Cpp.ErrorCodes
public typealias VectorUInt8 = Cpp.VectorUInt8
public typealias SpanConstUInt8 = Cpp.SpanConstUInt8

private enum LocalErrors: Error {
    case invalidArgument
}

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

public class AesGcm {
    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
    }
}

public class AesKw {
    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

public enum HashFunction {
    case sha1
    case sha256
    case sha384
    case sha512
}

public class Digest {
    var ctx: any CryptoKit.HashFunction

    public required init<T: CryptoKit.HashFunction>(_: T.Type) {
        ctx = T()
    }

    public static func sha1Init() -> Digest {
        return Self(Insecure.SHA1.self)
    }

    public static func sha256Init() -> Digest {
        return Self(SHA256.self)
    }

    public static func sha384Init() -> Digest {
        return Self(SHA384.self)
    }

    public static func sha512Init() -> Digest {
        return Self(SHA512.self)
    }

    public func update(_ data: SpanConstUInt8) {
        ctx.update(data: data)
    }

    public func finalize() -> VectorUInt8 {
        ctx.finalize().copyToVectorUInt8()
    }

    public static func sha1(_ data: SpanConstUInt8) -> VectorUInt8 {
        return digest(data, t: Insecure.SHA1.self)
    }
    public static func sha256(_ data: SpanConstUInt8) -> VectorUInt8 {
        return digest(data, t: SHA256.self)
    }
    public static func sha384(_ data: SpanConstUInt8) -> VectorUInt8 {
        return digest(data, t: SHA384.self)
    }
    public static func sha512(_ data: SpanConstUInt8) -> VectorUInt8 {
        return 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
    {
        return Self.digest(data, t).copyToVectorUInt8()
    }

    fileprivate static func digest(_ data: SpanConstUInt8, hashFunction: HashFunction)
        -> any CryptoKit.Digest
    {
        switch hashFunction {
        case .sha256:
            return digest(data, SHA256.self)
        case .sha384:
            return digest(data, SHA384.self)
        case .sha512:
            return digest(data, SHA512.self)
        case .sha1:
            return digest(data, Insecure.SHA1.self)
        }
    }
}

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)
}
public enum ECImportReturnCode {
    case defaultValue
    case success
    case importFailed
}

public struct ECImportReturnValue {
    public var errorCode: ECImportReturnCode = .defaultValue
    public var key: ECKey? = nil
}

public struct ECKey {
    let key: ECKeyInternal
    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
    }
    public func toPub() -> ECKey {
        switch key {
        case .publicKey:
            return self
        case let .privateKey(v):
            switch v {
            case let .p256(u):
                return ECKey(publicKey: .p256(u.publicKey))
            case let .p384(u):
                return ECKey(publicKey: .p384(u.publicKey))
            case let .p521(u):
                return ECKey(publicKey: .p521(u.publicKey))
            }
        }
    }

    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
    }

    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
    }
    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
    }
    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
    }
    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
    }
    public func sign(message: SpanConstUInt8, hashFunction: HashFunction)
        -> CryptoOperationReturnValue
    {
        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
    }

    public func verify(
        message: SpanConstUInt8, signature: SpanConstUInt8, hashFunction: HashFunction
    ) -> CryptoOperationReturnValue {
        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
        }
    }

    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 let .p256(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 let .p384(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 let .p521(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
    }
}

public enum EdSigningAlgorithm {
    case ed25519
    case ed448
}

public enum EdKeyAgreementAlgorithm {
    case x25519
    case x448
}

public class EdKey {
    public static func generatePrivateKey(algo: EdSigningAlgorithm) -> VectorUInt8 {
        switch algo {
        case .ed25519:
            return Curve25519.Signing.PrivateKey().rawRepresentation.copyToVectorUInt8()
        case .ed448:
            return Data(count: 0).copyToVectorUInt8()
        }
    }

    public static func generatePrivateKeyKeyAgreement(algo: EdKeyAgreementAlgorithm) -> VectorUInt8
    {
        switch algo {
        case .x25519:
            return Curve25519.KeyAgreement.PrivateKey().rawRepresentation.copyToVectorUInt8()
        case .x448:
            return Data(count: 0).copyToVectorUInt8()
        }
    }

    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
    }

    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
    }
    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
        }

    }

    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
        }

    }

    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
    }
    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
    }

    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

    }
}

public class HMAC {
    public static func sign(key: SpanConstUInt8, data: SpanConstUInt8, hashFunction: HashFunction)
        -> VectorUInt8
    {
        switch hashFunction {
        case .sha1:
            return CryptoKit.HMAC<Insecure.SHA1>.authenticationCode(data: data, key: key)
        case .sha256:
            return CryptoKit.HMAC<SHA256>.authenticationCode(data: data, key: key)
        case .sha384:
            return CryptoKit.HMAC<SHA384>.authenticationCode(data: data, key: key)
        case .sha512:
            return CryptoKit.HMAC<SHA512>.authenticationCode(data: data, key: key)
        }
    }
    public static func verify(
        mac: SpanConstUInt8, key: SpanConstUInt8, data: SpanConstUInt8, hashFunction: HashFunction
    ) -> Bool {
        switch hashFunction {
        case .sha1:
            return CryptoKit.HMAC<Insecure.SHA1>.isValidAuthenticationCode(
                mac: mac, data: data, key: key)
        case .sha256:
            return CryptoKit.HMAC<SHA256>.isValidAuthenticationCode(mac: mac, data: data, key: key)
        case .sha384:
            return CryptoKit.HMAC<SHA384>.isValidAuthenticationCode(mac: mac, data: data, key: key)
        case .sha512:
            return CryptoKit.HMAC<SHA512>.isValidAuthenticationCode(mac: mac, data: data, key: key)
        }
    }
}

// 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

public class HKDF {
    public static func deriveBits(
        key: SpanConstUInt8, salt: SpanConstUInt8, info: SpanConstUInt8, outputBitCount: Int,
        hashFunction: HashFunction
    ) -> CryptoOperationReturnValue {
        var returnValue = CryptoOperationReturnValue()
        if outputBitCount <= 0 || outputBitCount % 8 != 0 {
             returnValue.errorCode = .InvalidArgument
            return returnValue
        } else {
             returnValue.errorCode = .Success
        }
        switch hashFunction {
        case .sha1:
            if outputBitCount > hkdfInputSizeLimitSHA1 {
                 returnValue.errorCode = .InvalidArgument
                break
            }
             returnValue.result =
                CryptoKit.HKDF<Insecure.SHA1>.deriveKey(
                    inputKeyMaterial: key, salt: salt, info: info,
                    outputByteCount: outputBitCount / 8)

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

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

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

        }
        return returnValue
    }
}
#endif