snarkvm_console_program/data/plaintext/encrypt.rs
1// Copyright 2024-2025 Aleo Network Foundation
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<N: Network> Plaintext<N> {
19 /// Encrypts `self` to the given address under the given randomizer.
20 pub fn encrypt(&self, address: &Address<N>, randomizer: Scalar<N>) -> Result<Ciphertext<N>> {
21 // Compute the plaintext view key.
22 let plaintext_view_key = (**address * randomizer).to_x_coordinate();
23 // Encrypt the plaintext.
24 self.encrypt_symmetric(plaintext_view_key)
25 }
26
27 /// Encrypts `self` under the given plaintext view key.
28 pub fn encrypt_symmetric(&self, plaintext_view_key: Field<N>) -> Result<Ciphertext<N>> {
29 // Determine the number of randomizers needed to encrypt the plaintext.
30 let num_randomizers = self.num_randomizers()?;
31 // Prepare a randomizer for each field element.
32 let randomizers = N::hash_many_psd8(&[N::encryption_domain(), plaintext_view_key], num_randomizers);
33 // Encrypt the plaintext.
34 self.encrypt_with_randomizers(&randomizers)
35 }
36
37 /// Encrypts `self` under the given randomizers.
38 pub(crate) fn encrypt_with_randomizers(&self, randomizers: &[Field<N>]) -> Result<Ciphertext<N>> {
39 // Encrypt the plaintext.
40 Ciphertext::from_fields(
41 &self
42 .to_fields()?
43 .into_iter()
44 .zip_eq(randomizers)
45 .map(|(plaintext, randomizer)| plaintext + randomizer)
46 .collect::<Vec<_>>(),
47 )
48 }
49}