Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

impl Absorb for String #138

Merged
merged 5 commits into from
Feb 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions crypto-primitives/src/sponge/absorb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use ark_ec::{
use ark_ff::models::{Fp, FpConfig};
use ark_ff::{BigInteger, Field, PrimeField, ToConstraintField};
use ark_serialize::CanonicalSerialize;
use ark_std::string::String;
use ark_std::vec::Vec;

pub use ark_crypto_primitives_macros::*;
Expand Down Expand Up @@ -229,6 +230,17 @@ impl Absorb for isize {
}
}

impl Absorb for String {
fn to_sponge_bytes(&self, dest: &mut Vec<u8>) {
self.len().to_sponge_bytes(dest);
dest.extend_from_slice(self.as_bytes())
}

fn to_sponge_field_elements<F: PrimeField>(&self, dest: &mut Vec<F>) {
self.as_bytes().to_sponge_field_elements(dest)
}
}

impl<P: TEModelParameters> Absorb for TEAffine<P>
where
P::BaseField: ToConstraintField<<P::BaseField as Field>::BasePrimeField>,
Expand Down Expand Up @@ -456,4 +468,31 @@ mod tests {
let out_manual = sponge.squeeze_bytes(32);
assert_eq!(out_derived, out_manual);
}

#[test]
fn test_string_absort() {
// absorbing two strings should not be the same as absorbing the concatenated string
let s1 = "hello".to_string();
let s2 = "world".to_string();

let mut dest1 = Vec::new();
s1.to_sponge_bytes(&mut dest1);
s2.to_sponge_bytes(&mut dest1);

let mut dest2 = Vec::new();
let s3 = "helloworld".to_string();
s3.to_sponge_bytes(&mut dest2);

assert_ne!(dest1, dest2);

// Same for converting to sponge field elements
let mut dest1: Vec<Fr> = Vec::new();
s1.to_sponge_field_elements(&mut dest1);
s2.to_sponge_field_elements(&mut dest1);

let mut dest2 = Vec::new();
s3.to_sponge_field_elements(&mut dest2);

assert_ne!(dest1, dest2);
}
}
Loading