-
Notifications
You must be signed in to change notification settings - Fork 3
/
Sodium.swift
1052 lines (814 loc) · 26.1 KB
/
Sodium.swift
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Clibsodium
/**
A singleton instance of the `Clibsodium` wrapper.
*/
let sodium = Sodium()
/**
The default return value that indicates success of an operation performed
by `libsodium`.
*/
fileprivate let sSuccess: Int32 = 0
/**
A wrapper for `libsodium` that on one hand offers convenient access to the
`libsodium` bindings and on the other hand assures that `libsodium` was
initialized before actually invoking methods.
*/
struct Sodium {
/**
This initializes `libsodium`.
- see: [`libsodium` Usage](https://download.libsodium.org/doc/usage/)
*/
fileprivate init() {
let sAlreadyInitialized: Int32 = 1
let sFailure: Int32 = -1
let status = Clibsodium.sodium_init()
guard status != sFailure else {
fatalError("Failed to initialize libsodium!")
}
guard [sSuccess, sAlreadyInitialized].contains(status) else {
fatalError("Unhandled status: \(status)")
}
}
// MARK: - Generic Hashing
/**
Access to the wrapper for generic hashing.
*/
let generichash = SodiumGenericHash()
/**
A wrapper for generic hashing.
*/
struct SodiumGenericHash {
/**
The initializer is disabled.
*/
fileprivate init() {}
/**
The default key size in bytes.
*/
let defaultKeySizeInBytes = Clibsodium.crypto_generichash_keybytes()
/**
The maximum key size in bytes.
*/
let minimumKeySizeInBytes = Clibsodium.crypto_generichash_keybytes_min()
/**
The minimum key size in bytes.
*/
let maximumKeySizeInBytes = Clibsodium.crypto_generichash_keybytes_max()
/**
The default output size in bytes.
*/
let defaultOutputSizeInBytes = Clibsodium.crypto_generichash_bytes()
/**
The minimum output size in bytes.
*/
let minimumOutputSizeInBytes = Clibsodium.crypto_generichash_bytes_min()
/**
The maximum output size in bytes.
*/
let maximumOutputSizeInBytes = Clibsodium.crypto_generichash_bytes_max()
/**
Calculates a generic hash for a given memory region.
- precondition:
- `minimumOutputSizeInBytes` ≤ `outputSizeInBytes` ≤ `maximumOutputSizeInBytes`
- 0 ≤ `inputSizeInBytes`
- 0 ≤ `keySizeInBytes`
- `key` ≠ `nil` ⇒ `minimumKeySizeInBytes` ≤ `keySizeInBytes` ≤ `maximumKeySizeInBytes`
- parameters:
- outputSizeInBytes: The size of the output in bytes.
- input: A pointer to the memory region that should be hashed.
- inputSizeInBytes: The size of `input`.
- key: The key that should be used for keyed hashing.
- keySizeInBytes: The size of `key`.
- returns: The hash.
*/
func hash(outputSizeInBytes: Int, input: UnsafePointer<UInt8>, inputSizeInBytes: UInt64, key: UnsafePointer<UInt8>? = nil, keySizeInBytes: Int = 0) -> Bytes {
precondition(minimumOutputSizeInBytes <= outputSizeInBytes)
precondition(outputSizeInBytes <= maximumOutputSizeInBytes)
precondition(0 <= inputSizeInBytes)
precondition(0 <= keySizeInBytes)
precondition(key == nil || minimumKeySizeInBytes <= keySizeInBytes)
precondition(key == nil || keySizeInBytes <= maximumKeySizeInBytes)
var result = Bytes(count: outputSizeInBytes)
let status = Clibsodium.crypto_generichash(
&result,
outputSizeInBytes,
input,
inputSizeInBytes,
key,
keySizeInBytes
)
guard status == sSuccess else {
fatalError("Unhandled status: \(status)")
}
return result
}
/**
Calculates a generic hash for a given memory region.
- precondition: 0 ≤ `inputSizeInBytes`
- parameters:
- input: A pointer to the memory region that should be hashed.
- inputSizeInBytes: The size of `input`.
- returns: The hash.
*/
func hash(input: UnsafePointer<UInt8>, inputSizeInBytes: UInt64) -> Bytes {
return hash(outputSizeInBytes: defaultOutputSizeInBytes, input: input, inputSizeInBytes: inputSizeInBytes)
}
}
// MARK: - Key Derivation
/**
Access to the key derivation wrapper.
*/
let kdf = SodiumKeyDerivation()
/**
A wrapper for key derivation.
*/
struct SodiumKeyDerivation {
/**
The initializer is disabled.
*/
fileprivate init() {}
/**
The size of the master key in bytes.
*/
let masterKeySizeInBytes = Clibsodium.crypto_kdf_keybytes()
/**
The size of a sub key context in bytes.
*/
let contextSizeInBytes = Clibsodium.crypto_kdf_contextbytes()
/**
The minimum size of a derived key in bytes.
*/
let minimumSubKeySizeInBytes = Clibsodium.crypto_kdf_bytes_min()
/**
The maximum size of a derived key in bytes.
*/
let maximumSubKeySizeInBytes = Clibsodium.crypto_kdf_bytes_max()
/**
Generate a master key.
- parameters:
- pointer: The memory region where the key will be stored.
*/
func keygen(_ pointer: UnsafeMutablePointer<UInt8>) {
Clibsodium.crypto_kdf_keygen(pointer)
}
/**
Derive a sub key from a given master key.
- precondition:
- `minimumSubKeySizeInBytes` ≤ `subKeySizeInBytes` ≤ `maximumSubKeySizeInBytes`
- `context.count` = `contextSizeInBytes`
- size of `masterKey` = `masterKeySizeInBytes`
- parameters:
- subKey: The memory region where the sub key should be stored.
- subKeySizeInBytes: The size of `subKey` in bytes.
- subKeyId: The ID of the sub key.
- context: A context.
- masterKey: The master key.
*/
func derive(subKey: UnsafeMutablePointer<UInt8>, subKeySizeInBytes: Int, subKeyId: UInt64, context: Bytes, masterKey: UnsafePointer<UInt8>) {
precondition(minimumSubKeySizeInBytes <= subKeySizeInBytes)
precondition(subKeySizeInBytes <= maximumSubKeySizeInBytes)
precondition(context.count == contextSizeInBytes)
let status = context.withUnsafeBytes {
contextPtr in
return Clibsodium.crypto_kdf_derive_from_key(
subKey,
subKeySizeInBytes,
subKeyId,
contextPtr.map(Int8.init),
masterKey
)
}
guard status == sSuccess else {
fatalError("Unhandled status code: \(status)")
}
}
}
// MARK: - Key Exchange
/**
Access to the wrapper for key exchange.
*/
let kx = SodiumKeyExchange()
/**
A wrapper for key exchange.
*/
struct SodiumKeyExchange {
/**
The initializer is disabled.
*/
fileprivate init() {}
/**
The size of the secret key in bytes.
*/
let secretKeySizeInBytes = Clibsodium.crypto_kx_secretkeybytes()
/**
The size of the session key in bytes.
*/
let sessionKeySizeInBytes = Clibsodium.crypto_kx_sessionkeybytes()
/**
The size of the public key in bytes.
*/
let publicKeySizeInBytes = Clibsodium.crypto_kx_publickeybytes()
/**
Generate a keypair that can be used for exchanging keys.
- parameters:
- publicKeyPtr: The pointer to where the public key will be
stored.
- secretKeyPtr: The pointer to where the secret key will be
stored.
*/
func keypair(publicKeyPtr: UnsafeMutablePointer<UInt8>, secretKeyPtr: UnsafeMutablePointer<UInt8>) {
Clibsodium.crypto_kx_keypair(publicKeyPtr, secretKeyPtr)
}
/**
Calculate session keys for the client side.
- parameters:
- rxPtr: A pointer to where the session key, that is used to
receive data from the server, should be stored.
- txPtr: A pointer to where the session key, that is used to
send data to the server, should be stored.
- clientPk: A pointer to the client's public key.
- clientSk: A pointer to the client's secret key.
- serverPk: A pointer to the server's public key.
- returns:
`0` on success and `-1` if `serverPk` is not acceptible.
*/
func client_session_keys(
rxPtr: UnsafeMutablePointer<UInt8>,
txPtr: UnsafeMutablePointer<UInt8>,
clientPk: UnsafePointer<UInt8>,
clientSk: UnsafePointer<UInt8>,
serverPk: UnsafePointer<UInt8>
) -> Int32 {
return Clibsodium.crypto_kx_client_session_keys(rxPtr, txPtr, clientPk, clientSk, serverPk)
}
/**
Calculate session keys for the server side.
- parameters:
- rxPtr: A pointer to where the session key, that is used to
receive data from the client, should be stored.
- txPtr: A pointer to where the session key, that is used to
sen data to the client, should be stored.
- serverPk: A pointer to the server's public key.
- serverSk: A pointer to the server's secret key.
- clientPk: A pointer to the client's public key.
- returns:
`0` on success and `-1` if `clientPk` is not acceptible.
*/
func server_session_keys(
rxPtr: UnsafeMutablePointer<UInt8>,
txPtr: UnsafeMutablePointer<UInt8>,
serverPk: UnsafePointer<UInt8>,
serverSk: UnsafePointer<UInt8>,
clientPk: UnsafePointer<UInt8>
) -> Int32 {
return Clibsodium.crypto_kx_server_session_keys(rxPtr, txPtr, serverPk, serverSk, clientPk)
}
}
// MARK: - Memory
/**
Access to the secure memory wrapper.
*/
let memory = SodiumMemory()
/**
A wrapper for handling secure memory allocations.
- see: [`libsodium`: Securing memory allocations](https://download.libsodium.org/doc/helpers/memory_management.html)
*/
struct SodiumMemory {
/**
The initializer is disabled.
*/
fileprivate init() {}
/**
Allocates a guarded memory region of a given size.
- precondition: 0 ≤ `sizeInBytes`
- parameters:
- sizeInBytes: The size of the allocated memory.
- returns: A pointer to the guarded memory region.
*/
func allocate(sizeInBytes: Int) -> UnsafeMutableRawPointer {
precondition(0 <= sizeInBytes)
return Clibsodium.sodium_malloc(sizeInBytes)!
}
/**
Frees a guarded memory region.
- parameters:
- pointer: A pointer to the guarded memory region.
*/
func free(_ pointer: UnsafeMutableRawPointer) {
Clibsodium.sodium_free(pointer)
}
/**
Wipes a guarded memory region by overwriting it with zeroes.
- precondition: 0 ≤ `amountInBytes`
- parameters:
- pointer: A pointer to the guarded memory region.
- amountInBytes: The amount of bytes that should be zeroed,
starting at the beginning of the memory region.
*/
func wipe(_ pointer: UnsafeMutableRawPointer, amountInBytes: Int) {
precondition(0 <= amountInBytes)
Clibsodium.sodium_memzero(pointer, amountInBytes)
}
/**
Wipes a byte array by overwriting it with zeroes.
- parameters:
- bytes: A byte array.
*/
func wipe(_ bytes: inout Bytes) {
wipe(&bytes, amountInBytes: bytes.count)
}
/**
Compares two guarded memory regions in constant time.
- precondition: 0 ≤ `amountInBytes`
- parameters:
- lhs: A pointer to the guarded memory region.
- rhs: A pointer to the guarded memory region.
- amountInBytes: The amount of bytes that should be compared,
starting at the beginning of the memory region.
- returns: `true` if both regions are equal up to `amountInBytes`.
*/
func areEqual(_ lhs: UnsafeRawPointer, _ rhs: UnsafeRawPointer, amountInBytes: Int) -> Bool {
precondition(0 <= amountInBytes)
let sNotEqual: Int32 = -1
let status = Clibsodium.sodium_memcmp(lhs, rhs, amountInBytes)
guard status != sNotEqual else { return false }
guard status == sSuccess else {
fatalError("Unhandled status code: \(status)")
}
return true
}
/**
Makes a guarded memory region read-only.
- parameters:
- pointer: A pointer to the guarded memory region.
*/
func make_readonly(_ pointer: UnsafeMutableRawPointer) {
let status = Clibsodium.sodium_mprotect_readonly(pointer)
guard status == sSuccess else {
fatalError("Unhandled status code: \(status)")
}
}
/**
Makes a guarded memory region read-writable.
- parameters:
- pointer: A pointer to the guarded memory region.
*/
func make_readwritable(_ pointer: UnsafeMutableRawPointer) {
let status = Clibsodium.sodium_mprotect_readwrite(pointer)
guard status == sSuccess else {
fatalError("Unhandled status code: \(status)")
}
}
/**
Makes a guarded memory region inaccessible.
- parameters:
- pointer: A pointer to the guarded memory region.
*/
func make_inaccessible(_ pointer: UnsafeMutableRawPointer) {
let status = Clibsodium.sodium_mprotect_noaccess(pointer)
guard status == sSuccess else {
fatalError("Unhandled status code: \(status)")
}
}
}
// MARK: - Password Hashing
/**
Access to the password hashing wrapper
*/
let pwhash = SodiumPasswordHash()
/**
A wrapper for password hashing.
*/
struct SodiumPasswordHash {
/**
The initializer is disabled.
*/
fileprivate init() {}
/**
This is the fastest option and should be avoided if possible.
*/
let opslimit_interactive = Clibsodium.crypto_pwhash_opslimit_interactive()
/**
This takes about 0.7 seconds on a 2.8 Ghz Core i7 CPU.
*/
let opslimit_moderate = Clibsodium.crypto_pwhash_opslimit_moderate()
/**
This takes about 3.5 seconds on a 2.8 Ghz Core i7 CPU.
*/
let opslimit_sensitive = Clibsodium.crypto_pwhash_opslimit_sensitive()
/**
This requires about 64 MiB memory.
*/
let memlimit_interactive = Clibsodium.crypto_pwhash_memlimit_interactive()
/**
This requires about 256 MiB memory.
*/
let memlimit_moderate = Clibsodium.crypto_pwhash_memlimit_moderate()
/**
This requires about 1 GiB memory.
*/
let memlimit_sensitive = Clibsodium.crypto_pwhash_memlimit_sensitive()
/**
Size of a storable string in bytes.
*/
let sizeOfStorableStringInBytes = Clibsodium.crypto_pwhash_strbytes()
/**
Size of a salt used for password hashing in bytes.
*/
let sizeOfSaltInBytes = Clibsodium.crypto_pwhash_saltbytes()
/**
Minimum size for passwords.
*/
let minimumPasswordLength = Clibsodium.crypto_pwhash_passwd_min()
/**
Maximum size for passwords.
*/
let maximumPasswordLength = Clibsodium.crypto_pwhash_passwd_max()
/**
Minimum size of derived keys in bytes.
*/
let minimumKeySizeInBytes = Clibsodium.crypto_pwhash_bytes_min()
/**
Maximum size of derived keys in bytes.
*/
let maximumKeySizeInBytes = Clibsodium.crypto_pwhash_bytes_max()
/**
Creates a string that can be used for storing user passwords for the
purpose of authentication.
- precondition:
- 0 ≤ `passwordSizeInBytes`
- `opslimit` ∈ {`opslimit_interactive`, `opslimit_moderate`, `opslimit_sensitive`}
- `memlimit` ∈ {`memlimit_interactive`, `memlimit_moderate`, `memlimit_sensitive`}
- parameters:
- password: A pointer to the password.
- passwordSizeInBytes: The size of the password.
- opslimit: Complexity limit for hashing.
- memlimit: Memory limit for hashing.
- returns:
An ASCII-encoded string that can be stored, `nil` on failure.
*/
func storableString(password: UnsafePointer<Int8>, passwordSizeInBytes: UInt64, opslimit: Int, memlimit: Int) -> String? {
let sFailure: Int32 = -1
precondition(0 <= passwordSizeInBytes)
precondition([opslimit_interactive, opslimit_moderate, opslimit_sensitive].contains(opslimit))
precondition([memlimit_interactive, memlimit_moderate, memlimit_sensitive].contains(memlimit))
var result = Bytes(count: sizeOfStorableStringInBytes).map(Int8.init)
let status = Clibsodium.crypto_pwhash_str(
&result,
password,
passwordSizeInBytes,
UInt64(opslimit),
memlimit
)
guard status != sFailure else { return nil }
guard status == sSuccess else {
fatalError("Unhandled status: \(status)")
}
return String.init(bytes: result.map(UInt8.init), encoding: .ascii)!
}
/**
Check if a password is verifying a storable string.
- precondition:
- `storableString` is ASCII-encoded
- 0 ≤ `passwordSizeInBytes`
- parameters:
- storableString: The storable string.
- password: A pointer to the password.
- passwordSizeInBytes: The size of the password in bytes.
- returns: `true` if `password` verifies `storableString`.
*/
func isVerifying(storableString: String, password: UnsafePointer<Int8>, passwordSizeInBytes: UInt64) -> Bool {
let sVerificationFailed: Int32 = -1
precondition(storableString.data(using: .ascii) != nil)
precondition(0 <= passwordSizeInBytes)
let status = storableString.data(using: .ascii)!.withUnsafeBytes {
strPtr in
return Clibsodium.crypto_pwhash_str_verify(strPtr, password, passwordSizeInBytes)
}
guard status != sVerificationFailed else { return false }
guard status == sSuccess else {
fatalError("Unhandled status: \(status)")
}
return true
}
/**
Derive a key from a given password with a given salt.
- parameters:
- key: A pointer to the memory, where the derived key should be
written.
- sizeInBytes: The size of the memory area reserved for the
`key`.
- from password: A pointer to the password, from which the `key`
will be derived.
- passwordSizeInBytes: The size of the `password` in bytes.
- salt: The salt that will be used in order to prevent rainbow
table attacks.
- opslimit: Complexity limit for hashing.
- memlimit: Memory limit for hashing.
*/
func derive(key: UnsafeMutablePointer<UInt8>, sizeInBytes: UInt64, from password: UnsafePointer<Int8>, passwordSizeInBytes: UInt64, salt: Bytes, opslimit: UInt64, memlimit: Int, algorithm: Int32 = Clibsodium.crypto_pwhash_alg_default()) {
let sComputationFailed = -1
precondition(minimumKeySizeInBytes <= sizeInBytes)
precondition(sizeInBytes <= maximumKeySizeInBytes)
precondition(minimumPasswordLength <= passwordSizeInBytes)
precondition(passwordSizeInBytes <= maximumKeySizeInBytes)
precondition(Clibsodium.crypto_pwhash_opslimit_min() <= opslimit)
precondition(opslimit <= Clibsodium.crypto_pwhash_opslimit_max())
precondition(Clibsodium.crypto_pwhash_memlimit_min() <= memlimit)
precondition(memlimit <= Clibsodium.crypto_pwhash_memlimit_max())
let status = Clibsodium.crypto_pwhash(key, sizeInBytes, password, passwordSizeInBytes, salt, opslimit, memlimit, algorithm)
guard status != sComputationFailed else {
fatalError("Computation failed. This might have been caused by insufficient memory.")
}
guard status == sSuccess else {
fatalError("Unhandled status: \(status)")
}
}
}
// MARK: - Random
/**
Access to the wrapper for secure random byte generation.
*/
let random = SodiumRandom()
/**
A wrapper for generating random bytes securely.
*/
struct SodiumRandom {
/**
The initializer is disabled.
*/
fileprivate init() {}
/**
Write random bytes into a memory region.
- precondition: 0 ≤ `sizeInBytes`
- parameters:
- pointer: A pointer to the memory region.
- sizeInBytes: The amount of bytes that should be written.
*/
func bytes(_ pointer: UnsafeMutableRawPointer, sizeInBytes: Int) {
precondition(0 <= sizeInBytes)
Clibsodium.randombytes_buf(pointer, sizeInBytes)
}
/**
Generate a randomly filled byte array.
- parameters:
- count: The size of the byte array in bytes.
- returns: The byte array.
*/
func bytes(count: Int) -> Bytes {
var result = Bytes(count: count)
bytes(&result, sizeInBytes: count)
return result
}
/**
Generate a random number.
- returns: The random number.
*/
func number() -> UInt32 {
return Clibsodium.randombytes_random()
}
/**
Generates a random number with uniform distribution.
- parameters:
- upperBound: The upper bound.
- returns: A random number between 0 and `upperBound`.
*/
func uniform(upperBound: UInt32) -> UInt32 {
return Clibsodium.randombytes_uniform(upperBound)
}
}
// MARK: - Symmetric Encryption (SecretBox)
/**
Access to the secret box wrapper.
*/
let secretbox = SodiumSecretBox()
/**
A wrapper for symmetric encryption.
*/
struct SodiumSecretBox {
/**
The initializer is disabled.
*/
fileprivate init() {}
/**
The size of the key in bytes.
*/
let sizeOfKeyInBytes = Clibsodium.crypto_secretbox_keybytes()
/**
The size of the nonce in bytes.
*/
let sizeOfNonceInBytes = Clibsodium.crypto_secretbox_noncebytes()
/**
The size of the message authentication code (MAC) in bytes.
*/
let sizeOfMacInBytes = Clibsodium.crypto_secretbox_macbytes()
/**
Generates a new symmetric key.
- parameters:
- pointer: The memory region where the key will be stored.
*/
func keygen(_ pointer: UnsafeMutablePointer<UInt8>) {
Clibsodium.crypto_secretbox_keygen(pointer)
}
/**
Encrypt data.
- precondition:
- size of `nonce` = `sizeOfNonceInBytes`
- size of `key` = `sizeOfKeyInBytes`
- postcondition:
- `result.0.count` = `sizeOfMacInBytes`
- `result.1.count` = `plaintext.count`
- parameters:
- plaintext: The text that should be encrypted.
- nonce: A pointer to the nonce.
- key: A pointer to the key.
- returns: A tuple (MAC, ciphertext).
*/
func encrypt(plaintext: Bytes, nonce: UnsafePointer<UInt8>, key: UnsafePointer<UInt8>) -> (Bytes, Bytes) {
var ciphertext = Bytes(count: plaintext.count)
var mac = Bytes(count: sizeOfMacInBytes)
let status = Clibsodium.crypto_secretbox_detached(
&ciphertext,
&mac,
plaintext,
UInt64(plaintext.count),
nonce,
key
)
guard status == sSuccess else {
fatalError("Unhandled status: \(status)")
}
return (mac, ciphertext)
}
/**
Decrypt data.
- precondition:
- size of `mac` = `sizeOfMacInBytes`
- size of `nonce` = `sizeOfNonceInBytes`
- size of `key` = `sizeOfKeyInBytes`
- postcondition: `result.count` = `ciphertext.count`
- parameters:
- ciphertext: The ciphertext.
- mac: A pointer to the message authentication code (MAC).
- nonce: A pointer to the nonce.
- key: A pointer to the key.
- returns:
The plaintext, `nil` if the integrity of the authenticated
ciphertext could not be verified.
*/
func decrypt(ciphertext: Bytes, mac: UnsafePointer<UInt8>, nonce: UnsafePointer<UInt8>, key: UnsafePointer<UInt8>) -> Bytes? {
let sVerificationFailed: Int32 = -1
var plaintext = Bytes(count: ciphertext.count)
let status = Clibsodium.crypto_secretbox_open_detached(
&plaintext,
ciphertext,
mac,
UInt64(ciphertext.count),
nonce,
key
)
guard status != sVerificationFailed else { return nil }
guard status == sSuccess else {
fatalError("Unhandled status: \(status)")
}
return plaintext
}
}
// MARK: - Padding
/**
Add padding to protect message lengths.
- warning: Padding has to be applied to plaintext before encryption.
- precondition: 0 < `blockSize`
- postcondition: `result.count` % `blockSize` = 0
- parameters:
- unpadded: The unpadded plaintext bytes.
- blockSize: The block size in bytes.
- returns: The padded plaintext bytes.
*/
func pad(unpadded: Bytes, blockSize: Int) -> Bytes {
precondition(0 < blockSize)
let sBufferTooSmall = -1
let bufferLength = ((unpadded.count / blockSize) + 1) * blockSize
var buffer = unpadded + Bytes(count: bufferLength - unpadded.count)
var paddedLength = 0
let status = sodium_pad(&paddedLength, &buffer, unpadded.count, blockSize, bufferLength)
guard status != sBufferTooSmall else {
fatalError("Reserved buffer is too small.")
}
guard status == sSuccess else {
fatalError("Unhandled status: \(status)")
}
return buffer[..<paddedLength].bytes
}
/**
Add padding to protect message lengths.
- warning: Padding has to be applied to plaintext before encryption.
- precondition: 0 < `blockSize`
- postcondition: `result.count` % `blockSize` = 0
- parameters:
- unpadded: The unpadded plaintext bytes.
- blockSize: The block size in bytes.
- returns: The padded plaintext bytes.
*/
func unpad(padded: Bytes, blockSize: Int) -> Bytes? {
precondition(0 < blockSize)
let sInvalidPadding = -1
var unpaddedLength = 0
let status = sodium_unpad(&unpaddedLength, padded, padded.count, blockSize)
guard status != sInvalidPadding else {
return nil
}
guard status == sSuccess else {
fatalError("Unhandled status: \(status)")
}
return padded[..<unpaddedLength].bytes
}
// MARK: - Utilities
/**
Converts hex-characters to a byte array.
- parameters:
- hex: The string.
- ignore: A string containing characters that should be ignored,
e.g., this is useful to ignore the colon if `hex` is "00:11".
- returns: The byte array.
*/
func hex2bin(_ hex: String, ignore: String? = nil) -> Bytes? {
let hexBytes = hex.utf8Bytes.map(Int8.init)
let reservedCapacity = hexBytes.count / 2
var result = Bytes(count: reservedCapacity)
var bytesWritten: size_t = 0
let ignoreBytes = ignore?.cString(using: .utf8)
let status = Clibsodium.sodium_hex2bin(
&result,
reservedCapacity,
hexBytes,
hexBytes.count,
ignoreBytes,
&bytesWritten,
nil
)
guard status == sSuccess else {
return nil
}
return result[..<bytesWritten].bytes
}
/**
Converts a byte array to a hex-encoded string.
- parameters:
- bin: The byte array.
- returns: The hex-encoded string.
*/
func bin2hex(_ bin: Bytes) -> String {
let sizeOfResultInBytes = bin.count * 2 + 1
var result = Bytes(count: sizeOfResultInBytes).map(Int8.init)
Clibsodium.sodium_bin2hex(
&result,
sizeOfResultInBytes,
bin,
bin.count
)
return String(validatingUTF8: result)!
}
/**