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

how to add tag/additionalData #559

Closed
nbari opened this issue Oct 26, 2023 · 2 comments
Closed

how to add tag/additionalData #559

nbari opened this issue Oct 26, 2023 · 2 comments

Comments

@nbari
Copy link

nbari commented Oct 26, 2023

I am trying to migrate this from go to rust

// Encrypt AES-256 GCM
func Encrypt(password, message, additionalData []byte) ([]byte, error) {
	if len(password) != 32 {
		return nil, fmt.Errorf("key size %d != 32", len(password))
	}

	c, err := aes.NewCipher(password)
	if err != nil {
		return nil, err
	}

	gcm, err := cipher.NewGCM(c)
	if err != nil {
		return nil, err
	}

	nonce, err := crypto.GenerateNonce(gcm.NonceSize())
	if err != nil {
		return nil, err
	}

	out := gcm.Seal(nonce, nonce, message, additionalData)
	return out, nil
}

From my understanding the AdditionalData is the tag, I am using this in rust:

fn encrypt(password: &[u8,32], data : &Vec<u8>)-> Result<Vec<u8>> { 
   let key = GenericArray::from_slice(password);
    let cipher = Aes256Gcm::new(key);
    let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
    cipher.encrypt(&nonce, data.as_ref()).map_or_else(
        |_| Err(anyhow!("Failed to encrypt data")),
        |ciphertext| {
            let mut encrypted_data = nonce.to_vec();
            encrypted_data.extend_from_slice(&ciphertext);
            Ok(encrypted_data)
        },
    )
}

But how do you pass the additionalData/Tag ?

@tarcieri
Copy link
Member

Instead of data.as_ref(), pass an aead::Payload instead: https://docs.rs/aead/latest/aead/struct.Payload.html

@nbari
Copy link
Author

nbari commented Oct 26, 2023

Hi, many thanks, just in case I soved using:

 let key = GenericArray::from_slice(password);
    let cipher = Aes256Gcm::new(key);
    let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
    let payload = Payload {
        msg: data.as_ref(),
        aad: additional_data.as_bytes(),
    };
    cipher.encrypt(&nonce, payload).map_or_else(
        |_| Err(anyhow!("Failed to encrypt data")),
        |ciphertext| {
            let mut encrypted_data = nonce.to_vec();
            encrypted_data.extend_from_slice(&ciphertext);
            Ok(encrypted_data)
        },
    )

@nbari nbari closed this as completed Oct 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants