Skip to content

Commit

Permalink
impl Absorb for String (#138)
Browse files Browse the repository at this point in the history
* impl Absorb for String

* add String from ark_std

* absorb length when converting String to sponge bytes

* add test to ensure that absorbing two strings is different from concat
  • Loading branch information
mmagician authored Feb 10, 2024
1 parent ccf9d95 commit b93e005
Showing 1 changed file with 39 additions and 0 deletions.
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);
}
}

0 comments on commit b93e005

Please sign in to comment.