aboutsummaryrefslogblamecommitdiffstats
path: root/library/sodium-plus/lib/sodiumplus.js
blob: 7f5bc4c080f3f6ad69c6440e5ab1b7dac07d8a1c (plain) (tree)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212



























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                             
const Backend = require('./backend');
const CryptographyKey = require('./cryptography-key');
const Ed25519SecretKey = require('./keytypes/ed25519sk');
const Ed25519PublicKey = require('./keytypes/ed25519pk');
const LibsodiumWrappersBackend = require('./backend/libsodium-wrappers');
const SodiumError = require('./sodium-error');
const SodiumNativeBackend = require('./backend/sodiumnative');
const X25519PublicKey = require('./keytypes/x25519pk');
const X25519SecretKey = require('./keytypes/x25519sk');
const Util = require('./util');

/* istanbul ignore if */
if (typeof (Buffer) === 'undefined') {
    let Buffer = require('buffer/').Buffer;
}

class SodiumPlus {
    constructor(backend) {
        /* istanbul ignore if */
        if (!(backend instanceof Backend)) {
            throw new TypeError('Backend object must implement the backend function');
        }
        this.backend = backend;
        Util.populateConstants(this);
    }

    /**
     * Returns the name of the current active backend.
     * This method is NOT async.
     *
     * @return {string}
     */
    getBackendName() {
        return this.backend.backendName;
    }

    /**
     * Is this powered by sodium-native?
     * This method is NOT async.
     *
     * @return {boolean}
     */
    isSodiumNative() {
        return (this.backend instanceof SodiumNativeBackend);
    }

    /**
     * Is this powered by libsodium-wrappers?
     * This method is NOT async.
     *
     * @return {boolean}
     */
    isLibsodiumWrappers() {
        return (this.backend instanceof LibsodiumWrappersBackend);
    }

    /**
     * Automatically select a backend.
     *
     * @return {Promise<SodiumPlus>}
     */
    static async auto() {
        let backend;
        try {
            backend = await SodiumNativeBackend.init();
        } catch (e) {
            backend = await LibsodiumWrappersBackend.init();
        }
        /* istanbul ignore if */
        if (!backend) {
            backend = await LibsodiumWrappersBackend.init();
        }
        Util.populateConstants(backend);
        return new SodiumPlus(backend);
    }

    /**
     * If our backend isn't defined, it will trigger an autoload.
     *
     * Mostly used internally. `await SodiumPlus.auto()` provides the same
     * exact guarantee as this method.
     *
     * @return {Promise<void>}
     */
    async ensureLoaded() {
        /* istanbul ignore if */
        if (typeof (this.backend) === 'undefined') {
            try {
                await SodiumPlus.auto();
            } catch (e) {
                this.backend = await LibsodiumWrappersBackend.init();
            }
        }
    }

    /**
     * Decrypt a message (and optional associated data) with XChaCha20-Poly1305
     *
     * @param {String|Buffer} ciphertext
     * @param {String|Buffer} nonce
     * @param {CryptographyKey} key
     * @param {String|Buffer} assocData
     * @return {Promise<Buffer>}
     * @throws {SodiumError}
     */
    async crypto_aead_xchacha20poly1305_ietf_decrypt(ciphertext, nonce, key, assocData = '') {
        await this.ensureLoaded();
        if (nonce.length !== 24) {
            throw new SodiumError('Argument 2 must be 24 bytes');
        }
        if (!(key instanceof CryptographyKey)) {
            throw new TypeError('Argument 3 must be an instance of CryptographyKey');
        }
        return await this.backend.crypto_aead_xchacha20poly1305_ietf_decrypt(
            await Util.toBuffer(ciphertext),
            assocData.length > 0 ? await Util.toBuffer(assocData) : null,
            await Util.toBuffer(nonce),
            key
        );
    }

    /**
     * Encrypt a message (and optional associated data) with XChaCha20-Poly1305.
     *
     * Throws a SodiumError if an invalid ciphertext/AAD is provided for this
     * nonce and key.
     *
     * @param {String|Buffer} plaintext
     * @param {String|Buffer} nonce
     * @param {CryptographyKey} key
     * @param {String|Buffer} assocData
     * @return {Promise<Buffer>}
     * @throws {SodiumError}
     */
    async crypto_aead_xchacha20poly1305_ietf_encrypt(plaintext, nonce, key, assocData = '') {
        await this.ensureLoaded();
        if (nonce.length !== 24) {
            throw new SodiumError('Argument 2 must be 24 bytes');
        }
        if (!(key instanceof CryptographyKey)) {
            throw new TypeError('Argument 3 must be an instance of CryptographyKey');
        }

        return await this.backend.crypto_aead_xchacha20poly1305_ietf_encrypt(
            await Util.toBuffer(plaintext),
            assocData.length > 0 ? await Util.toBuffer(assocData) : null,
            await Util.toBuffer(nonce),
            key
        );
    }

