extern crate arrayvec;
use params::HandshakePattern;
use error::{ErrorKind, Result, StateProblem};
use cipherstate::CipherStates;
use constants::{MAXMSGLEN, TAGLEN};
pub struct TransportState {
pub cipherstates: CipherStates,
pattern: HandshakePattern,
initiator: bool,
}
impl TransportState {
pub fn new(cipherstates: CipherStates, pattern: HandshakePattern, initiator: bool) -> Self {
TransportState {
cipherstates: cipherstates,
pattern: pattern,
initiator: initiator,
}
}
pub fn write_transport_message(&mut self,
payload: &[u8],
message: &mut [u8]) -> Result<usize> {
if !self.initiator && self.pattern.is_oneway() {
bail!(ErrorKind::State(StateProblem::OneWay));
} else if payload.len() + TAGLEN > MAXMSGLEN {
bail!(ErrorKind::Input);
} else if payload.len() + TAGLEN > message.len() {
bail!(ErrorKind::Input);
}
let cipher = if self.initiator { &mut self.cipherstates.0 } else { &mut self.cipherstates.1 };
Ok(cipher.encrypt(payload, message))
}
pub fn read_transport_message(&mut self,
payload: &[u8],
message: &mut [u8]) -> Result<usize> {
if self.initiator && self.pattern.is_oneway() {
bail!(ErrorKind::State(StateProblem::OneWay));
}
let cipher = if self.initiator { &mut self.cipherstates.1 } else { &mut self.cipherstates.0 };
cipher.decrypt(payload, message).map_err(|_| ErrorKind::Decrypt.into())
}
pub fn rekey_initiator(&mut self, key: &[u8]) {
self.cipherstates.rekey_initiator(key)
}
pub fn rekey_responder(&mut self, key: &[u8]) {
self.cipherstates.rekey_responder(key)
}
}