-
Notifications
You must be signed in to change notification settings - Fork 14
/
rust.rs
1506 lines (1409 loc) · 50.8 KB
/
rust.rs
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
//
// This file was automatically generated by witx-codegen - Do not edit manually.
//
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Error {
WasiError(i32),
}
impl std::error::Error for Error {}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::WasiError(e) => write!(f, "Wasi error {}", e),
}
}
}
pub type WasiHandle = i32;
pub type Char8 = u8;
pub type Char32 = u32;
pub type WasiPtr<T> = *const T;
pub type WasiMutPtr<T> = *mut T;
pub type WasiStringBytesPtr = WasiPtr<Char8>;
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct WasiSlice<T> {
ptr: WasiPtr<T>,
len: usize,
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct WasiMutSlice<T> {
ptr: WasiMutPtr<T>,
len: usize,
}
impl<T> WasiSlice<T> {
pub fn as_slice(&self) -> &[T] {
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
pub fn from_slice(&self, slice: &[T]) -> Self {
WasiSlice {
ptr: slice.as_ptr() as _,
len: slice.len(),
}
}
}
impl<T> WasiMutSlice<T> {
pub fn as_slice(&self) -> &[T] {
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
pub fn as_mut_slice(&self) -> &mut [T] {
unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
}
pub fn from_slice(&self, slice: &[T]) -> Self {
WasiMutSlice {
ptr: slice.as_ptr() as _,
len: slice.len(),
}
}
pub fn from_mut_slice(&self, slice: &mut [T]) -> Self {
WasiMutSlice {
ptr: slice.as_mut_ptr(),
len: slice.len(),
}
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct WasiString {
ptr: WasiStringBytesPtr,
len: usize,
}
impl<T: AsRef<str>> From<T> for WasiString {
fn from(s: T) -> Self {
let s = s.as_ref();
WasiString {
ptr: s.as_ptr() as _,
len: s.len(),
}
}
}
impl WasiString {
pub fn as_str(&self) -> Result<&str, std::str::Utf8Error> {
std::str::from_utf8(unsafe { std::slice::from_raw_parts(self.ptr, self.len) })
}
pub fn as_slice(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
pub fn from_slice(&self, slice: &[u8]) -> Self {
WasiString {
ptr: slice.as_ptr() as _,
len: slice.len(),
}
}
}
// ---------------------- Module: [wasi_ephemeral_crypto_symmetric] ----------------------
/// Error codes.
pub type CryptoErrno = u16;
#[allow(non_snake_case)]
pub mod CRYPTO_ERRNO {
use super::CryptoErrno;
pub const SUCCESS: CryptoErrno = 0;
pub const GUEST_ERROR: CryptoErrno = 1;
pub const NOT_IMPLEMENTED: CryptoErrno = 2;
pub const UNSUPPORTED_FEATURE: CryptoErrno = 3;
pub const PROHIBITED_OPERATION: CryptoErrno = 4;
pub const UNSUPPORTED_ENCODING: CryptoErrno = 5;
pub const UNSUPPORTED_ALGORITHM: CryptoErrno = 6;
pub const UNSUPPORTED_OPTION: CryptoErrno = 7;
pub const INVALID_KEY: CryptoErrno = 8;
pub const INVALID_LENGTH: CryptoErrno = 9;
pub const VERIFICATION_FAILED: CryptoErrno = 10;
pub const RNG_ERROR: CryptoErrno = 11;
pub const ALGORITHM_FAILURE: CryptoErrno = 12;
pub const INVALID_SIGNATURE: CryptoErrno = 13;
pub const CLOSED: CryptoErrno = 14;
pub const INVALID_HANDLE: CryptoErrno = 15;
pub const OVERFLOW: CryptoErrno = 16;
pub const INTERNAL_ERROR: CryptoErrno = 17;
pub const TOO_MANY_HANDLES: CryptoErrno = 18;
pub const KEY_NOT_SUPPORTED: CryptoErrno = 19;
pub const KEY_REQUIRED: CryptoErrno = 20;
pub const INVALID_TAG: CryptoErrno = 21;
pub const INVALID_OPERATION: CryptoErrno = 22;
pub const NONCE_REQUIRED: CryptoErrno = 23;
pub const INVALID_NONCE: CryptoErrno = 24;
pub const OPTION_NOT_SET: CryptoErrno = 25;
pub const NOT_FOUND: CryptoErrno = 26;
pub const PARAMETERS_MISSING: CryptoErrno = 27;
pub const IN_PROGRESS: CryptoErrno = 28;
pub const INCOMPATIBLE_KEYS: CryptoErrno = 29;
pub const EXPIRED: CryptoErrno = 30;
}
/// Encoding to use for importing or exporting a key pair.
pub type KeypairEncoding = u16;
#[allow(non_snake_case)]
pub mod KEYPAIR_ENCODING {
use super::KeypairEncoding;
pub const RAW: KeypairEncoding = 0;
pub const PKCS_8: KeypairEncoding = 1;
pub const PEM: KeypairEncoding = 2;
pub const LOCAL: KeypairEncoding = 3;
}
/// Encoding to use for importing or exporting a public key.
pub type PublickeyEncoding = u16;
#[allow(non_snake_case)]
pub mod PUBLICKEY_ENCODING {
use super::PublickeyEncoding;
pub const RAW: PublickeyEncoding = 0;
pub const PKCS_8: PublickeyEncoding = 1;
pub const PEM: PublickeyEncoding = 2;
pub const SEC: PublickeyEncoding = 3;
pub const COMPRESSED_SEC: PublickeyEncoding = 4;
pub const LOCAL: PublickeyEncoding = 5;
}
/// Encoding to use for importing or exporting a secret key.
pub type SecretkeyEncoding = u16;
#[allow(non_snake_case)]
pub mod SECRETKEY_ENCODING {
use super::SecretkeyEncoding;
pub const RAW: SecretkeyEncoding = 0;
pub const PKCS_8: SecretkeyEncoding = 1;
pub const PEM: SecretkeyEncoding = 2;
pub const SEC: SecretkeyEncoding = 3;
pub const COMPRESSED_SEC: SecretkeyEncoding = 4;
pub const LOCAL: SecretkeyEncoding = 5;
}
/// Encoding to use for importing or exporting a signature.
pub type SignatureEncoding = u16;
#[allow(non_snake_case)]
pub mod SIGNATURE_ENCODING {
use super::SignatureEncoding;
pub const RAW: SignatureEncoding = 0;
pub const DER: SignatureEncoding = 1;
}
/// An algorithm category.
pub type AlgorithmType = u16;
#[allow(non_snake_case)]
pub mod ALGORITHM_TYPE {
use super::AlgorithmType;
pub const SIGNATURES: AlgorithmType = 0;
pub const SYMMETRIC: AlgorithmType = 1;
pub const KEY_EXCHANGE: AlgorithmType = 2;
}
/// Version of a managed key.
///
/// A version can be an arbitrary `u64` integer, with the expection of some reserved values.
pub type Version = u64;
/// Size of a value.
pub type Size = usize;
/// A UNIX timestamp, in seconds since 01/01/1970.
pub type Timestamp = u64;
/// A 64-bit value
pub type U64 = u64;
/// Handle for functions returning output whose size may be large or not known in advance.
///
/// An `array_output` object contains a host-allocated byte array.
///
/// A guest can get the size of that array after a function returns in order to then allocate a buffer of the correct size.
/// In addition, the content of such an object can be consumed by a guest in a streaming fashion.
///
/// An `array_output` handle is automatically closed after its full content has been consumed.
pub type ArrayOutput = WasiHandle;
/// A set of options.
///
/// This type is used to set non-default parameters.
///
/// The exact set of allowed options depends on the algorithm being used.
pub type Options = WasiHandle;
/// A handle to the optional secrets management facilities offered by a host.
///
/// This is used to generate, retrieve and invalidate managed keys.
pub type SecretsManager = WasiHandle;
/// A key pair.
pub type Keypair = WasiHandle;
/// A state to absorb data to be signed.
///
/// After a signature has been computed or verified, the state remains valid for further operations.
///
/// A subsequent signature would sign all the data accumulated since the creation of the state object.
pub type SignatureState = WasiHandle;
/// A signature.
pub type Signature = WasiHandle;
/// A public key, for key exchange and signature verification.
pub type Publickey = WasiHandle;
/// A secret key, for key exchange mechanisms.
pub type Secretkey = WasiHandle;
/// A state to absorb signed data to be verified.
pub type SignatureVerificationState = WasiHandle;
/// A state to perform symmetric operations.
///
/// The state is not reset nor invalidated after an option has been performed.
/// Incremental updates and sessions are thus supported.
pub type SymmetricState = WasiHandle;
/// A symmetric key.
///
/// The key can be imported from raw bytes, or can be a reference to a managed key.
///
/// If it was imported, the host will wipe it from memory as soon as the handle is closed.
pub type SymmetricKey = WasiHandle;
/// An authentication tag.
///
/// This is an object returned by functions computing authentication tags.
///
/// A tag can be compared against another tag (directly supplied as raw bytes) in constant time with the `symmetric_tag_verify()` function.
///
/// This object type can't be directly created from raw bytes. They are only returned by functions computing MACs.
///
/// The host is reponsible for securely wiping them from memory on close.
pub type SymmetricTag = WasiHandle;
/// Options index, only required by the Interface Types translation layer.
pub type OptOptionsU = u8;
#[allow(non_snake_case)]
pub mod OPT_OPTIONS_U {
use super::OptOptionsU;
pub const SOME: OptOptionsU = 0;
pub const NONE: OptOptionsU = 1;
}
/// An optional options set.
///
/// This union simulates an `Option<Options>` type to make the `options` parameter of some functions optional.
#[repr(C)]
pub union OptOptionsMember {
some: Options, // if tag=0
// none with no associated value if tag=1
}
#[repr(C, packed)]
pub struct OptOptions {
pub tag: u8,
__pad8_0: u8,
__pad16_0: u16,
__pad32_0: u32,
pub member: std::mem::MaybeUninit<OptOptionsMember>,
}
impl OptOptions {
fn new(tag: u8) -> Self {
let mut tu = unsafe { std::mem::zeroed::<Self>() };
tu.tag = tag;
tu
}
// --- some: Options if tag=0
pub fn new_some(val: Options) -> Self {
let mut tu = Self::new(0);
tu.member = std::mem::MaybeUninit::new(OptOptionsMember { some: val });
tu
}
pub fn into_some(self) -> Options {
assert_eq!(self.tag, 0);
unsafe { self.member.assume_init().some }
}
pub fn set_some(&mut self, val: Options) {
assert_eq!(self.tag, 0);
let uval = OptOptionsMember { some: val };
unsafe { *self.member.as_mut_ptr() = uval };
}
pub fn is_some(&self) -> bool {
self.tag == 0
}
// --- none: (no associated content) if tag=1
pub fn new_none() -> Self {
Self::new(1)
}
pub fn is_none(&self) -> bool {
self.tag == 1
}
}
/// Symmetric key index, only required by the Interface Types translation layer.
pub type OptSymmetricKeyU = u8;
#[allow(non_snake_case)]
pub mod OPT_SYMMETRIC_KEY_U {
use super::OptSymmetricKeyU;
pub const SOME: OptSymmetricKeyU = 0;
pub const NONE: OptSymmetricKeyU = 1;
}
/// An optional symmetric key.
///
/// This union simulates an `Option<SymmetricKey>` type to make the `symmetric_key` parameter of some functions optional.
#[repr(C)]
pub union OptSymmetricKeyMember {
some: SymmetricKey, // if tag=0
// none with no associated value if tag=1
}
#[repr(C, packed)]
pub struct OptSymmetricKey {
pub tag: u8,
__pad8_0: u8,
__pad16_0: u16,
__pad32_0: u32,
pub member: std::mem::MaybeUninit<OptSymmetricKeyMember>,
}
impl OptSymmetricKey {
fn new(tag: u8) -> Self {
let mut tu = unsafe { std::mem::zeroed::<Self>() };
tu.tag = tag;
tu
}
// --- some: SymmetricKey if tag=0
pub fn new_some(val: SymmetricKey) -> Self {
let mut tu = Self::new(0);
tu.member = std::mem::MaybeUninit::new(OptSymmetricKeyMember { some: val });
tu
}
pub fn into_some(self) -> SymmetricKey {
assert_eq!(self.tag, 0);
unsafe { self.member.assume_init().some }
}
pub fn set_some(&mut self, val: SymmetricKey) {
assert_eq!(self.tag, 0);
let uval = OptSymmetricKeyMember { some: val };
unsafe { *self.member.as_mut_ptr() = uval };
}
pub fn is_some(&self) -> bool {
self.tag == 0
}
// --- none: (no associated content) if tag=1
pub fn new_none() -> Self {
Self::new(1)
}
pub fn is_none(&self) -> bool {
self.tag == 1
}
}
/// Generate a new symmetric key for a given algorithm.
///
/// `options` can be `None` to use the default parameters, or an algoritm-specific set of parameters to override.
///
/// This function may return `unsupported_feature` if key generation is not supported by the host for the chosen algorithm, or `unsupported_algorithm` if the algorithm is not supported by the host.
pub fn symmetric_key_generate(
algorithm_ptr: WasiPtr<Char8>,
algorithm_len: usize,
options: OptOptions,
) -> Result<SymmetricKey, Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_key_generate(
algorithm_ptr: WasiPtr<Char8>,
algorithm_len: usize,
options: OptOptions,
result_ptr: WasiMutPtr<SymmetricKey>,
) -> CryptoErrno;
}
let mut result_ptr = std::mem::MaybeUninit::uninit();
let res = unsafe {
symmetric_key_generate(
algorithm_ptr,
algorithm_len,
options,
result_ptr.as_mut_ptr(),
)
};
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(unsafe { result_ptr.assume_init() })
}
/// Create a symmetric key from raw material.
///
/// The algorithm is internally stored along with the key, and trying to use the key with an operation expecting a different algorithm will return `invalid_key`.
///
/// The function may also return `unsupported_algorithm` if the algorithm is not supported by the host.
pub fn symmetric_key_import(
algorithm_ptr: WasiPtr<Char8>,
algorithm_len: usize,
raw: WasiPtr<u8>,
raw_len: Size,
) -> Result<SymmetricKey, Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_key_import(
algorithm_ptr: WasiPtr<Char8>,
algorithm_len: usize,
raw: WasiPtr<u8>,
raw_len: Size,
result_ptr: WasiMutPtr<SymmetricKey>,
) -> CryptoErrno;
}
let mut result_ptr = std::mem::MaybeUninit::uninit();
let res = unsafe {
symmetric_key_import(
algorithm_ptr,
algorithm_len,
raw,
raw_len,
result_ptr.as_mut_ptr(),
)
};
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(unsafe { result_ptr.assume_init() })
}
/// Export a symmetric key as raw material.
///
/// This is mainly useful to export a managed key.
///
/// May return `prohibited_operation` if this operation is denied.
pub fn symmetric_key_export(symmetric_key: SymmetricKey) -> Result<ArrayOutput, Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_key_export(
symmetric_key: SymmetricKey,
result_ptr: WasiMutPtr<ArrayOutput>,
) -> CryptoErrno;
}
let mut result_ptr = std::mem::MaybeUninit::uninit();
let res = unsafe { symmetric_key_export(symmetric_key, result_ptr.as_mut_ptr()) };
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(unsafe { result_ptr.assume_init() })
}
/// Destroy a symmetric key.
///
/// Objects are reference counted. It is safe to close an object immediately after the last function needing it is called.
pub fn symmetric_key_close(symmetric_key: SymmetricKey) -> Result<(), Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_key_close(symmetric_key: SymmetricKey) -> CryptoErrno;
}
let res = unsafe { symmetric_key_close(symmetric_key) };
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(())
}
/// __(optional)__
/// Generate a new managed symmetric key.
///
/// The key is generated and stored by the secrets management facilities.
///
/// It may be used through its identifier, but the host may not allow it to be exported.
///
/// The function returns the `unsupported_feature` error code if secrets management facilities are not supported by the host,
/// or `unsupported_algorithm` if a key cannot be created for the chosen algorithm.
///
/// The function may also return `unsupported_algorithm` if the algorithm is not supported by the host.
///
/// This is also an optional import, meaning that the function may not even exist.
pub fn symmetric_key_generate_managed(
secrets_manager: SecretsManager,
algorithm_ptr: WasiPtr<Char8>,
algorithm_len: usize,
options: OptOptions,
) -> Result<SymmetricKey, Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_key_generate_managed(
secrets_manager: SecretsManager,
algorithm_ptr: WasiPtr<Char8>,
algorithm_len: usize,
options: OptOptions,
result_ptr: WasiMutPtr<SymmetricKey>,
) -> CryptoErrno;
}
let mut result_ptr = std::mem::MaybeUninit::uninit();
let res = unsafe {
symmetric_key_generate_managed(
secrets_manager,
algorithm_ptr,
algorithm_len,
options,
result_ptr.as_mut_ptr(),
)
};
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(unsafe { result_ptr.assume_init() })
}
/// __(optional)__
/// Store a symmetric key into the secrets manager.
///
/// On success, the function stores the key identifier into `$symmetric_key_id`,
/// into which up to `$symmetric_key_id_max_len` can be written.
///
/// The function returns `overflow` if the supplied buffer is too small.
pub fn symmetric_key_store_managed(
secrets_manager: SecretsManager,
symmetric_key: SymmetricKey,
symmetric_key_id: WasiMutPtr<u8>,
symmetric_key_id_max_len: Size,
) -> Result<(), Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_key_store_managed(
secrets_manager: SecretsManager,
symmetric_key: SymmetricKey,
symmetric_key_id: WasiMutPtr<u8>,
symmetric_key_id_max_len: Size,
) -> CryptoErrno;
}
let res = unsafe {
symmetric_key_store_managed(
secrets_manager,
symmetric_key,
symmetric_key_id,
symmetric_key_id_max_len,
)
};
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(())
}
/// __(optional)__
/// Replace a managed symmetric key.
///
/// This function crates a new version of a managed symmetric key, by replacing `$kp_old` with `$kp_new`.
///
/// It does several things:
///
/// - The key identifier for `$symmetric_key_new` is set to the one of `$symmetric_key_old`.
/// - A new, unique version identifier is assigned to `$kp_new`. This version will be equivalent to using `$version_latest` until the key is replaced.
/// - The `$symmetric_key_old` handle is closed.
///
/// Both keys must share the same algorithm and have compatible parameters. If this is not the case, `incompatible_keys` is returned.
///
/// The function may also return the `unsupported_feature` error code if secrets management facilities are not supported by the host,
/// or if keys cannot be rotated.
///
/// Finally, `prohibited_operation` can be returned if `$symmetric_key_new` wasn't created by the secrets manager, and the secrets manager prohibits imported keys.
///
/// If the operation succeeded, the new version is returned.
///
/// This is an optional import, meaning that the function may not even exist.
pub fn symmetric_key_replace_managed(
secrets_manager: SecretsManager,
symmetric_key_old: SymmetricKey,
symmetric_key_new: SymmetricKey,
) -> Result<Version, Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_key_replace_managed(
secrets_manager: SecretsManager,
symmetric_key_old: SymmetricKey,
symmetric_key_new: SymmetricKey,
result_ptr: WasiMutPtr<Version>,
) -> CryptoErrno;
}
let mut result_ptr = std::mem::MaybeUninit::uninit();
let res = unsafe {
symmetric_key_replace_managed(
secrets_manager,
symmetric_key_old,
symmetric_key_new,
result_ptr.as_mut_ptr(),
)
};
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(unsafe { result_ptr.assume_init() })
}
/// __(optional)__
/// Return the key identifier and version of a managed symmetric key.
///
/// If the key is not managed, `unsupported_feature` is returned instead.
///
/// This is an optional import, meaning that the function may not even exist.
pub fn symmetric_key_id(
symmetric_key: SymmetricKey,
symmetric_key_id: WasiMutPtr<u8>,
symmetric_key_id_max_len: Size,
) -> Result<(Size, Version), Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_key_id(
symmetric_key: SymmetricKey,
symmetric_key_id: WasiMutPtr<u8>,
symmetric_key_id_max_len: Size,
result_0_ptr: WasiMutPtr<Size>,
result_1_ptr: WasiMutPtr<Version>,
) -> CryptoErrno;
}
let mut result_0_ptr = std::mem::MaybeUninit::uninit();
let mut result_1_ptr = std::mem::MaybeUninit::uninit();
let res = unsafe {
symmetric_key_id(
symmetric_key,
symmetric_key_id,
symmetric_key_id_max_len,
result_0_ptr.as_mut_ptr(),
result_1_ptr.as_mut_ptr(),
)
};
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(unsafe { (result_0_ptr.assume_init(), result_1_ptr.assume_init()) })
}
/// __(optional)__
/// Return a managed symmetric key from a key identifier.
///
/// `kp_version` can be set to `version_latest` to retrieve the most recent version of a symmetric key.
///
/// If no key matching the provided information is found, `not_found` is returned instead.
///
/// This is an optional import, meaning that the function may not even exist.
pub fn symmetric_key_from_id(
secrets_manager: SecretsManager,
symmetric_key_id: WasiPtr<u8>,
symmetric_key_id_len: Size,
symmetric_key_version: Version,
) -> Result<SymmetricKey, Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_key_from_id(
secrets_manager: SecretsManager,
symmetric_key_id: WasiPtr<u8>,
symmetric_key_id_len: Size,
symmetric_key_version: Version,
result_ptr: WasiMutPtr<SymmetricKey>,
) -> CryptoErrno;
}
let mut result_ptr = std::mem::MaybeUninit::uninit();
let res = unsafe {
symmetric_key_from_id(
secrets_manager,
symmetric_key_id,
symmetric_key_id_len,
symmetric_key_version,
result_ptr.as_mut_ptr(),
)
};
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(unsafe { result_ptr.assume_init() })
}
/// Create a new state to aborb and produce data using symmetric operations.
///
/// The state remains valid after every operation in order to support incremental updates.
///
/// The function has two optional parameters: a key and an options set.
///
/// It will fail with a `key_not_supported` error code if a key was provided but the chosen algorithm doesn't natively support keying.
///
/// On the other hand, if a key is required, but was not provided, a `key_required` error will be thrown.
///
/// Some algorithms may require additional parameters. They have to be supplied as an options set:
///
/// ```rust
/// let options_handle = ctx.options_open()?;
/// ctx.options_set("context", b"My application")?;
/// ctx.options_set_u64("fanout", 16)?;
/// let state_handle = ctx.symmetric_state_open("BLAKE2b-512", None, Some(options_handle))?;
/// ```
///
/// If some parameters are mandatory but were not set, the `parameters_missing` error code will be returned.
///
/// A notable exception is the `nonce` parameter, that is common to most AEAD constructions.
///
/// If a nonce is required but was not supplied:
///
/// - If it is safe to do so, the host will automatically generate a nonce. This is true for nonces that are large enough to be randomly generated, or if the host is able to maintain a global counter.
/// - If not, the function will fail and return the dedicated `nonce_required` error code.
///
/// A nonce that was automatically generated can be retrieved after the function returns with `symmetric_state_get(state_handle, "nonce")`.
///
/// **Sample usage patterns:**
///
/// - **Hashing**
///
/// ```rust
/// let mut out = [0u8; 64];
/// let state_handle = ctx.symmetric_state_open("SHAKE-128", None, None)?;
/// ctx.symmetric_state_absorb(state_handle, b"data")?;
/// ctx.symmetric_state_absorb(state_handle, b"more_data")?;
/// ctx.symmetric_state_squeeze(state_handle, &mut out)?;
/// ```
///
/// - **MAC**
///
/// ```rust
/// let mut raw_tag = [0u8; 64];
/// let key_handle = ctx.symmetric_key_import("HMAC/SHA-512", b"key")?;
/// let state_handle = ctx.symmetric_state_open("HMAC/SHA-512", Some(key_handle), None)?;
/// ctx.symmetric_state_absorb(state_handle, b"data")?;
/// ctx.symmetric_state_absorb(state_handle, b"more_data")?;
/// let computed_tag_handle = ctx.symmetric_state_squeeze_tag(state_handle)?;
/// ctx.symmetric_tag_pull(computed_tag_handle, &mut raw_tag)?;
/// ```
///
/// Verification:
///
/// ```rust
/// let state_handle = ctx.symmetric_state_open("HMAC/SHA-512", Some(key_handle), None)?;
/// ctx.symmetric_state_absorb(state_handle, b"data")?;
/// ctx.symmetric_state_absorb(state_handle, b"more_data")?;
/// let computed_tag_handle = ctx.symmetric_state_squeeze_tag(state_handle)?;
/// ctx.symmetric_tag_verify(computed_tag_handle, expected_raw_tag)?;
/// ```
///
/// - **Tuple hashing**
///
/// ```rust
/// let mut out = [0u8; 64];
/// let state_handle = ctx.symmetric_state_open("TupleHashXOF256", None, None)?;
/// ctx.symmetric_state_absorb(state_handle, b"value 1")?;
/// ctx.symmetric_state_absorb(state_handle, b"value 2")?;
/// ctx.symmetric_state_absorb(state_handle, b"value 3")?;
/// ctx.symmetric_state_squeeze(state_handle, &mut out)?;
/// ```
/// Unlike MACs and regular hash functions, inputs are domain separated instead of being concatenated.
///
/// - **Key derivation using extract-and-expand**
///
/// Extract:
///
/// ```rust
/// let mut prk = vec![0u8; 64];
/// let key_handle = ctx.symmetric_key_import("HKDF-EXTRACT/SHA-512", b"key")?;
/// let state_handle = ctx.symmetric_state_open("HKDF-EXTRACT/SHA-512", Some(key_handle), None)?;
/// ctx.symmetric_state_absorb(state_handle, b"salt")?;
/// let prk_handle = ctx.symmetric_state_squeeze_key(state_handle, "HKDF-EXPAND/SHA-512")?;
/// ```
///
/// Expand:
///
/// ```rust
/// let mut subkey = vec![0u8; 32];
/// let state_handle = ctx.symmetric_state_open("HKDF-EXPAND/SHA-512", Some(prk_handle), None)?;
/// ctx.symmetric_state_absorb(state_handle, b"info")?;
/// ctx.symmetric_state_squeeze(state_handle, &mut subkey)?;
/// ```
///
/// - **Key derivation using a XOF**
///
/// ```rust
/// let mut subkey1 = vec![0u8; 32];
/// let mut subkey2 = vec![0u8; 32];
/// let key_handle = ctx.symmetric_key_import("BLAKE3", b"key")?;
/// let state_handle = ctx.symmetric_state_open("BLAKE3", Some(key_handle), None)?;
/// ctx.symmetric_absorb(state_handle, b"context")?;
/// ctx.squeeze(state_handle, &mut subkey1)?;
/// ctx.squeeze(state_handle, &mut subkey2)?;
/// ```
///
/// - **Password hashing**
///
/// ```rust
/// let mut memory = vec![0u8; 1_000_000_000];
/// let options_handle = ctx.symmetric_options_open()?;
/// ctx.symmetric_options_set_guest_buffer(options_handle, "memory", &mut memory)?;
/// ctx.symmetric_options_set_u64(options_handle, "opslimit", 5)?;
/// ctx.symmetric_options_set_u64(options_handle, "parallelism", 8)?;
///
/// let state_handle = ctx.symmetric_state_open("ARGON2-ID-13", None, Some(options))?;
/// ctx.symmtric_state_absorb(state_handle, b"password")?;
///
/// let pw_str_handle = ctx.symmetric_state_squeeze_tag(state_handle)?;
/// let mut pw_str = vec![0u8; ctx.symmetric_tag_len(pw_str_handle)?];
/// ctx.symmetric_tag_pull(pw_str_handle, &mut pw_str)?;
/// ```
///
/// - **AEAD encryption with an explicit nonce**
///
/// ```rust
/// let key_handle = ctx.symmetric_key_generate("AES-256-GCM", None)?;
/// let message = b"test";
///
/// let options_handle = ctx.symmetric_options_open()?;
/// ctx.symmetric_options_set(options_handle, "nonce", nonce)?;
///
/// let state_handle = ctx.symmetric_state_open("AES-256-GCM", Some(key_handle), Some(options_handle))?;
/// let mut ciphertext = vec![0u8; message.len() + ctx.symmetric_state_max_tag_len(state_handle)?];
/// ctx.symmetric_state_absorb(state_handle, "additional data")?;
/// ctx.symmetric_state_encrypt(state_handle, &mut ciphertext, message)?;
/// ```
///
/// - **AEAD encryption with automatic nonce generation**
///
/// ```rust
/// let key_handle = ctx.symmetric_key_generate("AES-256-GCM-SIV", None)?;
/// let message = b"test";
/// let mut nonce = [0u8; 24];
///
/// let state_handle = ctx.symmetric_state_open("AES-256-GCM-SIV", Some(key_handle), None)?;
///
/// let nonce_handle = ctx.symmetric_state_options_get(state_handle, "nonce")?;
/// ctx.array_output_pull(nonce_handle, &mut nonce)?;
///
/// let mut ciphertext = vec![0u8; message.len() + ctx.symmetric_state_max_tag_len(state_handle)?];
/// ctx.symmetric_state_absorb(state_handle, "additional data")?;
/// ctx.symmetric_state_encrypt(state_handle, &mut ciphertext, message)?;
/// ```
///
/// - **Session authenticated modes**
///
/// ```rust
/// let mut out = [0u8; 16];
/// let mut out2 = [0u8; 16];
/// let mut ciphertext = [0u8; 20];
/// let key_handle = ctx.symmetric_key_generate("Xoodyak-128", None)?;
/// let state_handle = ctx.symmetric_state_open("Xoodyak-128", Some(key_handle), None)?;
/// ctx.symmetric_state_absorb(state_handle, b"data")?;
/// ctx.symmetric_state_encrypt(state_handle, &mut ciphertext, b"abcd")?;
/// ctx.symmetric_state_absorb(state_handle, b"more data")?;
/// ctx.symmetric_state_squeeze(state_handle, &mut out)?;
/// ctx.symmetric_state_squeeze(state_handle, &mut out2)?;
/// ctx.symmetric_state_ratchet(state_handle)?;
/// ctx.symmetric_state_absorb(state_handle, b"more data")?;
/// let next_key_handle = ctx.symmetric_state_squeeze_key(state_handle, "Xoodyak-128")?;
/// // ...
/// ```
pub fn symmetric_state_open(
algorithm_ptr: WasiPtr<Char8>,
algorithm_len: usize,
key: OptSymmetricKey,
options: OptOptions,
) -> Result<SymmetricState, Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_state_open(
algorithm_ptr: WasiPtr<Char8>,
algorithm_len: usize,
key: OptSymmetricKey,
options: OptOptions,
result_ptr: WasiMutPtr<SymmetricState>,
) -> CryptoErrno;
}
let mut result_ptr = std::mem::MaybeUninit::uninit();
let res = unsafe {
symmetric_state_open(
algorithm_ptr,
algorithm_len,
key,
options,
result_ptr.as_mut_ptr(),
)
};
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(unsafe { result_ptr.assume_init() })
}
/// Retrieve a parameter from the current state.
///
/// In particular, `symmetric_state_options_get("nonce")` can be used to get a nonce that as automatically generated.
///
/// The function may return `options_not_set` if an option was not set, which is different from an empty value.
///
/// It may also return `unsupported_option` if the option doesn't exist for the chosen algorithm.
pub fn symmetric_state_options_get(
handle: SymmetricState,
name_ptr: WasiPtr<Char8>,
name_len: usize,
value: WasiMutPtr<u8>,
value_max_len: Size,
) -> Result<Size, Error> {
#[link(wasm_import_module = "wasi_ephemeral_crypto_symmetric")]
extern "C" {
fn symmetric_state_options_get(
handle: SymmetricState,
name_ptr: WasiPtr<Char8>,
name_len: usize,
value: WasiMutPtr<u8>,
value_max_len: Size,
result_ptr: WasiMutPtr<Size>,
) -> CryptoErrno;
}
let mut result_ptr = std::mem::MaybeUninit::uninit();
let res = unsafe {
symmetric_state_options_get(
handle,
name_ptr,
name_len,
value,
value_max_len,
result_ptr.as_mut_ptr(),
)
};
if res != 0 {
return Err(Error::WasiError(res as _));
}
Ok(unsafe { result_ptr.assume_init() })
}
/// Retrieve an integer parameter from the current state.
///
/// In particular, `symmetric_state_options_get("nonce")` can be used to get a nonce that as automatically generated.