Repository: novifinancial/opaque-ke
Pull request #108 (2020-12-30 07:34:01)

Updating envelope structure to support two fixed modes
To keep in sync with the changes in https://github.com/cfrg/draft-irtf-cfrg-opaque/pull/102.

The envelope will now support only two modes: a base mode, and a custom identifier mode. This means that we can get rid of the envelope credentials format that we were previously using, which also makes #58 obsolete.

This also addresses #104.

kevinlewi: @huitseeker for review

Patch:
diff --git a/src/envelope.rs b/src/envelope.rs
index 7212098..ec75e16 100644
--- a/src/envelope.rs
+++ b/src/envelope.rs
@@ -6,7 +6,7 @@
 use crate::{
     errors::{InternalPakeError, PakeError, ProtocolError},
     hash::Hash,
-    serialization::{serialize, tokenize, u8_to_credential_type, CredentialType},
+    serialization::{serialize, tokenize},
 };
 use digest::Digest;
 use generic_array::{
@@ -16,7 +16,7 @@ use generic_array::{
 use hkdf::Hkdf;
 use hmac::{Hmac, Mac, NewMac};
 use rand_core::{CryptoRng, RngCore};
-use std::collections::HashMap;
+use std::convert::TryFrom;
 
 // Constant string used as salt for HKDF computation
 const STR_ENVU: &[u8] = b"EnvU";
@@ -27,6 +27,23 @@ pub(crate) type ExportKeySize = U32;
 
 const NONCE_LEN: usize = 32;
 
+#[derive(Clone, Copy, PartialEq)]
+pub(crate) enum InnerEnvelopeMode {
+    Base = 0,
+    CustomIdentifier = 1,
+}
+
+impl TryFrom<u8> for InnerEnvelopeMode {
+    type Error = PakeError;
+    fn try_from(x: u8) -> Result<Self, Self::Error> {
+        match x {
+            0 => Ok(InnerEnvelopeMode::Base),
+            1 => Ok(InnerEnvelopeMode::CustomIdentifier),
+            _ => Err(PakeError::SerializationError),
+        }
+    }
+}
+
 /// This struct is an instantiation of the envelope as described in
 /// https://tools.ietf.org/html/draft-krawczyk-cfrg-opaque-06#section-4
 ///
@@ -38,61 +55,23 @@ const NONCE_LEN: usize = 32;
 /// an XOR-based approach without compromising on security, and to avoid
 /// the confusion around the implementation of an RKR-secure encryption.
 pub(crate) struct Envelope<D: Hash> {
+    mode: InnerEnvelopeMode,
     nonce: Vec<u8>,
     ciphertext: Vec<u8>,
     auth_data: Vec<u8>,
     hmac: GenericArray<u8, <D as Digest>::OutputSize>,
 }
 
-pub(crate) struct OpenedEnvelopeECF {
-    pub(crate) credentials_map: HashMap<CredentialType, Vec<u8>>,
+pub(crate) struct OpenedEnvelope {
+    pub(crate) client_s_sk: Vec<u8>,
     pub(crate) export_key: GenericArray<u8, ExportKeySize>,
 }
 
-pub(crate) struct OpenedEnvelope {
+pub(crate) struct OpenedInnerEnvelope {
     pub(crate) plaintext: Vec<u8>,
     pub(crate) export_key: GenericArray<u8, ExportKeySize>,
 }
 
-/// Representation for the format of the envelope
-pub struct EnvelopeCredentialsFormat {
-    pub(crate) secret_credentials: Vec<CredentialType>,
-    pub(crate) cleartext_credentials: Vec<CredentialType>,
-}
-
-impl EnvelopeCredentialsFormat {
-    /// Creates a new envelope credentials format with validity checking
-    /// An ECF is valid if:
-    /// - skU is a secret credential
-    /// - pkS is either a secret or cleartext credential
-    pub fn new(
-        secret_credentials: Vec<CredentialType>,
-        cleartext_credentials: Vec<CredentialType>,
-    ) -> Result<Self, ProtocolError> {
-        if !secret_credentials.iter().any(|&v| v == CredentialType::SkU) {
-            // No skU found in secret credentials
-            return Err(ProtocolError::ServerInvalidEnvelopeCredentialsFormatError);
-        }
-        if !secret_credentials.iter().any(|&v| v == CredentialType::PkS)
-            && !cleartext_credentials
-                .iter()
-                .any(|&v| v == CredentialType::PkS)
-        {
-            // No pkS found in either secret credentials or cleartext_credentials
-            return Err(ProtocolError::ServerInvalidEnvelopeCredentialsFormatError);
-        }
-        Ok(Self {
-            secret_credentials,
-            cleartext_credentials,
-        })
-    }
-
-    /// Uses the default setting for the envelope credentials format
-    pub fn default() -> Result<Self, ProtocolError> {
-        Self::new(vec![CredentialType::SkU], vec![CredentialType::PkS])
-    }
-}
-
 impl<D: Hash> Envelope<D> {
     /// The additional number of bytes added to the plaintext
     pub(crate) fn additional_size() -> usize {
@@ -107,13 +86,19 @@ impl<D: Hash> Envelope<D> {
         ExportKeySize::to_usize()
     }
 
+    pub(crate) fn get_mode(&self) -> InnerEnvelopeMode {
+        self.mode
+    }
+
     pub(crate) fn new(
+        mode: InnerEnvelopeMode,
         nonce: Vec<u8>,
         ciphertext: Vec<u8>,
         auth_data: Vec<u8>,
         hmac: GenericArray<u8, <D as Digest>::OutputSize>,
     ) -> Self {
         Self {
+            mode,
             nonce,
             ciphertext,
             auth_data,
@@ -122,13 +107,13 @@ impl<D: Hash> Envelope<D> {
     }
 
     /// The format of the output is:
-    /// nonce             | ciphertext       | hmac
-    /// nonce_size bytes  | variable length  | hmac_size bytes
+    /// mode | nonce             | ciphertext       | hmac
+    /// u8   | nonce_size bytes  | variable length  | hmac_size bytes
     pub(crate) fn from_bytes(bytes: &[u8]) -> Result<Self, InternalPakeError> {
         let (result, remainder) = Self::deserialize(bytes)
-            .map_err(|_| InternalPakeError::IncompatibleEnvelopeCredentialsError)?;
+            .map_err(|_| InternalPakeError::InvalidEnvelopeStructureError)?;
         if !remainder.is_empty() {
-            return Err(InternalPakeError::IncompatibleEnvelopeCredentialsError);
+            return Err(InternalPakeError::InvalidEnvelopeStructureError);
         }
         Ok(result)
     }
@@ -139,6 +124,7 @@ impl<D: Hash> Envelope<D> {
 
     pub(crate) fn serialize(&self) -> Vec<u8> {
         [
+            &[self.mode as u8],
             &self.nonce[..],
             &serialize(&self.ciphertext, 2)[..],
             &serialize(&self.auth_data, 2)[..],
@@ -148,18 +134,27 @@ impl<D: Hash> Envelope<D> {
     }
 
     pub(crate) fn deserialize(input: &[u8]) -> Result<(Self, Vec<u8>), ProtocolError> {
-        if input.len() < NONCE_LEN {
+        if input.is_empty() {
             return Err(ProtocolError::VerificationError(
                 PakeError::SerializationError,
             ));
         }
+        let mode = InnerEnvelopeMode::try_from(input[0])?;
 
-        let nonce = &input[..NONCE_LEN];
-        let (ciphertext, remainder) = tokenize(&input[NONCE_LEN..], 2)?;
+        let bytes = &input[1..];
+        if bytes.len() < NONCE_LEN {
+            return Err(ProtocolError::VerificationError(
+                PakeError::SerializationError,
+            ));
+        }
+
+        let nonce = &bytes[..NONCE_LEN];
+        let (ciphertext, remainder) = tokenize(&bytes[NONCE_LEN..], 2)?;
         let (auth_data, remainder) = tokenize(&remainder, 2)?;
         let (hmac, remainder) = tokenize(&remainder, 2)?;
         Ok((
             Self::new(
+                mode,
                 nonce.to_vec(),
                 ciphertext,
                 auth_data,
@@ -169,58 +164,26 @@ impl<D: Hash> Envelope<D> {
         ))
     }
 
-    fn serialize_extensions(
-        cred_format: Vec<CredentialType>,
-        credentials: &HashMap<CredentialType, Vec<u8>>,
-    ) -> Result<Vec<u8>, InternalPakeError> {
-        let mut ret = Vec::new();
-        for index_type in cred_format {
-            match &credentials.get(&index_type) {
-                Some(v) => {
-                    ret.push(index_type as u8 + 1);
-                    ret.extend(serialize(&v, 2));
-                }
-                None => return Err(InternalPakeError::IncompatibleEnvelopeCredentialsError),
-            }
-        }
-        Ok(ret)
-    }
-
-    fn deserialize_extensions(
-        bytes: &[u8],
-    ) -> Result<HashMap<CredentialType, Vec<u8>>, InternalPakeError> {
-        let mut credentials: HashMap<CredentialType, Vec<u8>> = HashMap::new();
-        let mut bytes_copy: Vec<u8> = Vec::new();
-        bytes_copy.extend_from_slice(&bytes);
-        while !bytes_copy.is_empty() {
-            let t = u8_to_credential_type(bytes_copy[0])
-                .ok_or(InternalPakeError::IncompatibleEnvelopeCredentialsError)?;
-            let (cred, remainder) = tokenize(&bytes_copy[1..], 2)
-                .map_err(|_| InternalPakeError::IncompatibleEnvelopeCredentialsError)?;
-            bytes_copy = remainder;
-            credentials.insert(t, cred);
-        }
-        Ok(credentials)
-    }
-
     pub(crate) fn seal<R: RngCore + CryptoRng>(
-        key: &[u8],
-        ecf: EnvelopeCredentialsFormat,
-        credentials: HashMap<CredentialType, Vec<u8>>,
         rng: &mut R,
+        key: &[u8],
+        client_s_sk: &[u8],
+        server_s_pk: &[u8],
+        optional_ids: Option<(Vec<u8>, Vec<u8>)>,
     ) -> Result<(Self, GenericArray<u8, ExportKeySize>), InternalPakeError> {
-        let plaintext = Self::serialize_extensions(ecf.secret_credentials, &credentials)?;
-        let aad = Self::serialize_extensions(ecf.cleartext_credentials, &credentials)?;
-        Self::seal_raw(key, &plaintext, &aad, rng)
+        let plaintext = serialize(&client_s_sk, 2);
+        let aad = construct_aad(server_s_pk, &optional_ids);
+        Self::seal_raw(rng, key, &plaintext, &aad, mode_from_ids(&optional_ids))
     }
 
     /// Uses a key to convert the plaintext into an envelope, authenticated by the aad field.
     /// Note that a new nonce is sampled for each call to seal.
     pub(crate) fn seal_raw<R: RngCore + CryptoRng>(
+        rng: &mut R,
         key: &[u8],
         plaintext: &[u8],
         aad: &[u8],
-        rng: &mut R,
+        mode: InnerEnvelopeMode,
     ) -> Result<(Self, GenericArray<u8, ExportKeySize>), InternalPakeError> {
         let mut nonce = vec![0u8; NONCE_LEN];
         rng.fill_bytes(&mut nonce);
@@ -247,6 +210,7 @@ impl<D: Hash> Envelope<D> {
 
         Ok((
             Self::new(
+                mode,
                 nonce,
                 ciphertext.to_vec(),
                 aad.to_vec(),
@@ -256,21 +220,29 @@ impl<D: Hash> Envelope<D> {
         ))
     }
 
-    pub(crate) fn open(&self, key: &[u8]) -> Result<OpenedEnvelopeECF, InternalPakeError> {
-        let mut credentials_map = Self::deserialize_extensions(&self.auth_data)?;
-        let opened = self.open_raw(key, &self.auth_data)?;
-        let plaintext_map = Self::deserialize_extensions(&opened.plaintext)?;
-
-        for (i, plaintext) in plaintext_map {
-            if credentials_map.contains_key(&i) {
-                // Trying to set a credential that was already provided in the aad
-                return Err(InternalPakeError::IncompatibleEnvelopeCredentialsError);
-            }
-            credentials_map.insert(i, plaintext);
+    pub(crate) fn open(
+        &self,
+        key: &[u8],
+        server_s_pk: &[u8],
+        optional_ids: &Option<(Vec<u8>, Vec<u8>)>,
+    ) -> Result<OpenedEnvelope, InternalPakeError> {
+        // First, check that mode matches
+        if self.mode != mode_from_ids(optional_ids) {
+            return Err(InternalPakeError::IncompatibleEnvelopeModeError);
         }
 
-        Ok(OpenedEnvelopeECF {
-            credentials_map,
+        let aad = construct_aad(server_s_pk, optional_ids);
+        let opened = self.open_raw(key, &aad)?;
+
+        let (client_s_sk, remainder) = tokenize(&opened.plaintext, 2)
+            .map_err(|_| InternalPakeError::UnexpectedEnvelopeContentsError)?;
+        if !remainder.is_empty() {
+            // Should not have anything else in plaintext
+            return Err(InternalPakeError::UnexpectedEnvelopeContentsError);
+        }
+
+        Ok(OpenedEnvelope {
+            client_s_sk,
             export_key: opened.export_key,
         })
     }
@@ -281,7 +253,7 @@ impl<D: Hash> Envelope<D> {
         &self,
         key: &[u8],
         aad: &[u8],
-    ) -> Result<OpenedEnvelope, InternalPakeError> {
+    ) -> Result<OpenedInnerEnvelope, InternalPakeError> {
         let h = Hkdf::<D>::new(Some(&self.nonce), &key);
         let mut okm =
             vec![0u8; self.ciphertext.len() + Self::hmac_key_size() + Self::export_key_size()];
@@ -305,13 +277,29 @@ impl<D: Hash> Envelope<D> {
             .zip(self.ciphertext.iter())
             .map(|(&x1, &x2)| x1 ^ x2)
             .collect();
-        Ok(OpenedEnvelope {
+        Ok(OpenedInnerEnvelope {
             plaintext,
             export_key: *GenericArray::from_slice(&export_key),
         })
     }
 }
 
+// Helper functions
+
+fn construct_aad(server_s_pk: &[u8], optional_ids: &Option<(Vec<u8>, Vec<u8>)>) -> Vec<u8> {
+    optional_ids
+        .iter()
+        .flat_map(|(l, r)| [serialize(server_s_pk, 2), serialize(l, 2), serialize(r, 2)].concat())
+        .collect()
+}
+
+pub(crate) fn mode_from_ids(optional_ids: &Option<(Vec<u8>, Vec<u8>)>) -> InnerEnvelopeMode {
+    match optional_ids {
+        Some(_) => InnerEnvelopeMode::CustomIdentifier,
+        None => InnerEnvelopeMode::Base,
+    }
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -326,8 +314,14 @@ mod tests {
         let mut msg = [0u8; 100];
         rng.fill_bytes(&mut msg);
 
-        let (envelope, export_key_1) =
-            Envelope::<sha2::Sha256>::seal_raw(&key, &msg, b"aad", &mut rng).unwrap();
+        let (envelope, export_key_1) = Envelope::<sha2::Sha256>::seal_raw(
+            &mut rng,
+            &key,
+            &msg,
+            b"aad",
+            InnerEnvelopeMode::Base,
+        )
+        .unwrap();
         let opened_envelope = envelope.open_raw(&key, b"aad").unwrap();
         assert_eq!(&msg.to_vec(), &opened_envelope.plaintext);
         assert_eq!(&export_key_1.to_vec(), &opened_envelope.export_key.to_vec());
diff --git a/src/errors.rs b/src/errors.rs
index ac2b642..1578770 100644
--- a/src/errors.rs
+++ b/src/errors.rs
@@ -46,7 +46,13 @@ pub enum InternalPakeError {
     SealOpenHmacError,
     /// This error occurs when the envelope cannot be constructed properly
     /// based on the credentials that were specified to be required.
-    IncompatibleEnvelopeCredentialsError,
+    InvalidEnvelopeStructureError,
+    /// This error occurs when attempting to open an envelope of the wrong
+    /// type (base mode, custom identifier)
+    IncompatibleEnvelopeModeError,
+    /// This error occurs when the envelope is opened and deserialization
+    /// fails
+    UnexpectedEnvelopeContentsError,
 }
 
 /// Represents an error in password checking
diff --git a/src/lib.rs b/src/lib.rs
index 44d0cd3..1d1e376 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -468,3 +468,8 @@ pub use crate::opaque::{
     ClientLoginFinishParameters, ClientLoginStartParameters, ClientRegistrationFinishParameters,
     ServerLoginStartParameters,
 };
+pub use crate::opaque::{
+    ClientLoginFinishResult, ClientLoginStartResult, ClientRegistrationFinishResult,
+    ClientRegistrationStartResult, ServerLoginFinishResult, ServerLoginStartResult,
+    ServerRegistrationStartResult,
+};
diff --git a/src/map_to_curve.rs b/src/map_to_curve.rs
index 20655a8..b5b58b1 100644
--- a/src/map_to_curve.rs
+++ b/src/map_to_curve.rs
@@ -19,14 +19,14 @@ use hkdf::Hkdf;
 /// A subtrait of Group specifying how to hash a password into a point
 pub trait GroupWithMapToCurve: Group {
     /// The ciphersuite identifier as dictated by
-    /// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-05.txt
+    /// <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-05.txt>
     const SUITE_ID: usize;
 
     /// transforms a password and domain separation tag (DST) into a curve point
     fn map_to_curve<H: Hash>(msg: &[u8], dst: &[u8]) -> Result<Self, InternalPakeError>;
 
     /// Generates the contextString parameter as defined in
-    /// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-05.txt
+    /// <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-05.txt>
     fn get_context_string(mode: u8) -> Vec<u8> {
         [i2osp(mode as usize, 1), i2osp(Self::SUITE_ID, 2)].concat()
     }
diff --git a/src/messages.rs b/src/messages.rs
index 543c941..f04b279 100644
--- a/src/messages.rs
+++ b/src/messages.rs
@@ -7,7 +7,7 @@
 
 use crate::{
     ciphersuite::CipherSuite,
-    envelope::{Envelope, EnvelopeCredentialsFormat},
+    envelope::Envelope,
     errors::{
         utils::{check_slice_size, check_slice_size_atleast},
         PakeError, ProtocolError,
@@ -16,7 +16,7 @@ use crate::{
     hash::Hash,
     key_exchange::traits::{KeyExchange, ToBytes},
     keypair::{KeyPair, SizedBytesExt},
-    serialization::{serialize, tokenize, u8_to_credential_type, CredentialType},
+    serialization::{serialize, tokenize},
 };
 use generic_array::{typenum::Unsigned, GenericArray};
 use generic_bytes::SizedBytes;
@@ -84,8 +84,6 @@ pub struct RegistrationResponse<Grp> {
     pub(crate) beta: Grp,
     /// Server's static public key
     pub(crate) server_s_pk: Vec<u8>,
-    /// Envelope credentials format
-    pub(crate) ecf: EnvelopeCredentialsFormat,
 }
 
 impl<Grp> TryFrom<&[u8]> for RegistrationResponse<Grp>
@@ -103,16 +101,10 @@ where
         let arr = GenericArray::from_slice(&checked_slice[..elem_len]);
         let beta = Grp::from_element_slice(arr)?;
 
+        // FIXME check public key bytes
         let server_s_pk = checked_slice[elem_len..].to_vec();
 
-        // Note that we use a default envelope credentials format here, since it
-        // is not included in the byte representation
-        let ecf = EnvelopeCredentialsFormat::default()?;
-        Ok(Self {
-            beta,
-            server_s_pk,
-            ecf,
-        })
+        Ok(Self { beta, server_s_pk })
     }
 }
 
@@ -131,27 +123,6 @@ where
         let mut registration_response: Vec<u8> = Vec::new();
         registration_response.extend_from_slice(&serialize(&self.beta.to_arr(), 2));
         registration_response.extend_from_slice(&serialize(&self.server_s_pk, 2));
-
-        // Handle ecf serialization
-        let secret_credentials: Vec<u8> = self
-            .ecf
-            .secret_credentials
-            .iter()
-            .map(|&x| x as u8 + 1)
-            .collect();
-        let cleartext_credentials: Vec<u8> = self
-            .ecf
-            .cleartext_credentials
-            .iter()
-            .map(|&x| x as u8 + 1)
-            .collect();
-        let ecf_serialized = [
-            serialize(&secret_credentials, 1),
-            serialize(&cleartext_credentials, 1),
-        ]
-        .concat();
-        registration_response.extend_from_slice(&ecf_serialized);
-
         registration_response
     }
 
@@ -160,19 +131,6 @@ where
         let (beta_bytes, remainder) = tokenize(&input, 2)?;
         let (server_s_pk, remainder) = tokenize(&remainder, 2)?;
 
-        // Handle ecf deserialization
-        let (secret_credentials, remainder) = tokenize(&remainder, 1)?;
-        let (cleartext_credentials, remainder) = tokenize(&remainder, 1)?;
-        let sc = secret_credentials
-            .iter()
-            .map(|x| u8_to_credential_type(*x).ok_or(PakeError::SerializationError))
-            .collect::<Result<Vec<CredentialType>, _>>()?;
-        let cc = cleartext_credentials
-            .iter()
-            .map(|x| u8_to_credential_type(*x).ok_or(PakeError::SerializationError))
-            .collect::<Result<Vec<CredentialType>, _>>()?;
-        let ecf = EnvelopeCredentialsFormat::new(sc, cc)?;
-
         if !remainder.is_empty() {
             return Err(PakeError::SerializationError.into());
         }
@@ -186,11 +144,7 @@ where
         // correct subgroup
         let arr = GenericArray::from_slice(&checked_slice);
         let beta = Grp::from_element_slice(arr)?;
-        Ok(Self {
-            ecf,
-            server_s_pk,
-            beta,
-        })
+        Ok(Self { server_s_pk, beta })
     }
 }
 
@@ -309,6 +263,7 @@ impl<CS: CipherSuite> CredentialRequest<CS> {
 pub struct CredentialResponse<CS: CipherSuite> {
     /// the server's oprf output
     pub(crate) beta: CS::Group,
+    pub(crate) server_s_pk: <CS::KeyFormat as KeyPair>::Repr,
     /// the user's sealed information,
     pub(crate) envelope: Envelope<CS::Hash>,
     pub(crate) ke2_message: <CS::KeyExchange as KeyExchange<CS::Hash, CS::KeyFormat>>::KE2Message,
@@ -319,6 +274,7 @@ impl<CS: CipherSuite> CredentialResponse<CS> {
     pub fn serialize(&self) -> Vec<u8> {
         let mut credential_response: Vec<u8> = Vec::new();
         credential_response.extend_from_slice(&serialize(&self.beta.to_arr(), 2));
+        credential_response.extend_from_slice(&serialize(&self.server_s_pk.to_arr().to_vec(), 2));
         credential_response.extend_from_slice(&self.envelope.to_bytes());
         credential_response.extend_from_slice(&self.ke2_message.to_bytes());
         credential_response
@@ -326,8 +282,12 @@ impl<CS: CipherSuite> CredentialResponse<CS> {
 
     /// Deserialization from bytes
     pub fn deserialize(input: &[u8]) -> Result<Self, ProtocolError> {
-        let (beta_bytes, envelope_and_ke2m_bytes) = tokenize(&input, 2)?;
-        let concatenated = [&beta_bytes[..], &envelope_and_ke2m_bytes[..]].concat();
+        let (beta_bytes, server_s_pk_and_envelope_and_ke2m_bytes) = tokenize(&input, 2)?;
+        let concatenated = [
+            &beta_bytes[..],
+            &server_s_pk_and_envelope_and_ke2m_bytes[..],
+        ]
+        .concat();
         Self::try_from(&concatenated[..])
     }
 }
@@ -345,7 +305,17 @@ impl<CS: CipherSuite> TryFrom<&[u8]> for CredentialResponse<CS> {
         let arr = GenericArray::from_slice(beta_bytes);
         let beta = CS::Group::from_element_slice(arr)?;
 
-        let (envelope, remainder) = Envelope::<CS::Hash>::deserialize(&checked_slice[elem_len..])?;
+        let (serialized_server_s_pk, remainder) = tokenize(&checked_slice[elem_len..], 2)?;
+        let sized_server_s_pk = check_slice_size(
+            &serialized_server_s_pk[..],
+            <<CS::KeyFormat as KeyPair>::Repr as SizedBytes>::Len::to_usize(),
+            "server_s_pk in credential_response",
+        )?;
+        let unchecked_server_s_pk =
+            <CS::KeyFormat as KeyPair>::Repr::from_bytes(&sized_server_s_pk[..])?;
+        let server_s_pk = CS::KeyFormat::check_public_key(unchecked_server_s_pk)?;
+
+        let (envelope, remainder) = Envelope::<CS::Hash>::deserialize(&remainder)?;
 
         let ke2_message_size = CS::KeyExchange::ke2_message_size();
         let checked_remainder =
@@ -357,6 +327,7 @@ impl<CS: CipherSuite> TryFrom<&[u8]> for CredentialResponse<CS> {
 
         Ok(Self {
             beta,
+            server_s_pk,
             envelope,
             ke2_message,
         })
diff --git a/src/opaque.rs b/src/opaque.rs
index a769ca1..4596d64 100644
--- a/src/opaque.rs
+++ b/src/opaque.rs
@@ -7,7 +7,7 @@
 
 use crate::{
     ciphersuite::CipherSuite,
-    envelope::{Envelope, EnvelopeCredentialsFormat, ExportKeySize},
+    envelope::{mode_from_ids, Envelope, ExportKeySize},
     errors::{utils::check_slice_size_atleast, InternalPakeError, PakeError, ProtocolError},
     group::Group,
     hash::Hash,
@@ -15,7 +15,7 @@ use crate::{
     keypair::{KeyPair, SizedBytesExt},
     map_to_curve::GroupWithMapToCurve,
     oprf,
-    serialization::{serialize, tokenize, CredentialType},
+    serialization::serialize,
     slow_hash::SlowHash,
     CredentialFinalization, CredentialRequest, CredentialResponse, RegistrationRequest,
     RegistrationResponse, RegistrationUpload,
@@ -23,7 +23,6 @@ use crate::{
 use generic_array::{typenum::Unsigned, GenericArray};
 use generic_bytes::SizedBytes;
 use rand_core::{CryptoRng, RngCore};
-use std::collections::HashMap;
 use std::{convert::TryFrom, marker::PhantomData};
 use zeroize::Zeroize;
 
@@ -81,13 +80,15 @@ impl<CS: CipherSuite> ClientRegistration<CS> {
 
 /// Optional parameters for client registration finish
 pub enum ClientRegistrationFinishParameters {
-    /// Specifying the identifiers idU and idS
+    /// Specifying the identifiers idU and idS (corresponding to custom identifier mode)
     WithIdentifiers(Vec<u8>, Vec<u8>),
+    /// No identifiers specified (corresponding to base mode)
+    Default,
 }
 
 impl Default for ClientRegistrationFinishParameters {
     fn default() -> Self {
-        Self::WithIdentifiers(Vec::new(), Vec::new())
+        Self::Default
     }
 }
 
@@ -176,7 +177,7 @@ impl<CS: CipherSuite> ClientRegistration<CS> {
     /// }
     /// let mut client_rng = OsRng;
     /// let mut server_rng = OsRng;
-    /// let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
+    /// let server_kp = Default::generate_random_keypair(&mut server_rng)?;
     /// let client_registration_start_result = ClientRegistration::<Default>::start(&mut client_rng, b"hunter2")?;
     /// let server_registration_start_result =
     /// ServerRegistration::<Default>::start(&mut server_rng, client_registration_start_result.message, server_kp.public())?;
@@ -190,29 +191,22 @@ impl<CS: CipherSuite> ClientRegistration<CS> {
         r2: RegistrationResponse<CS::Group>,
         params: ClientRegistrationFinishParameters,
     ) -> Result<ClientRegistrationFinishResult<CS::KeyFormat, CS::Hash>, ProtocolError> {
-        let (id_u, id_s) = match params {
-            ClientRegistrationFinishParameters::WithIdentifiers(id_u, id_s) => (id_u, id_s),
+        let optional_ids = match params {
+            ClientRegistrationFinishParameters::WithIdentifiers(id_u, id_s) => Some((id_u, id_s)),
+            ClientRegistrationFinishParameters::Default => None,
         };
-        let client_static_keypair = CS::KeyFormat::generate_random(rng)?;
+        let client_static_keypair = CS::generate_random_keypair(rng)?;
 
         let password_derived_key =
             get_password_derived_key::<CS::Group, CS::SlowHash, CS::Hash>(&self.token, r2.beta)?;
 
-        let mut credentials_map: HashMap<CredentialType, Vec<u8>> = HashMap::new();
-        credentials_map.insert(
-            CredentialType::SkU,
-            client_static_keypair.private().to_arr().to_vec(),
-        );
-        credentials_map.insert(
-            CredentialType::PkU,
-            client_static_keypair.public().to_arr().to_vec(),
-        );
-        credentials_map.insert(CredentialType::PkS, r2.server_s_pk);
-        credentials_map.insert(CredentialType::IdU, id_u);
-        credentials_map.insert(CredentialType::IdS, id_s);
-
-        let (envelope, export_key) =
-            Envelope::<CS::Hash>::seal(&password_derived_key, r2.ecf, credentials_map, rng)?;
+        let (envelope, export_key) = Envelope::<CS::Hash>::seal(
+            rng,
+            &password_derived_key,
+            &client_static_keypair.private().to_arr().to_vec(),
+            &r2.server_s_pk,
+            optional_ids,
+        )?;
 
         Ok(ClientRegistrationFinishResult {
             message: RegistrationUpload {
@@ -357,7 +351,7 @@ where
     /// }
     /// let mut client_rng = OsRng;
     /// let mut server_rng = OsRng;
-    /// let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
+    /// let server_kp = Default::generate_random_keypair(&mut server_rng)?;
     /// let client_registration_start_result = ClientRegistration::<Default>::start(&mut client_rng, b"hunter2")?;
     /// let server_registration_start_result = ServerRegistration::<Default>::start(&mut server_rng, client_registration_start_result.message, server_kp.public())?;
     /// # Ok::<(), ProtocolError>(())
@@ -377,7 +371,6 @@ where
             message: RegistrationResponse {
                 beta,
                 server_s_pk: server_s_pk.to_arr().to_vec(),
-                ecf: EnvelopeCredentialsFormat::default()?,
             },
             state: Self {
                 envelope: None,
@@ -410,7 +403,7 @@ where
     /// }
     /// let mut client_rng = OsRng;
     /// let mut server_rng = OsRng;
-    /// let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
+    /// let server_kp = Default::generate_random_keypair(&mut server_rng)?;
     /// let client_registration_start_result = ClientRegistration::<Default>::start(&mut client_rng, b"hunter2")?;
     /// let server_registration_start_result = ServerRegistration::<Default>::start(&mut server_rng, client_registration_start_result.message, server_kp.public())?;
     /// let mut client_rng = OsRng;
@@ -435,10 +428,6 @@ where
 
 /// The state elements the client holds to perform a login
 pub struct ClientLogin<CS: CipherSuite> {
-    /// User identity
-    id_u: Vec<u8>,
-    /// Server identity
-    id_s: Vec<u8>,
     /// token containing the client's password and the blinding factor
     token: oprf::Token<CS::Group>,
     ke1_state: <CS::KeyExchange as KeyExchange<CS::Hash, CS::KeyFormat>>::KE1State,
@@ -447,22 +436,19 @@ pub struct ClientLogin<CS: CipherSuite> {
 impl<CS: CipherSuite> TryFrom<&[u8]> for ClientLogin<CS> {
     type Error = ProtocolError;
     fn try_from(input: &[u8]) -> Result<Self, Self::Error> {
-        let (id_u, bytes) = tokenize(&input, 2)?;
-        let (id_s, bytes) = tokenize(&bytes, 2)?;
-
         let scalar_len = <CS::Group as Group>::ScalarLen::to_usize();
         let ke1_state_size =
             <CS::KeyExchange as KeyExchange<CS::Hash, CS::KeyFormat>>::ke1_state_size();
 
         let min_expected_len = scalar_len + ke1_state_size;
-        let checked_slice = (if bytes.len() <= min_expected_len {
+        let checked_slice = (if input.len() <= min_expected_len {
             Err(InternalPakeError::SizeError {
                 name: "client_login_bytes",
                 len: min_expected_len,
-                actual_len: bytes.len(),
+                actual_len: input.len(),
             })
         } else {
-            Ok(bytes.clone())
+            Ok(input)
         })?;
 
         let blinding_factor_bytes = GenericArray::from_slice(&checked_slice[..scalar_len]);
@@ -471,10 +457,8 @@ impl<CS: CipherSuite> TryFrom<&[u8]> for ClientLogin<CS> {
             <CS::KeyExchange as KeyExchange<CS::Hash, CS::KeyFormat>>::KE1State::try_from(
                 &checked_slice[scalar_len..scalar_len + ke1_state_size],
             )?;
-        let password = bytes[scalar_len + ke1_state_size..].to_vec();
+        let password = input[scalar_len + ke1_state_size..].to_vec();
         Ok(Self {
-            id_u,
-            id_s,
             token: oprf::Token {
                 data: password,
                 blind: blinding_factor,
@@ -488,8 +472,6 @@ impl<CS: CipherSuite> ClientLogin<CS> {
     /// byte representation for the client's login state
     pub fn to_bytes(&self) -> Vec<u8> {
         let output: Vec<u8> = [
-            &serialize(&self.id_u, 2),
-            &serialize(&self.id_s, 2),
             &CS::Group::scalar_as_bytes(&self.token.blind)[..],
             &self.ke1_state.to_bytes(),
             &self.token.data,
@@ -503,13 +485,11 @@ impl<CS: CipherSuite> ClientLogin<CS> {
 pub enum ClientLoginStartParameters {
     /// Specifying an info field that will be sent to the server
     WithInfo(Vec<u8>),
-    /// Specifying the info field along with idU and idS
-    WithInfoAndIdentifiers(Vec<u8>, Vec<u8>, Vec<u8>),
 }
 
 impl Default for ClientLoginStartParameters {
     fn default() -> Self {
-        Self::WithInfoAndIdentifiers(Vec::new(), Vec::new(), Vec::new())
+        Self::WithInfo(Vec::new())
     }
 }
 
@@ -525,11 +505,18 @@ pub struct ClientLoginStartResult<CS: CipherSuite> {
 pub enum ClientLoginFinishParameters {
     /// Specifying an info and confidential info field that will be sent to the server
     WithInfo(Vec<u8>, Vec<u8>),
+    /// Specifying an id_u and id_s that will be matched against the server
+    WithIdentifiers(Vec<u8>, Vec<u8>),
+    /// Specifying an info, confidential info that will be sent to the server,
+    /// along with an id_u and id_s that will be matched against the server
+    WithInfoAndIdentifiers(Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>),
+    /// No info and no custom identifiers
+    Default,
 }
 
 impl Default for ClientLoginFinishParameters {
     fn default() -> Self {
-        Self::WithInfo(Vec::new(), Vec::new())
+        Self::Default
     }
 }
 
@@ -543,8 +530,6 @@ pub struct ClientLoginFinishResult<CS: CipherSuite> {
     pub export_key: GenericArray<u8, ExportKeySize>,
     /// The server's static public key
     pub server_s_pk: Vec<u8>,
-    /// An optional id_s if supplied by the server
-    pub id_s: Option<Vec<u8>>,
     /// The plaintext info sent by the client
     pub plain_info: Vec<u8>,
     /// The confidential info sent by the client
@@ -582,12 +567,7 @@ impl<CS: CipherSuite> ClientLogin<CS> {
         params: ClientLoginStartParameters,
         #[cfg(test)] postprocess: fn(<CS::Group as Group>::Scalar) -> <CS::Group as Group>::Scalar,
     ) -> Result<ClientLoginStartResult<CS>, ProtocolError> {
-        let (info, id_u, id_s) = match params {
-            ClientLoginStartParameters::WithInfo(info) => (info, Vec::new(), Vec::new()),
-            ClientLoginStartParameters::WithInfoAndIdentifiers(info, id_u, id_s) => {
-                (info, id_u, id_s)
-            }
-        };
+        let ClientLoginStartParameters::WithInfo(info) = params;
 
         let (token, alpha) = oprf::blind::<R, CS::Group, CS::Hash>(
             &password,
@@ -603,12 +583,7 @@ impl<CS: CipherSuite> ClientLogin<CS> {
 
         Ok(ClientLoginStartResult {
             message: l1,
-            state: Self {
-                id_u,
-                id_s,
-                token,
-                ke1_state,
-            },
+            state: Self { token, ke1_state },
         })
     }
 
@@ -638,7 +613,7 @@ impl<CS: CipherSuite> ClientLogin<CS> {
     /// let mut client_rng = OsRng;
     /// # let mut server_rng = OsRng;
     /// # let client_registration_start_result = ClientRegistration::<Default>::start(&mut client_rng, b"hunter2")?;
-    /// # let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
+    /// # let server_kp = Default::generate_random_keypair(&mut server_rng)?;
     /// # let server_registration_start_result = ServerRegistration::<Default>::start(&mut server_rng, client_registration_start_result.message, server_kp.public())?;
     /// # let client_registration_finish_result = client_registration_start_result.state.finish(&mut client_rng, server_registration_start_result.message, ClientRegistrationFinishParameters::default())?;
     /// # let p_file = server_registration_start_result.state.finish(client_registration_finish_result.message)?;
@@ -652,48 +627,62 @@ impl<CS: CipherSuite> ClientLogin<CS> {
         l2: CredentialResponse<CS>,
         params: ClientLoginFinishParameters,
     ) -> Result<ClientLoginFinishResult<CS>, ProtocolError> {
-        let (info, e_info) = match params {
-            ClientLoginFinishParameters::WithInfo(info, e_info) => (info, e_info),
+        let (info, e_info, optional_ids) = match params {
+            ClientLoginFinishParameters::Default => (Vec::new(), Vec::new(), None),
+            ClientLoginFinishParameters::WithInfo(info, e_info) => (info, e_info, None),
+            ClientLoginFinishParameters::WithIdentifiers(id_u, id_s) => {
+                (Vec::new(), Vec::new(), Some((id_u, id_s)))
+            }
+            ClientLoginFinishParameters::WithInfoAndIdentifiers(info, e_info, id_u, id_s) => {
+                (info, e_info, Some((id_u, id_s)))
+            }
         };
 
-        let l2_bytes: Vec<u8> = [&l2.beta.to_arr()[..], &l2.envelope.to_bytes()].concat();
+        let l2_beta_bytes = &l2.beta.to_arr()[..];
 
         let password_derived_key =
             get_password_derived_key::<CS::Group, CS::SlowHash, CS::Hash>(&self.token, l2.beta)?;
 
         let opened_envelope = &l2
             .envelope
-            .open(&password_derived_key)
+            .open(
+                &password_derived_key,
+                &l2.server_s_pk.to_arr().to_vec(),
+                &optional_ids,
+            )
             .map_err(|e| match e {
                 InternalPakeError::SealOpenHmacError => PakeError::InvalidLoginError,
                 err => PakeError::from(err),
             })?;
 
-        let client_s_sk = <CS::KeyFormat as KeyPair>::Repr::from_bytes(
-            &opened_envelope.credentials_map[&CredentialType::SkU],
-        )?;
-        let server_s_pk = <CS::KeyFormat as KeyPair>::Repr::from_bytes(
-            &opened_envelope.credentials_map[&CredentialType::PkS],
-        )?;
+        let client_s_sk =
+            <CS::KeyFormat as KeyPair>::Repr::from_bytes(&opened_envelope.client_s_sk)?;
 
-        let id_u = match opened_envelope.credentials_map.get(&CredentialType::IdU) {
-            Some(id_u) => id_u.clone(),
-            None => CS::KeyFormat::public_from_private(&client_s_sk)
-                .to_arr()
-                .to_vec(),
-        };
+        let server_s_pk_bytes = l2.server_s_pk.to_arr().to_vec();
 
-        let (id_s, ret_id_s) = match opened_envelope.credentials_map.get(&CredentialType::IdS) {
-            Some(id_s) => (id_s.clone(), Some(id_s.clone())),
-            None => (server_s_pk.to_arr().to_vec(), None),
+        let (id_u, id_s) = match optional_ids {
+            None => (
+                CS::KeyFormat::public_from_private(&client_s_sk)
+                    .to_arr()
+                    .to_vec(),
+                server_s_pk_bytes.clone(),
+            ),
+            Some((id_u, id_s)) => (id_u, id_s),
         };
 
+        let l2_bytes: Vec<u8> = [
+            serialize(&l2_beta_bytes, 2),
+            serialize(&server_s_pk_bytes, 2),
+            l2.envelope.to_bytes(),
+        ]
+        .concat();
+
         let (plain_info, confidential_info, shared_secret, ke3_message) =
             CS::KeyExchange::generate_ke3(
                 l2_bytes,
                 l2.ke2_message,
                 &self.ke1_state,
-                server_s_pk.clone(),
+                l2.server_s_pk,
                 client_s_sk,
                 id_u,
                 id_s,
@@ -707,8 +696,7 @@ impl<CS: CipherSuite> ClientLogin<CS> {
             message: CredentialFinalization { ke3_message },
             shared_secret,
             export_key: opened_envelope.export_key,
-            server_s_pk: server_s_pk.to_arr().to_vec(),
-            id_s: ret_id_s,
+            server_s_pk: server_s_pk_bytes,
         })
     }
 }
@@ -736,6 +724,8 @@ impl<CS: CipherSuite> TryFrom<&[u8]> for ServerLogin<CS> {
 pub enum ServerLoginStartParameters {
     /// Specifying an info and confidential info field that will be sent to the client
     WithInfo(Vec<u8>, Vec<u8>),
+    /// Specifying an id_u and id_s that will be matched against the client
+    WithIdentifiers(Vec<u8>, Vec<u8>),
     /// Specifying an info, confidential info that will be sent to the client,
     /// along with an id_u and id_s that will be matched against the client
     WithInfoAndIdentifiers(Vec<u8>, Vec<u8>, Vec<u8>, Vec<u8>),
@@ -769,8 +759,6 @@ pub struct ServerLoginFinishResult {
     pub confidential_info: Vec<u8>,
 }
 
-impl ServerLoginFinishResult {}
-
 impl<CS: CipherSuite> ServerLogin<CS> {
     /// byte representation for the server's login state
     pub fn to_bytes(&self) -> Vec<u8> {
@@ -802,7 +790,7 @@ impl<CS: CipherSuite> ServerLogin<CS> {
     /// }
     /// let mut client_rng = OsRng;
     /// let mut server_rng = OsRng;
-    /// let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
+    /// let server_kp = Default::generate_random_keypair(&mut server_rng)?;
     /// # let client_registration_start_result = ClientRegistration::<Default>::start(&mut client_rng, b"hunter2")?;
     /// # let server_registration_start_result = ServerRegistration::<Default>::start(&mut server_rng, client_registration_start_result.message, server_kp.public())?;
     /// # let client_registration_finish_result = client_registration_start_result.state.finish(&mut client_rng, server_registration_start_result.message, ClientRegistrationFinishParameters::default())?;
@@ -822,29 +810,42 @@ impl<CS: CipherSuite> ServerLogin<CS> {
             .client_s_pk
             .ok_or(InternalPakeError::SealError)?;
 
-        let (info, e_info, id_u, id_s) = match params {
-            ServerLoginStartParameters::WithInfo(info, e_info) => (info, e_info, None, None),
+        let (info, e_info, optional_ids) = match params {
+            ServerLoginStartParameters::WithInfo(info, e_info) => (info, e_info, None),
+            ServerLoginStartParameters::WithIdentifiers(id_u, id_s) => {
+                (Vec::new(), Vec::new(), Some((id_u, id_s)))
+            }
             ServerLoginStartParameters::WithInfoAndIdentifiers(info, e_info, id_u, id_s) => {
-                (info, e_info, Some(id_u), Some(id_s))
+                (info, e_info, Some((id_u, id_s)))
             }
         };
 
-        let id_u = match id_u {
-            Some(id_u) => id_u,
-            None => client_s_pk.to_arr().to_vec(),
-        };
+        let envelope = password_file.envelope.ok_or(InternalPakeError::SealError)?;
+        if envelope.get_mode() != mode_from_ids(&optional_ids) {
+            return Err(InternalPakeError::IncompatibleEnvelopeModeError.into());
+        }
 
-        let id_s = match id_s {
-            Some(id_s) => id_s,
-            None => CS::KeyFormat::public_from_private(server_s_sk)
-                .to_arr()
-                .to_vec(),
+        let (id_u, id_s) = match optional_ids {
+            None => (
+                client_s_pk.to_arr().to_vec(),
+                CS::KeyFormat::public_from_private(server_s_sk)
+                    .to_arr()
+                    .to_vec(),
+            ),
+            Some((id_u, id_s)) => (id_u, id_s),
         };
 
         let l1_bytes = &l1.to_bytes();
         let beta = oprf::evaluate(l1.alpha, &password_file.oprf_key);
-        let envelope = password_file.envelope.ok_or(InternalPakeError::SealError)?;
-        let l2_component: Vec<u8> = [&beta.to_arr()[..], &envelope.to_bytes()].concat();
+
+        let server_s_pk = CS::KeyFormat::public_from_private(&server_s_sk);
+
+        let l2_component: Vec<u8> = [
+            serialize(&beta.to_arr()[..], 2),
+            serialize(&server_s_pk.to_arr()[..], 2),
+            envelope.to_bytes(),
+        ]
+        .concat();
 
         let (plain_info, ke2_state, ke2_message) = CS::KeyExchange::generate_ke2(
             rng,
@@ -861,6 +862,7 @@ impl<CS: CipherSuite> ServerLogin<CS> {
 
         let l2 = CredentialResponse {
             beta,
+            server_s_pk,
             envelope,
             ke2_message,
         };
@@ -901,7 +903,7 @@ impl<CS: CipherSuite> ServerLogin<CS> {
     /// }
     /// let mut client_rng = OsRng;
     /// let mut server_rng = OsRng;
-    /// let server_kp = X25519KeyPair::generate_random(&mut server_rng)?;
+    /// let server_kp = Default::generate_random_keypair(&mut server_rng)?;
     /// # let client_registration_start_result = ClientRegistration::<Default>::start(&mut client_rng, b"hunter2")?;
     /// # let server_registration_start_result = ServerRegistration::<Default>::start(&mut server_rng, client_registration_start_result.message, server_kp.public())?;
     /// # let client_registration_finish_result = client_registration_start_result.state.finish(&mut client_rng, server_registration_start_result.message, ClientRegistrationFinishParameters::default())?;
diff --git a/src/serialization/mod.rs b/src/serialization/mod.rs
index aa8582e..eb51f03 100644
--- a/src/serialization/mod.rs
+++ b/src/serialization/mod.rs
@@ -5,26 +5,6 @@
 
 use crate::errors::PakeError;
 
-#[derive(Copy, Clone, Eq, Hash, PartialEq)]
-pub enum CredentialType {
-    SkU,
-    PkU,
-    PkS,
-    IdU,
-    IdS,
-}
-
-pub(crate) fn u8_to_credential_type(x: u8) -> Option<CredentialType> {
-    match x {
-        1 => Some(CredentialType::SkU),
-        2 => Some(CredentialType::PkU),
-        3 => Some(CredentialType::PkS),
-        4 => Some(CredentialType::IdU),
-        5 => Some(CredentialType::IdS),
-        _ => None,
-    }
-}
-
 // Corresponds to the I2OSP() function from RFC8017
 pub(crate) fn i2osp(input: usize, length: usize) -> Vec<u8> {
     if length <= std::mem::size_of::<usize>() {


Test patch:
diff --git a/src/serialization/tests.rs b/src/serialization/tests.rs
index 5e06710..c179e2a 100644
--- a/src/serialization/tests.rs
+++ b/src/serialization/tests.rs
@@ -5,7 +5,7 @@
 
 use crate::{
     ciphersuite::CipherSuite,
-    envelope::Envelope,
+    envelope::{Envelope, InnerEnvelopeMode},
     group::Group,
     key_exchange::{
         traits::{KeyExchange, ToBytes},
@@ -34,7 +34,6 @@ impl CipherSuite for Default {
     type SlowHash = crate::slow_hash::NoOpHash;
 }
 
-const MAX_ID_LENGTH: usize = 10;
 const MAX_INFO_LENGTH: usize = 10;
 
 fn random_ristretto_point() -> RistrettoPoint {
@@ -80,6 +79,7 @@ fn server_registration_roundtrip() {
 
     // Construct a mock envelope
     let mut mock_envelope_bytes = Vec::new();
+    mock_envelope_bytes.extend_from_slice(&[0; 1]); // mode = 0
     mock_envelope_bytes.extend_from_slice(&[0; NONCE_LEN]); // empty nonce
     mock_envelope_bytes.extend_from_slice(&[0, 0]); // empty ciphertext
     mock_envelope_bytes.extend_from_slice(&[0, 0]); // empty auth_data
@@ -121,7 +121,6 @@ fn register_second_message_roundtrip() {
     let mut rng = OsRng;
     let skp = Default::generate_random_keypair(&mut rng).unwrap();
     let pubkey_bytes = skp.public().to_arr();
-    let credential_types = [1, 1, 1, 3];
 
     let beta_length: usize = beta_bytes.len();
     let pubkey_length: usize = pubkey_bytes.len();
@@ -131,7 +130,6 @@ fn register_second_message_roundtrip() {
     input.extend_from_slice(beta_bytes.as_slice());
     input.extend_from_slice(&pubkey_length.to_be_bytes()[std::mem::size_of::<usize>() - 2..]);
     input.extend_from_slice(&pubkey_bytes.as_slice());
-    input.extend_from_slice(&credential_types);
 
     let r2 = RegistrationResponse::<RistrettoPoint>::deserialize(input.as_slice()).unwrap();
     let r2_bytes = r2.serialize();
@@ -150,8 +148,14 @@ fn register_third_message_roundtrip() {
     let mut msg = [0u8; 32];
     rng.fill_bytes(&mut msg);
 
-    let (envelope, _) =
-        Envelope::<sha2::Sha256>::seal_raw(&key, &msg, &pubkey_bytes, &mut rng).unwrap();
+    let (envelope, _) = Envelope::<sha2::Sha256>::seal_raw(
+        &mut rng,
+        &key,
+        &msg,
+        &pubkey_bytes,
+        InnerEnvelopeMode::Base,
+    )
+    .unwrap();
     let envelope_bytes = envelope.serialize();
 
     let pubkey_length: usize = pubkey_bytes.len();
@@ -206,6 +210,7 @@ fn login_second_message_roundtrip() {
     let mut rng = OsRng;
     let skp = Default::generate_random_keypair(&mut rng).unwrap();
     let pubkey_bytes = skp.public().to_arr();
+    let pubkey_length: usize = pubkey_bytes.len();
 
     let mut key = [0u8; 32];
     rng.fill_bytes(&mut key);
@@ -213,8 +218,14 @@ fn login_second_message_roundtrip() {
     let mut msg = [0u8; 32];
     rng.fill_bytes(&mut msg);
 
-    let (envelope, _) =
-        Envelope::<sha2::Sha256>::seal_raw(&key, &msg, &pubkey_bytes, &mut rng).unwrap();
+    let (envelope, _) = Envelope::<sha2::Sha256>::seal_raw(
+        &mut rng,
+        &key,
+        &msg,
+        &pubkey_bytes,
+        InnerEnvelopeMode::Base,
+    )
+    .unwrap();
 
     let server_e_kp = Default::generate_random_keypair(&mut rng).unwrap();
     let mut mac = [0u8; 32];
@@ -239,6 +250,8 @@ fn login_second_message_roundtrip() {
     let mut input = Vec::new();
     input.extend_from_slice(&pt_bytes.len().to_be_bytes()[std::mem::size_of::<usize>() - 2..]);
     input.extend_from_slice(pt_bytes.as_slice());
+    input.extend_from_slice(&pubkey_length.to_be_bytes()[std::mem::size_of::<usize>() - 2..]);
+    input.extend_from_slice(&pubkey_bytes.as_slice());
     input.extend_from_slice(&envelope.serialize());
     input.extend_from_slice(&ke2m[..]);
 
@@ -273,13 +286,6 @@ fn login_third_message_roundtrip() {
 fn client_login_roundtrip() {
     let pw = b"hunter2";
     let mut rng = OsRng;
-    let id_u_length: usize = rng.gen_range(0, MAX_ID_LENGTH);
-    let id_s_length: usize = rng.gen_range(0, MAX_ID_LENGTH);
-    let mut id_u = [0u8; MAX_ID_LENGTH];
-    rng.fill_bytes(&mut id_u);
-    let mut id_s = [0u8; MAX_ID_LENGTH];
-    rng.fill_bytes(&mut id_s);
-
     let sc = <RistrettoPoint as Group>::random_scalar(&mut rng);
 
     let client_e_kp = Default::generate_random_keypair(&mut rng).unwrap();
@@ -291,10 +297,8 @@ fn client_login_roundtrip() {
     hasher.update(l1_data);
     let hashed_l1 = hasher.finalize();
 
-    // serialization order: id_u, id_s, scalar, password, ke1_state
+    // serialization order: scalar, password, ke1_state
     let bytes: Vec<u8> = [
-        &serialize(&id_u[..id_u_length], 2)[..],
-        &serialize(&id_s[..id_s_length], 2)[..],
         &sc.as_bytes()[..],
         &pw[..],
         client_e_kp.public(),
diff --git a/src/tests/opaque_ke_test.rs b/src/tests/opaque_ke_test.rs
index b30d170..2969ec6 100644
--- a/src/tests/opaque_ke_test.rs
+++ b/src/tests/opaque_ke_test.rs
@@ -72,40 +72,40 @@ pub struct TestVectorParameters {
 
 static TEST_VECTOR: &str = r#"
 {
-    "client_s_pk": "15ac69b4b2ed5159c41e6522be68e9ecb8f9a36a0c5f87e3b40441a2f70c3c13",
-    "client_s_sk": "9856141d88217b303ceaa4d48ce4271baefcce3d9b9db119dabce597a18c5b7b",
-    "client_e_pk": "92380a7ffb59a800ba1256b1f91934eef2c703a7c95e06fca3887dc006a96203",
-    "client_e_sk": "d038503babf0b662cb06115823590b21c9737beda4009efca6923caaf5728f42",
-    "server_s_pk": "03da70333c51449c72a8282170d9e6a15c8ff221e26542eb812be186cdb5b025",
-    "server_s_sk": "18f1d52bb05df44671599a9d63ed3d327ea69eec1cada57c2cd287f9d21ef67e",
-    "server_e_pk": "9a808154123cda50e79bc9e42c96fe67b3d6b44fe920a0fd24ccd3eba97f7f20",
-    "server_e_sk": "b04fbabf986c77f7fc38dbc874f857da71719c73d821468e825ed3c83694ca65",
+    "client_s_pk": "037ffc2cece49ab487448c9b52debee00bfcc72f00c78668f9b160466cc5b25a",
+    "client_s_sk": "e09f8a22c083743c60a2eb41640dc7174edd8863bb1a7482c12a02f08914db60",
+    "client_e_pk": "61422d4437b43abca17d2297a3b519fc37b24e20cb45d14a91ffcb1bc2107a5c",
+    "client_e_sk": "c831faece522d77c10625d1b0ea5592fb4ee45b042b4af4218d5702b087b136e",
+    "server_s_pk": "2cd221b189b472badcc2d4984dba174fd2e016bcc2bc8110527a11f28cd4f54f",
+    "server_s_sk": "986f09786edea821e346bd961cc0d727d5af77f88acda9bf2f95235716535f7c",
+    "server_e_pk": "b282307ada534fbb7e91253e8a807d3a0c5adb0cbcfb39fe5bae5bfd407abf17",
+    "server_e_sk": "f0d994f344f79aab474637090d6aeb6319c0a8123e21a18774fb4b21496a9963",
     "id_u": "696455",
     "id_s": "696453",
     "password": "70617373776f7264",
-    "blinding_factor": "d2b1e25c51a6dcc03c228d650fee985161e91992753ebde17bfd3d31f6fd5102",
-    "oprf_key": "5bff6043ea154271aabb77433670a308599647dde78c52cee1066f4d45faa907",
-    "envelope_nonce": "b18428a147bbd11cac7e8732aa2291f5f56aef0e2ff20bebe473e6d8a24c4c74",
-    "client_nonce": "67dbc61533747146040f15782e8cae54912d81d5dd48d89c540a2d76501aad58",
-    "server_nonce": "e7a1329a7293f3fe32b35b09522d1afd6a2133341c0b60b38b5617a0ffee12a2",
+    "blinding_factor": "26f30696f7a0d47fe3c5a08e2962880f413e805c013b59dde187df0d1667b003",
+    "oprf_key": "b1126f88aa2377b1b56a81227c9f72c015dd6f94e1f8d88e4cb983016da50804",
+    "envelope_nonce": "66ea20d6a122e7cb9872fd141f338c8009655963f8ba925ca801182c63921ce6",
+    "client_nonce": "85320d740dc2d1b4e78e3c4d6e6ce474b3f2f5abe3c0e314555e310e9f5b7dde",
+    "server_nonce": "2e1d659f03ad117e51acad7e8b8519472237aa0c7e9c35482185cefdaa972607",
     "info1": "696e666f31",
     "info2": "696e666f32",
     "einfo2": "65696e666f32",
     "info3": "696e666f33",
     "einfo3": "65696e666f33",
-    "registration_request": "00200bdcb3a4076577657b7fbb2e472882710c1fc5794df6f6d0e16a454feef607c3",
-    "registration_response": "002045b7272936aae186fa84b98a47e66850e34e0599002d48bfbc799c079606372c002003da70333c51449c72a8282170d9e6a15c8ff221e26542eb812be186cdb5b02501010103",
-    "registration_upload": "b18428a147bbd11cac7e8732aa2291f5f56aef0e2ff20bebe473e6d8a24c4c740023778d07a4b4385527786c67d0365623e84c492dfe56c1d5598e7478634d3ea94fd85eea002303002003da70333c51449c72a8282170d9e6a15c8ff221e26542eb812be186cdb5b02500209f8df539c6b1a6eaa12facd3c469fc418a7a3bd874181fb8c16e20f6eed033fc002015ac69b4b2ed5159c41e6522be68e9ecb8f9a36a0c5f87e3b40441a2f70c3c13",
-    "credential_request": "00200bdcb3a4076577657b7fbb2e472882710c1fc5794df6f6d0e16a454feef607c367dbc61533747146040f15782e8cae54912d81d5dd48d89c540a2d76501aad580005696e666f3192380a7ffb59a800ba1256b1f91934eef2c703a7c95e06fca3887dc006a96203",
-    "credential_response": "002045b7272936aae186fa84b98a47e66850e34e0599002d48bfbc799c079606372cb18428a147bbd11cac7e8732aa2291f5f56aef0e2ff20bebe473e6d8a24c4c740023778d07a4b4385527786c67d0365623e84c492dfe56c1d5598e7478634d3ea94fd85eea002303002003da70333c51449c72a8282170d9e6a15c8ff221e26542eb812be186cdb5b02500209f8df539c6b1a6eaa12facd3c469fc418a7a3bd874181fb8c16e20f6eed033fcb04fbabf986c77f7fc38dbc874f857da71719c73d821468e825ed3c83694ca650005696e666f329a808154123cda50e79bc9e42c96fe67b3d6b44fe920a0fd24ccd3eba97f7f20000665696e666f32c36b4e4987357f90247da7ca99eb259efacb48e894049d30d16a0bef9f0c14f4",
-    "key_exchange": "0005696e666f33000665696e666f33676707238432bfcfacd0a4e9d087776d0e3e32fe034e7e259fdaa25a69f4f4ba",
-    "client_registration_state": "d2b1e25c51a6dcc03c228d650fee985161e91992753ebde17bfd3d31f6fd510270617373776f7264",
-    "client_login_state": "00036964550003696453d2b1e25c51a6dcc03c228d650fee985161e91992753ebde17bfd3d31f6fd5102d038503babf0b662cb06115823590b21c9737beda4009efca6923caaf5728f4267dbc61533747146040f15782e8cae54912d81d5dd48d89c540a2d76501aad58ba195961229f243fa68e9bb23e228308dcccde52a59fa4655cef23beab52fc2f70617373776f7264",
-    "server_registration_state": "5bff6043ea154271aabb77433670a308599647dde78c52cee1066f4d45faa907",
-    "server_login_state": "4fadb7bdfc4691eb5f0fc3d20c218fd9d066b70feaa75412d57287b3157f8f557bcde6814f15097b1a2c7ad80d3c6bea53525fc7b79f9311b9412a69a47ac7deaff4e62f4302141d288651e4368aa37eb542f54a7a71d5091fdcf4dd71d78e12",
-    "password_file": "5bff6043ea154271aabb77433670a308599647dde78c52cee1066f4d45faa90715ac69b4b2ed5159c41e6522be68e9ecb8f9a36a0c5f87e3b40441a2f70c3c13b18428a147bbd11cac7e8732aa2291f5f56aef0e2ff20bebe473e6d8a24c4c740023778d07a4b4385527786c67d0365623e84c492dfe56c1d5598e7478634d3ea94fd85eea002303002003da70333c51449c72a8282170d9e6a15c8ff221e26542eb812be186cdb5b02500209f8df539c6b1a6eaa12facd3c469fc418a7a3bd874181fb8c16e20f6eed033fc",
-    "export_key": "c4d8e55e747645234c187724d11e7b9af7c2299972c3724a0850f5a3b7ee0d77",
-    "shared_secret": "aff4e62f4302141d288651e4368aa37eb542f54a7a71d5091fdcf4dd71d78e12"
+    "registration_request": "00205cebd79b362cbb48eab435801125e4646c4e56c9f19d720f1b7cdbca4c300ea8",
+    "registration_response": "002075dfc31fff8a44bde1ed1fd8c9295b7516bce1fe7559692883ada956a423fa9c00202cd221b189b472badcc2d4984dba174fd2e016bcc2bc8110527a11f28cd4f54f",
+    "registration_upload": "0166ea20d6a122e7cb9872fd141f338c8009655963f8ba925ca801182c63921ce600223c2deccbf09b5506d628137bd661b6de943a92fe762fd2b872c6adabc1e4c10ca2fb002c00202cd221b189b472badcc2d4984dba174fd2e016bcc2bc8110527a11f28cd4f54f000369645500036964530020dd6e96af9578ad04ef758070afdbb34ac695d2be131fed185ce746537cd02de60020037ffc2cece49ab487448c9b52debee00bfcc72f00c78668f9b160466cc5b25a",
+    "credential_request": "00205cebd79b362cbb48eab435801125e4646c4e56c9f19d720f1b7cdbca4c300ea885320d740dc2d1b4e78e3c4d6e6ce474b3f2f5abe3c0e314555e310e9f5b7dde0005696e666f3161422d4437b43abca17d2297a3b519fc37b24e20cb45d14a91ffcb1bc2107a5c",
+    "credential_response": "002075dfc31fff8a44bde1ed1fd8c9295b7516bce1fe7559692883ada956a423fa9c00202cd221b189b472badcc2d4984dba174fd2e016bcc2bc8110527a11f28cd4f54f0166ea20d6a122e7cb9872fd141f338c8009655963f8ba925ca801182c63921ce600223c2deccbf09b5506d628137bd661b6de943a92fe762fd2b872c6adabc1e4c10ca2fb002c00202cd221b189b472badcc2d4984dba174fd2e016bcc2bc8110527a11f28cd4f54f000369645500036964530020dd6e96af9578ad04ef758070afdbb34ac695d2be131fed185ce746537cd02de6f0d994f344f79aab474637090d6aeb6319c0a8123e21a18774fb4b21496a99630005696e666f32b282307ada534fbb7e91253e8a807d3a0c5adb0cbcfb39fe5bae5bfd407abf17000665696e666f32fb98272619ab5c17b860c2a59f194b88203080f641b96c278d10d69be004d2dd",
+    "key_exchange": "0005696e666f33000665696e666f33a13c4265ac30d7e079e975a550571ee95e74149cdc83b8683ac12d3764ed779a",
+    "client_registration_state": "26f30696f7a0d47fe3c5a08e2962880f413e805c013b59dde187df0d1667b00370617373776f7264",
+    "client_login_state": "26f30696f7a0d47fe3c5a08e2962880f413e805c013b59dde187df0d1667b003c831faece522d77c10625d1b0ea5592fb4ee45b042b4af4218d5702b087b136e85320d740dc2d1b4e78e3c4d6e6ce474b3f2f5abe3c0e314555e310e9f5b7dde518be4c0634f9829245f95c3ead10fafa41c29be9c6ca976bff9a1a22a61895e70617373776f7264",
+    "server_registration_state": "b1126f88aa2377b1b56a81227c9f72c015dd6f94e1f8d88e4cb983016da50804",
+    "server_login_state": "cb5e5021406dab84937ee7964c288e2ea176f7533ef12c2f7836dfc0a034c0387088884ba8e2ed9703ebf185a91511426d4dff480bd7282057e49b0b0fc38d6fa58f4c40f986833c2773696694d51a0a36d9ee85b0aacfc9cdad34dd9ad90d61",
+    "password_file": "b1126f88aa2377b1b56a81227c9f72c015dd6f94e1f8d88e4cb983016da50804037ffc2cece49ab487448c9b52debee00bfcc72f00c78668f9b160466cc5b25a0166ea20d6a122e7cb9872fd141f338c8009655963f8ba925ca801182c63921ce600223c2deccbf09b5506d628137bd661b6de943a92fe762fd2b872c6adabc1e4c10ca2fb002c00202cd221b189b472badcc2d4984dba174fd2e016bcc2bc8110527a11f28cd4f54f000369645500036964530020dd6e96af9578ad04ef758070afdbb34ac695d2be131fed185ce746537cd02de6",
+    "export_key": "776947002cb41ad575506e82778313bb8d2767dd9d7ed3fd55f875071d833a2e",
+    "shared_secret": "a58f4c40f986833c2773696694d51a0a36d9ee85b0aacfc9cdad34dd9ad90d61"
 }
 "#;
 
@@ -369,11 +369,7 @@ where
     let client_login_start_result = ClientLogin::<CS>::start(
         &mut client_login_start_rng,
         password,
-        ClientLoginStartParameters::WithInfoAndIdentifiers(
-            info1.to_vec(),
-            id_u.to_vec(),
-            id_s.to_vec(),
-        ),
+        ClientLoginStartParameters::WithInfo(info1.to_vec()),
         std::convert::identity,
     )
     .unwrap();
@@ -386,7 +382,12 @@ where
         password_file,
         server_s_kp.private(),
         client_login_start_result.message,
-        ServerLoginStartParameters::WithInfo(info2.to_vec(), einfo2.to_vec()),
+        ServerLoginStartParameters::WithInfoAndIdentifiers(
+            info2.to_vec(),
+            einfo2.to_vec(),
+            id_u.to_vec(),
+            id_s.to_vec(),
+        ),
     )
     .unwrap();
     let credential_response_bytes = server_login_start_result.message.serialize().to_vec();
@@ -396,7 +397,12 @@ where
         .state
         .finish(
             server_login_start_result.message,
-            ClientLoginFinishParameters::WithInfo(info3.to_vec(), einfo3.to_vec()),
+            ClientLoginFinishParameters::WithInfoAndIdentifiers(
+                info3.to_vec(),
+                einfo3.to_vec(),
+                id_u.to_vec(),
+                id_s.to_vec(),
+            ),
         )
         .unwrap();
     let key_exchange_bytes = client_login_finish_result.message.to_bytes().to_vec();
@@ -550,11 +556,7 @@ fn test_credential_request() -> Result<(), ProtocolError> {
     let client_login_start_result = ClientLogin::<X255193dhNoSlowHash>::start(
         &mut client_login_start_rng,
         &parameters.password,
-        ClientLoginStartParameters::WithInfoAndIdentifiers(
-            parameters.info1,
-            parameters.id_u,
-            parameters.id_s,
-        ),
+        ClientLoginStartParameters::WithInfo(parameters.info1),
         postprocess_blinding_factor::<<X255193dhNoSlowHash as CipherSuite>::Group>,
     )?;
     assert_eq!(
@@ -579,7 +581,12 @@ fn test_credential_response() -> Result<(), ProtocolError> {
         &Key::try_from(&parameters.server_s_sk[..]).unwrap(),
         CredentialRequest::<X255193dhNoSlowHash>::deserialize(&parameters.credential_request[..])
             .unwrap(),
-        ServerLoginStartParameters::WithInfo(parameters.info2.to_vec(), parameters.einfo2.to_vec()),
+        ServerLoginStartParameters::WithInfoAndIdentifiers(
+            parameters.info2.to_vec(),
+            parameters.einfo2.to_vec(),
+            parameters.id_u,
+            parameters.id_s,
+        ),
     )?;
     assert_eq!(
         hex::encode(&parameters.info1),
@@ -611,9 +618,11 @@ fn test_key_exchange() -> Result<(), ProtocolError> {
                 CredentialResponse::<X255193dhNoSlowHash>::deserialize(
                     &parameters.credential_response[..],
                 )?,
-                ClientLoginFinishParameters::WithInfo(
+                ClientLoginFinishParameters::WithInfoAndIdentifiers(
                     parameters.info3.to_vec(),
                     parameters.einfo3.to_vec(),
+                    parameters.id_u,
+                    parameters.id_s,
                 ),
             )?;
 
@@ -629,7 +638,6 @@ fn test_key_exchange() -> Result<(), ProtocolError> {
         hex::encode(&parameters.server_s_pk),
         hex::encode(&client_login_finish_result.server_s_pk)
     );
-    assert_eq!(None, client_login_finish_result.id_s);
     assert_eq!(
         hex::encode(&parameters.shared_secret),
         hex::encode(&client_login_finish_result.shared_secret)