lit_sdk/
encryption.rs

1//! Encryption methods
2
3use crate::{EncryptedMulticastRequest, EndpointRequest, Response, SdkError, SdkResult, UrlPrefix};
4use lit_node_core::{
5    lit_rust_crypto::blsful::{
6        Bls12381G2Impl, PublicKey, Signature, SignatureSchemes, SignatureShare, TimeCryptCiphertext,
7    },
8    request::EncryptionSignRequest as InnerEncryptionSignRequest,
9    response::{EncryptionSignResponse as InnerEncryptionSignResponse, GenericResponse},
10};
11use std::{collections::HashMap, marker::PhantomData};
12use uuid::Uuid;
13
14/// The response type for encryption sign requests
15pub type EncryptionSignResponse = Response<GenericResponse<InnerEncryptionSignResponse>>;
16
17/// The encryption sign request struct
18pub type EncryptionSignRequest = EncryptedMulticastRequest<
19    EncryptionSignRequestBuilder,
20    InnerEncryptionSignRequest,
21    GenericResponse<InnerEncryptionSignResponse>,
22>;
23
24encrypted_multicast_builder!(
25    EncryptionSignRequestBuilder,
26    InnerEncryptionSignRequest,
27    GenericResponse<InnerEncryptionSignResponse>,
28    "/web/encryption/sign/v2"
29);
30
31impl EncryptionSignRequestBuilder {
32    /// Check that the inner request fields are set
33    fn request_checks(&self) -> SdkResult<()> {
34        Ok(())
35    }
36}
37
38/// Time Lock Encryption
39pub fn encrypt_time_lock(
40    public_key: &PublicKey<Bls12381G2Impl>,
41    message: &[u8],
42    identity: &[u8],
43) -> SdkResult<TimeCryptCiphertext<Bls12381G2Impl>> {
44    let ciphertext =
45        public_key.encrypt_time_lock(SignatureSchemes::ProofOfPossession, message, identity)?;
46    Ok(ciphertext)
47}
48
49/// Verify and decrypt the ciphertext using signature shares
50pub fn verify_and_decrypt_with_signatures_shares(
51    public_key: &PublicKey<Bls12381G2Impl>,
52    identity: &[u8],
53    ciphertext: &TimeCryptCiphertext<Bls12381G2Impl>,
54    shares: &[SignatureShare<Bls12381G2Impl>],
55) -> SdkResult<Vec<u8>> {
56    let signature = Signature::from_shares(shares)?;
57    verify_and_decrypt(public_key, identity, ciphertext, &signature)
58}
59
60/// Verify and decrypt the ciphertext using the signature
61pub fn verify_and_decrypt(
62    public_key: &PublicKey<Bls12381G2Impl>,
63    identity: &[u8],
64    ciphertext: &TimeCryptCiphertext<Bls12381G2Impl>,
65    signature: &Signature<Bls12381G2Impl>,
66) -> SdkResult<Vec<u8>> {
67    signature.verify(public_key, identity)?;
68    let plaintext = Option::<Vec<u8>>::from(ciphertext.decrypt(signature))
69        .ok_or_else(|| SdkError::Decryption("Decryption failure".to_string()))?;
70    Ok(plaintext)
71}