    /**
     * Generate an XChaCha20-Poly1305 key.
     *
     * @return {Promise<CryptographyKey>}
     */
    async crypto_aead_xchacha20poly1305_ietf_keygen() {
        return new CryptographyKey(await this.backend.randombytes_buf(32));
    }

    /**
     * Get an authenticator for a message for a given key.
     *
     * Algorithm: HMAC-SHA512 truncated to 32 bytes.
     *
     * @param {string|Buffer} message
     * @param {CryptographyKey} key
     * @return {Promise<Buffer>}
     */
    async crypto_auth(message, key) {
        await this.ensureLoaded();
        if (!(key instanceof CryptographyKey)) {
            throw new TypeError('Argument 2 must be an instance of CryptographyKey');
        }
        await this.ensureLoaded();
        return await this.backend.crypto_auth(
            await Util.toBuffer(message),
            key
        );
    }

    /**
     * @return {Promise<CryptographyKey>}
     */
    async crypto_auth_keygen() {
        return new CryptographyKey(await this.backend.randombytes_buf(32));
    }

    /**
     * Verify an authenticator for a message for a given key.
     *
     * @param {string|Buffer} message
     * @param {CryptographyKey} key
     * @param {Buffer} mac
     * @return {Promise<boolean>}
     */
    async crypto_auth_verify(message, key, mac) {
        await this.ensureLoaded();
        if (!(key instanceof CryptographyKey)) {
            throw new TypeError('Argument 2 must be an instance of CryptographyKey');
        }
        await this.ensureLoaded();
        return await this.backend.crypto_auth_verify(
            await Util.toBuffer(mac),
            await Util.toBuffer(message),
            key
        );
    }

