snarkvm_circuit_program/data/ciphertext/
decrypt.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18impl<A: Aleo> Ciphertext<A> {
19    /// Decrypts `self` into plaintext using the given plaintext view key.
20    pub fn decrypt_symmetric(&self, plaintext_view_key: Field<A>) -> Plaintext<A> {
21        // Determine the number of randomizers needed to encrypt the plaintext.
22        let num_randomizers = self.num_randomizers();
23        // Prepare a randomizer for each field element.
24        let randomizers = A::hash_many_psd8(&[A::encryption_domain(), plaintext_view_key], num_randomizers);
25        // Decrypt the plaintext.
26        self.decrypt_with_randomizers(&randomizers)
27    }
28
29    /// Decrypts `self` into plaintext using the given randomizers.
30    pub(crate) fn decrypt_with_randomizers(&self, randomizers: &[Field<A>]) -> Plaintext<A> {
31        // Decrypt the ciphertext.
32        Plaintext::from_fields(
33            &self
34                .iter()
35                .zip_eq(randomizers)
36                .map(|(ciphertext, randomizer)| ciphertext - randomizer)
37                .collect::<Vec<_>>(),
38        )
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45    use crate::{Circuit, Literal};
46    use snarkvm_circuit_types::Field;
47    use snarkvm_utilities::{TestRng, Uniform};
48
49    use anyhow::Result;
50
51    const ITERATIONS: u64 = 100;
52
53    fn check_encrypt_and_decrypt<A: Aleo>() -> Result<()> {
54        let mut rng = TestRng::default();
55
56        // Prepare the plaintext.
57        let plaintext = Plaintext::<A>::from(Literal::Field(Field::new(Mode::Private, Uniform::rand(&mut rng))));
58
59        // Encrypt the plaintext.
60        let plaintext_view_key = Field::new(Mode::Private, Uniform::rand(&mut rng));
61        let ciphertext = plaintext.encrypt_symmetric(plaintext_view_key.clone());
62        // Decrypt the plaintext.
63        assert_eq!(plaintext.eject(), ciphertext.decrypt_symmetric(plaintext_view_key).eject());
64        Ok(())
65    }
66
67    #[test]
68    fn test_encrypt_and_decrypt() -> Result<()> {
69        for _ in 0..ITERATIONS {
70            check_encrypt_and_decrypt::<Circuit>()?;
71        }
72        Ok(())
73    }
74}