    /**
     * Public-key authenticated encryption.
     *
     * @param {string|Buffer} plaintext
     * @param {Buffer} nonce
     * @param {X25519SecretKey} myPrivateKey
     * @param {X25519PublicKey} theirPublicKey
     * @return {Promise<Buffer>}
     */
    async crypto_box(plaintext, nonce, myPrivateKey, theirPublicKey) {
        await this.ensureLoaded();
        if (!(myPrivateKey instanceof X25519SecretKey)) {
            throw new TypeError('Argument 3 must be an instance of X25519SecretKey');
        }
        if (!(theirPublicKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 4 must be an instance of X25519PublicKey');
        }
        nonce = await Util.toBuffer(nonce);
        if (nonce.length !== 24) {
            throw new SodiumError('Nonce must be a buffer of exactly 24 bytes');
        }
        return this.backend.crypto_box(
            await Util.toBuffer(plaintext),
            await Util.toBuffer(nonce),
            myPrivateKey,
            theirPublicKey
        );
    }

    /**
     * Public-key authenticated decryption.
     *
     * @param {Buffer} ciphertext
     * @param {Buffer} nonce
     * @param {X25519SecretKey} myPrivateKey
     * @param {X25519PublicKey} theirPublicKey
     * @return {Promise<Buffer>}
     */
    async crypto_box_open(ciphertext, nonce, myPrivateKey, theirPublicKey) {
        await this.ensureLoaded();
        if (!(myPrivateKey instanceof X25519SecretKey)) {
            throw new TypeError('Argument 3 must be an instance of X25519SecretKey');
        }
        if (!(theirPublicKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 4 must be an instance of X25519PublicKey');
        }
        ciphertext = await Util.toBuffer(ciphertext);
        if (ciphertext.length < 16) {
            throw new SodiumError('Ciphertext must be a buffer of at least 16 bytes');
        }
        nonce = await Util.toBuffer(nonce);
        if (nonce.length !== 24) {
            throw new SodiumError('Nonce must be a buffer of exactly 24 bytes');
        }
        return this.backend.crypto_box_open(
            ciphertext,
            nonce,
            myPrivateKey,
            theirPublicKey
        );
    }

    /**
     * @return {Promise<CryptographyKey>}
     */
    async crypto_box_keypair() {
        await this.ensureLoaded();
        return this.backend.crypto_box_keypair();
    }

    /**
     * Combine two X25519 keys (secret, public) into a keypair object.
     *
     * @param {X25519SecretKey} sKey
     * @param {X25519PublicKey} pKey
     * @return {Promise<CryptographyKey>}
     */
    async crypto_box_keypair_from_secretkey_and_publickey(sKey, pKey) {
        await this.ensureLoaded();
        if (!(sKey instanceof X25519SecretKey)) {
            throw new TypeError('Argument 1 must be an instance of X25519SecretKey');
        }
        if (!(pKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 2 must be an instance of X25519PublicKey');
        }
        return await this.backend.crypto_box_keypair_from_secretkey_and_publickey(sKey, pKey);
    }

    /**
     * Extract the secret key from an X25519 keypair object.
     *
     * @param {CryptographyKey} keypair
     * @return {Promise<X25519SecretKey>}
     */
    async crypto_box_secretkey(keypair) {
        if (keypair.getLength()!== 64) {
            throw new SodiumError('Keypair must be 64 bytes');
        }
        return new X25519SecretKey(
            Buffer.from(keypair.getBuffer().slice(0, 32))
        );
    }

    /**
     * Extract the public key from an X25519 keypair object.
     *
     * @param {CryptographyKey} keypair
     * @return {Promise<X25519PublicKey>}
     */
    async crypto_box_publickey(keypair) {
        if (keypair.getLength() !== 64) {
            throw new SodiumError('Keypair must be 64 bytes');
        }
        return new X25519PublicKey(
            Buffer.from(keypair.getBuffer().slice(32, 64))
        );
    }

    /**
     * Derive the public key from a given X25519 secret key.
     *
     * @param {X25519SecretKey} secretKey
     * @return {Promise<X25519PublicKey>}
     */
    async crypto_box_publickey_from_secretkey(secretKey) {
        await this.ensureLoaded();
        if (!(secretKey instanceof X25519SecretKey)) {
            throw new TypeError('Argument 1 must be an instance of X25519SecretKey');
        }
        return new X25519PublicKey(
            await this.backend.crypto_scalarmult_base(secretKey)
        );
    }

    /**
     * Anonymous public-key encryption. (Message integrity is still assured.)
     *
     * @param {string|Buffer} plaintext
     * @param {X25519PublicKey} publicKey
     * @return {Promise<Buffer>}
     */
    async crypto_box_seal(plaintext, publicKey) {
        await this.ensureLoaded();
        if (!(publicKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 2 must be an instance of X25519PublicKey');
        }
        return await this.backend.crypto_box_seal(plaintext, publicKey);
    }

    /**
     * Anonymous public-key decryption. (Message integrity is still assured.)
     *
     * @param {Buffer} ciphertext
     * @param {X25519PublicKey} publicKey
     * @param {X25519SecretKey} secretKey
     * @return {Promise<Buffer>}
     */
    async crypto_box_seal_open(ciphertext, publicKey, secretKey) {
        await this.ensureLoaded();
        if (!(publicKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 2 must be an instance of X25519PublicKey');
        }
        if (!(secretKey instanceof X25519SecretKey)) {
            throw new TypeError('Argument 3 must be an instance of X25519SecretKey');
        }
        return await this.backend.crypto_box_seal_open(
            await Util.toBuffer(ciphertext),
            publicKey,
            secretKey
        );
    }

    /**
     * Generic-purpose cryptographic hash.
     *
     * @param {string|Buffer} message
     * @param {CryptographyKey|null} key
     * @param {number} outputLength
     * @return {Promise<Buffer>}
     */
    async crypto_generichash(message, key = null, outputLength = 32) {
        await this.ensureLoaded();
        return await this.backend.crypto_generichash(message, key, outputLength);
    }

    /**
     * Initialize a BLAKE2 hash context for stream hashing.
     *
     * @param {CryptographyKey|null} key
     * @param {number} outputLength
     * @return {Promise<Buffer>}
     */
    async crypto_generichash_init(key = null, outputLength = 32) {
        await this.ensureLoaded();
        return await this.backend.crypto_generichash_init(key, outputLength);
    }


    /**
     * Update the BLAKE2 hash state with a block of data.
     *
     * @param {*} state
     * @param {string|Buffer} message
     * @return {Promise<*>}
     */
    async crypto_generichash_update(state, message) {
        await this.ensureLoaded();
        return await this.backend.crypto_generichash_update(state, message);
    }

    /**
     * Obtain the final BLAKE2 hash output.
     *
     * @param {*} state
     * @param {number} outputLength
     * @return {Promise<Buffer>}
     */
    async crypto_generichash_final(state, outputLength = 32) {
        await this.ensureLoaded();
        return await this.backend.crypto_generichash_final(state, outputLength);
    }

    /**
     * Generate a 256-bit random key for BLAKE2.
     *
     * @return {Promise<CryptographyKey>}
     */
    async crypto_generichash_keygen() {
        return new CryptographyKey(
            await this.backend.randombytes_buf(this.CRYPTO_GENERICHASH_KEYBYTES)
        );
    }

    /**
     * Derive a subkey from a master key.
     *
     * @param {number} length
     * @param {number} subKeyId
     * @param {string|Buffer} context
     * @param {CryptographyKey} key
     * @return {Promise<CryptographyKey>}
     */
    async crypto_kdf_derive_from_key(length, subKeyId, context, key) {
        await this.ensureLoaded();
        if (length < 1) {
            throw new SodiumError('Length must be a positive integer.');
        }
        if (subKeyId < 0) {
            throw new SodiumError('Key ID must be an unsigned integer');
        }
        return await this.backend.crypto_kdf_derive_from_key(
            length,
            subKeyId,
            context,
            key
        );
    }

    /**
     * Generate a 256-bit random key for our KDF.
     *
     * @return {Promise<CryptographyKey>}
     */
    async crypto_kdf_keygen() {
        return new CryptographyKey(
            await this.backend.randombytes_buf(this.CRYPTO_KDF_KEYBYTES)
        );
    }

    /**
     * This is functionally identical to crypto_box_keypair().
     *
     * @return {Promise<CryptographyKey>}
     */
    async crypto_kx_keypair() {
        return this.crypto_box_keypair();
    }

    /**
     * Generate an X25519 keypair from a seed.
     *
     * @param {string|Buffer} seed
     * @return {Promise<CryptographyKey>}
     */
    async crypto_kx_seed_keypair(seed) {
        await this.ensureLoaded();
        const sk = await this.backend.crypto_generichash(seed, null, this.CRYPTO_KX_SECRETKEYBYTES);
        const pk = await this.backend.crypto_scalarmult_base(new CryptographyKey(sk));
        return new CryptographyKey(Buffer.concat([sk, pk]));
    }

    /**
     * Perform a key exchange from the client's perspective.
     *
     * Returns an array of two CryptographyKey objects.
     *
     * The first is meant for data sent from the server to the client (incoming decryption).
     * The second is meant for data sent from the client to the server (outgoing encryption).
     *
     * @param {X25519PublicKey} clientPublicKey
     * @param {X25519SecretKey} clientSecretKey
     * @param {X25519PublicKey} serverPublicKey
     * @return {Promise<CryptographyKey[]>}
     */
    async crypto_kx_client_session_keys(clientPublicKey, clientSecretKey, serverPublicKey) {
        await this.ensureLoaded();
        if (!(clientPublicKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 1 must be an instance of X25519PublicKey');
        }
        if (!(clientSecretKey instanceof X25519SecretKey)) {
            throw new TypeError('Argument 2 must be an instance of X25519SecretKey');
        }
        if (!(serverPublicKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 3 must be an instance of X25519PublicKey');
        }
        return this.backend.crypto_kx_client_session_keys(clientPublicKey, clientSecretKey, serverPublicKey);
    }

    /**
     * Perform a key exchange from the server's perspective.
     *
     * Returns an array of two CryptographyKey objects.
     *
     * The first is meant for data sent from the client to the server (incoming decryption).
     * The second is meant for data sent from the server to the client (outgoing encryption).
     *
     * @param {X25519PublicKey} serverPublicKey
     * @param {X25519SecretKey} serverSecretKey
     * @param {X25519PublicKey} clientPublicKey
     * @return {Promise<CryptographyKey[]>}
     */
    async crypto_kx_server_session_keys(serverPublicKey, serverSecretKey, clientPublicKey) {
        await this.ensureLoaded();
        if (!(serverPublicKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 1 must be an instance of X25519PublicKey');
        }
        if (!(serverSecretKey instanceof X25519SecretKey)) {
            throw new TypeError('Argument 2 must be an instance of X25519SecretKey');
        }
        if (!(clientPublicKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 3 must be an instance of X25519PublicKey');
        }
        return this.backend.crypto_kx_server_session_keys(serverPublicKey, serverSecretKey, clientPublicKey);
    }

    /**
     * @param {string|Buffer} message
     * @param {CryptographyKey} key
     * @return {Promise<Buffer>}
     */
    async crypto_onetimeauth(message, key) {
        if (!(key instanceof CryptographyKey)) {
            throw new TypeError('Argument 2 must be an instance of CryptographyKey');
        }
        return await this.backend.crypto_onetimeauth(await Util.toBuffer(message), key);
    }

    /**
     * @param {string|Buffer} message
     * @param {CryptographyKey} key
     * @param {Buffer} tag
     * @return {Promise<boolean>}
     */
    async crypto_onetimeauth_verify(message, key, tag) {
        if (!(key instanceof CryptographyKey)) {
            throw new TypeError('Argument 2 must be an instance of CryptographyKey');
        }
        return await this.backend.crypto_onetimeauth_verify(
            await Util.toBuffer(message),
            key,
            await Util.toBuffer(tag)
        );
    }

    /**
     * @return {Promise<CryptographyKey>}
     */
    async crypto_onetimeauth_keygen() {
        return new CryptographyKey(
            await this.backend.randombytes_buf(32)
        );
    }

    /**
     * Derive a cryptography key from a password and salt.
     *
     * @param {number} length
     * @param {string|Buffer} password
     * @param {Buffer} salt
     * @param {number} opslimit
     * @param {number} memlimit
     * @param {number|null} algorithm
     * @return {Promise<CryptographyKey>}
     */
    async crypto_pwhash(length, password, salt, opslimit, memlimit, algorithm = null) {
        await this.ensureLoaded();
        /* istanbul ignore if */
        if (!algorithm) {
            algorithm = this.CRYPTO_PWHASH_ALG_DEFAULT;
        }
        return new CryptographyKey(
            await this.backend.crypto_pwhash(
                length,
                await Util.toBuffer(password),
                await Util.toBuffer(salt),
                opslimit,
                memlimit,
                algorithm
            )
        );
    }

    /**
     * Get a password hash (in a safe-for-storage format)
     *
     * @param {string|Buffer} password
     * @param {number} opslimit
     * @param {number} memlimit
     * @return {Promise<string>}
     */
    async crypto_pwhash_str(password, opslimit, memlimit) {
        await this.ensureLoaded();
        return await this.backend.crypto_pwhash_str(password, opslimit, memlimit);
    }

    /**
     * Verify a password against a known password hash
     *
     * @param {string|Buffer} password
     * @param {string|Buffer} hash
     * @return {Promise<boolean>}
     */
    async crypto_pwhash_str_verify(password, hash) {
        await this.ensureLoaded();
        return await this.backend.crypto_pwhash_str_verify(password, hash);
    }

    /**
     * Does this password need to be rehashed?
     *
     * @param {string|Buffer} hash
     * @param {number} opslimit
     * @param {number} memlimit
     * @return {Promise<boolean>}
     */
    async crypto_pwhash_str_needs_rehash(hash, opslimit, memlimit) {
        await this.ensureLoaded();
        return await this.backend.crypto_pwhash_str_needs_rehash(hash, opslimit, memlimit);
    }

    /**
     * Elliptic Curve Diffie-Hellman key exchange
     *
     * @param {X25519SecretKey} secretKey
     * @param {X25519PublicKey} publicKey
     * @return {Promise<CryptographyKey>}
     */
    async crypto_scalarmult(secretKey, publicKey) {
        await this.ensureLoaded();
        if (!(secretKey instanceof X25519SecretKey)) {
            throw new TypeError('Argument 1 must be an instance of X25519SecretKey');
        }
        if (!(publicKey instanceof X25519PublicKey)) {
            throw new TypeError('Argument 2 must be an instance of X25519PublicKey');
        }
        return await this.backend.crypto_scalarmult(secretKey, publicKey);
    }

    /**
     * Generate an X25519PublicKey from an X25519SecretKey
     *
     * @param {X25519SecretKey} secretKey
     * @return {Promise<X25519PublicKey>}
     */
    async crypto_scalarmult_base(secretKey) {
        await this.ensureLoaded();
        if (!(secretKey instanceof X25519SecretKey)) {
            throw new TypeError('Argument 1 must be an instance of X25519SecretKey');
        }
        return new X25519PublicKey(
            await this.backend.crypto_scalarmult_base(secretKey)
        );
    }

    /**
     * Shared-key authenticated encryption
     *
     * @param {string|Buffer} plaintext
     * @param {Buffer} nonce
     * @param {CryptographyKey} key
     * @return {Promise<Buffer>}
     */
    async crypto_secretbox(plaintext, nonce, key) {
        await this.ensureLoaded();
        if (key.isEd25519Key() || key.isX25519Key()) {
            throw new TypeError('Argument 3 must not be an asymmetric key');
        }
        nonce = await Util.toBuffer(nonce);
        if (nonce.length !== 24) {
            throw new SodiumError('Nonce must be a buffer of exactly 24 bytes');
        }

        return await this.backend.crypto_secretbox(
            plaintext,
            nonce,
            key
        );
    }

    /**
     * Shared-key authenticated decryption
     *
     * @param {Buffer} ciphertext
     * @param {Buffer} nonce
     * @param {CryptographyKey} key
     * @return {Promise<Buffer>}
     */
    async crypto_secretbox_open(ciphertext, nonce, key) {
        await this.ensureLoaded();
        if (key.isEd25519Key() || key.isX25519Key()) {
            throw new TypeError('Argument 3 must not be an asymmetric key');
        }
        ciphertext = await Util.toBuffer(ciphertext);
        if (ciphertext.length < 16) {
            throw new SodiumError('Ciphertext must be a buffer of at least 16 bytes');
        }
        nonce = await Util.toBuffer(nonce);
        if (nonce.length !== 24) {
            throw new SodiumError('Nonce must be a buffer of exactly 24 bytes');
        }
        return await this.backend.crypto_secretbox_open(
            ciphertext,
            nonce,
            key
        );
    }

    /**
     * Generate a key for shared-key authenticated encryption.
     *
     * @return {Promise<CryptographyKey>}
     */
    async crypto_secretbox_keygen() {
        return new CryptographyKey(
            await this.backend.randombytes_buf(this.CRYPTO_SECRETBOX_KEYBYTES)
        );
    }

    /**
     * Internalize the internal state and a random header for stream encryption.
     *
     * @param {CryptographyKey} key
     * @return {Promise<array>}
     */
    async crypto_secretstream_xchacha20poly1305_init_push(key) {
        await this.ensureLoaded();
        if (!(key instanceof CryptographyKey)) {
            throw new TypeError('Key must be an instance of CryptographyKey');
        }
        if (key.getLength() !== 32) {
            throw new SodiumError('crypto_secretstream keys must be 32 bytes long');
        }
        const [state, header] = await this.backend.crypto_secretstream_xchacha20poly1305_init_push(key);
        return Object.freeze({
            header: header,
            push: this.crypto_secretstream_xchacha20poly1305_push.bind(this, state),
            rekey: this.crypto_secretstream_xchacha20poly1305_rekey.bind(this, state)
        });
    }

    /**
     * Initialize the internal state for stream decryption.
     *
     * @param {Buffer} header
     * @param {CryptographyKey} key
     * @return {Promise<*>}
     */
    async crypto_secretstream_xchacha20poly1305_init_pull(key, header) {
        await this.ensureLoaded();
        header = await Util.toBuffer(header);
        if (header.length !== 24) {
            throw new SodiumError('crypto_secretstream headers must be 24 bytes long');
        }
        if (!(key instanceof CryptographyKey)) {
            throw new TypeError('Key must be an instance of CryptographyKey');
        }
        if (key.getLength() !== 32) {
            throw new SodiumError('crypto_secretstream keys must be 32 bytes long');
        }
        const state = await this.backend.crypto_secretstream_xchacha20poly1305_init_pull(header, key);
        return Object.freeze({
            pull: this.crypto_secretstream_xchacha20poly1305_pull.bind(this, state)
        });
    }

    /**
     * Stream encryption.
     *
     * @param {*} state
     * @param {string|Buffer} message
     * @param {string|Buffer} ad
     * @param {number} tag
     * @return {Promise<Buffer>}
     */
    async crypto_secretstream_xchacha20poly1305_push(state, message, ad = '', tag = 0) {
        await this.ensureLoaded();
        return this.backend.crypto_secretstream_xchacha20poly1305_push(state, message, ad, tag);
    }

    /**
     * Stream decryption.
     *
     * @param {*} state
     * @param {Buffer} ciphertext
     * @param {string|Buffer} ad
     * @param {number} tag
     * @return {Promise<Buffer>}
     */
    async crypto_secretstream_xchacha20poly1305_pull(state, ciphertext, ad = '', tag = 0) {
        await this.ensureLoaded();
        return this.backend.crypto_secretstream_xchacha20poly1305_pull(state, ciphertext, ad, tag);
    }

    /**
     * Deterministic rekeying.
     *
     * @param {*} state
     * @return {Promise<void>}
     */
    async crypto_secretstream_xchacha20poly1305_rekey(state) {
        await this.ensureLoaded();
        await this.backend.crypto_secretstream_xchacha20poly1305_rekey(state);
    }

    /**
     * Generate a key for shared-key authenticated encryption.
     *
     * @return {Promise<CryptographyKey>}
     */
    async crypto_secretstream_xchacha20poly1305_keygen() {
        return new CryptographyKey(
            await this.backend.randombytes_buf(this.CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES)
        );
    }

    /**
     * Calculate a fast hash for short inputs.
     *
     * Algorithm: SipHash-2-4
     *
     * @param {string|Buffer} message
     * @param {CryptographyKey} key
     * @return {Promise<Buffer>}
     */
    async crypto_shorthash(message, key) {
        await this.ensureLoaded();
        return await this.backend.crypto_shorthash(await Util.toBuffer(message), key);
    }

    /**
     * @return {Promise<CryptographyKey>}
     */
    async crypto_shorthash_keygen() {
        return new CryptographyKey(
            await this.backend.randombytes_buf(this.CRYPTO_SHORTHASH_KEYBYTES)
        );
    }

    /**
     * Returns a signed message.
     *
     * @param {string|Buffer} message,
     * @param {Ed25519SecretKey} secretKey
     * @return {Promise<Buffer>}
     */
    async crypto_sign(message, secretKey) {
        await this.ensureLoaded();
        if (!(secretKey instanceof Ed25519SecretKey)) {
            throw new TypeError('Argument 2 must be an instance of Ed25519SecretKey');
        }
        return this.backend.crypto_sign(message, secretKey);
    }

    /**
     * Given a signed message, verify the Ed25519 signature. If it matches, return the
     * bare message (no signature).
     *
     * @param {string|Buffer} message,
     * @param {Ed25519PublicKey} publicKey
     * @return {Promise<Buffer>}
     */
    async crypto_sign_open(message, publicKey) {
        await this.ensureLoaded();
        if (!(publicKey instanceof Ed25519PublicKey)) {
            throw new TypeError('Argument 2 must be an instance of Ed25519PublicKey');
        }
        return this.backend.crypto_sign_open(message, publicKey);
    }

    /**
     * Returns the Ed25519 signature of the message, for the given secret key.
     *
     * @param {string|Buffer} message,
     * @param {Ed25519SecretKey} secretKey
     * @return {Promise<Buffer>}
     */
    async crypto_sign_detached(message, secretKey) {
        await this.ensureLoaded();
        if (!(secretKey instanceof Ed25519SecretKey)) {
            throw new TypeError('Argument 2 must be an instance of Ed25519SecretKey');
        }
        return this.backend.crypto_sign_detached(message, secretKey);
    }

    /**
     * Returns true if the Ed25519 signature is valid for a given message and public key.
     *
     * @param {string|Buffer} message,
     * @param {Ed25519PublicKey} publicKey
     * @param {Buffer} signature
     * @return {Promise<boolean>}
     */
    async crypto_sign_verify_detached(message, publicKey, signature) {
        await this.ensureLoaded();
        if (!(publicKey instanceof Ed25519PublicKey)) {
            throw new TypeError('Argument 2 must be an instance of Ed25519PublicKey');
        }
        return this.backend.crypto_sign_verify_detached(message, publicKey, signature);
    }

    /**
     * Extract the secret key from an Ed25519 keypair object.
     *
     * @param {CryptographyKey} keypair
     * @return {Promise<Ed25519SecretKey>}
     */
    async crypto_sign_secretkey(keypair) {
        if (keypair.getLength() !== 96) {
            throw new SodiumError('Keypair must be 96 bytes');
        }
        return new Ed25519SecretKey(
            await Util.toBuffer(
                keypair.getBuffer().slice(0, 64)
            )
        );
    }

    /**
     * Extract the public key from an Ed25519 keypair object.
     *
     * @param {CryptographyKey} keypair
     * @return {Promise<Ed25519PublicKey>}
     */
    async crypto_sign_publickey(keypair) {
        if (keypair.getLength() !== 96) {
            throw new SodiumError('Keypair must be 96 bytes');
        }
        return new Ed25519PublicKey(
            keypair.getBuffer().slice(64, 96)
        );
    }

    /**
     * Generate an Ed25519 keypair object.
     *
     * @return {Promise<CryptographyKey>}
     */
    async crypto_sign_keypair() {
        await this.ensureLoaded();
        return this.backend.crypto_sign_keypair();
    }

    /**
     * Generate an Ed25519 keypair object from a seed.
     *
     * @param {Buffer} seed
     * @return {Promise<CryptographyKey>}
     */
    async crypto_sign_seed_keypair(seed) {
        await this.ensureLoaded();
        if (seed instanceof CryptographyKey) {
            seed = seed.getBuffer();
        }
        seed = await Util.toBuffer(seed);
        if (seed.length !== 32) {
            throw new SodiumError(`Seed must be 32 bytes long; got ${seed.length}`);
        }
        return this.backend.crypto_sign_seed_keypair(seed);
    }

    /**
     * Obtain a birationally equivalent X25519 secret key,
     * given an Ed25519 secret key.
     *
     * @param {Ed25519SecretKey} sk
     * @return {Promise<X25519SecretKey>}
     */
    async crypto_sign_ed25519_sk_to_curve25519(sk) {
        await this.ensureLoaded();
        return new X25519SecretKey(
            await this.backend.crypto_sign_ed25519_sk_to_curve25519(sk)
        );
    }

    /**
     * Obtain a birationally equivalent X25519 public key,
     * given an Ed25519 public key.
     *
     * @param {Ed25519PublicKey} pk
     * @return {Promise<X25519PublicKey>}
     */
    async crypto_sign_ed25519_pk_to_curve25519(pk) {
        await this.ensureLoaded();
        return new X25519PublicKey(
            await this.backend.crypto_sign_ed25519_pk_to_curve25519(pk)
        );
    }

    /**
     * Generate an arbitrary number of pseudorandom bytes from a given
     * nonce and key.
     *
     * @param {number} length
     * @param {Buffer} nonce
     * @param {CryptographyKey} key
     * @return {Promise<Buffer>}
     */
    async crypto_stream(length, nonce, key) {
        await this.ensureLoaded();
        return this.backend.crypto_stream(length, nonce, key);
    }

    /**
     * Encrypts a string (without authentication).
     *
     * @param {string|Buffer} plaintext
     * @param {Buffer} nonce
     * @param {CryptographyKey} key
     * @return {Promise<Buffer>}
     */
    async crypto_stream_xor(plaintext, nonce, key) {
        await this.ensureLoaded();
        return this.backend.crypto_stream_xor(plaintext, nonce, key);
    }
    /**
     * Generate a key for stream ciphers.
     *
     * @return {Promise<CryptographyKey>}
     */
    async crypto_stream_keygen() {
        return new CryptographyKey(
            await this.backend.randombytes_buf(this.CRYPTO_STREAM_KEYBYTES)
        );
    }

    /**
     * Returns a buffer filled with random bytes.
     *
     * @param {number} num
     * @return {Promise<Buffer>}
     */
    async randombytes_buf(num) {
        await this.ensureLoaded();
        return await this.backend.randombytes_buf(num);
    }

    /**
     * Generate an integer between 0 and upperBound (non-inclusive).
     *
     * For example, randombytes_uniform(10) returns an integer between 0 and 9.
     *
     * @param {number} upperBound
     * @return {Promise<number>}
     */
    async randombytes_uniform(upperBound) {
        await this.ensureLoaded();
        return this.backend.randombytes_uniform(upperBound);
    }

    /**
     * Add two buffers (little-endian). Returns the value.
     *
     * @param {Buffer} val
     * @param {Buffer} addv
     * @return {Promise<Buffer>}
     */
    async sodium_add(val, addv) {
        await this.ensureLoaded();
        return await this.backend.sodium_add(
            await Util.toBuffer(val),
            await Util.toBuffer(addv)
        );
    }

    /**
     * Convert to hex.
     *
     * @param {Buffer} decoded
     * @return {Promise<Buffer>}
     */
    async sodium_bin2hex(decoded) {
        await this.ensureLoaded();
        return this.backend.sodium_bin2hex(decoded);
    }

    /**
     * Compare two buffers in constant time.
     *
     * Returns -1 if b1 is less than b2.
     * Returns  1 if b1 is greater than b2.
     * Returns  0 if b1 is equal to b2.
     *
     * @param {Buffer} b1
     * @param {Buffer} b2
     * @return {Promise<number>}
     */
    async sodium_compare(b1, b2) {
        await this.ensureLoaded();
        return this.backend.sodium_compare(b1, b2);
    }
    /**
     * Convert to hex.
     *
     * @param {Buffer|string} encoded
     * @return {Promise<string>}
     */
    async sodium_hex2bin(encoded) {
        await this.ensureLoaded();
        return this.backend.sodium_hex2bin(encoded);
    }

    /**
     * Increment a buffer (little endian). Overwrites the buffer in-place.
     *
     * @param {Buffer} buf
     * @return {Promise<Buffer>}
     */
    async sodium_increment(buf) {
        await this.ensureLoaded();
        return this.backend.sodium_increment(buf);
    }

    /**
     * Returns true if the buffer is zero.
     *
     * @param {Buffer} buf
     * @param {number} len
     * @return {Promise<Buffer>}
     */
    async sodium_is_zero(buf, len) {
        await this.ensureLoaded();
        return this.backend.sodium_is_zero(buf, len);
    }

    /**
     * Timing-safe buffer comparison.
     *
     * @param {Buffer} b1
     * @param {Buffer} b2
     * @return {Promise<boolean>}
     */
    async sodium_memcmp(b1, b2) {
        await this.ensureLoaded();
        return this.backend.sodium_memcmp(b1, b2);
    }

    /**
     * Zero out a buffer. Overwrites the buffer in-place.
     *
     * @param {Buffer} buf
     * @return {Promise<void>}
     */
    async sodium_memzero(buf) {
        await this.ensureLoaded();
        await this.backend.sodium_memzero(buf);
    }

    /**
     * Pad a string.
     *
     * @param {string|Buffer} buf
     * @param {number} blockSize
     * @return {Promise<Buffer>}
     */
    async sodium_pad(buf, blockSize) {
        await this.ensureLoaded();
        return this.backend.sodium_pad(buf, blockSize);
    }

    /**
     * Unpad a string.
     *
     * @param {string|Buffer} buf
     * @param {number} blockSize
     * @return {Promise<Buffer>}
     */
    async sodium_unpad(buf, blockSize) {
        await this.ensureLoaded();
        return this.backend.sodium_unpad(buf, blockSize);
    }
}

module.exports = SodiumPlus;