pmv_encryption_rs 1.0.0

Implementation of PersonalMediaVault encrypted storage model. This library allows to encrypt and decrypt data, and also read ans write files in the same format PersonalMediaVault uses.
Documentation
// Encryption method

use std::fmt;

/// Custom error for parsing the encryption method
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct EncryptionMethodParseError;

impl fmt::Display for EncryptionMethodParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "unknown or unsupported encryption method number")
    }
}

/// Encryption method
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum EncryptionMethod {
    /// Compress data, then encrypt it with AES-256-CBC
    Aes256Zip,
    /// Just encrypt the data with AES-256-CBC
    Aes256Flat,
}

impl EncryptionMethod {
    /// Turns the encryption method into its corresponding numeric representation
    pub fn to_u16(&self) -> u16 {
        match self {
            EncryptionMethod::Aes256Zip => 1,
            EncryptionMethod::Aes256Flat => 2,
        }
    }

    /// Returns the corresponding method to its numeric representation
    /// If the number does not correspond to any method, it will return an error instead
    pub fn from_u16(v: u16) -> Result<EncryptionMethod, EncryptionMethodParseError> {
        match v {
            1 => Ok(EncryptionMethod::Aes256Zip),
            2 => Ok(EncryptionMethod::Aes256Flat),
            _ => Err(EncryptionMethodParseError),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encryption_method() {
        assert_eq!(EncryptionMethod::Aes256Zip.to_u16(), 1);
        assert_eq!(EncryptionMethod::Aes256Flat.to_u16(), 2);
        assert_eq!(
            EncryptionMethod::from_u16(1),
            Ok(EncryptionMethod::Aes256Zip)
        );
        assert_eq!(
            EncryptionMethod::from_u16(2),
            Ok(EncryptionMethod::Aes256Flat)
        );
        assert_eq!(
            EncryptionMethod::from_u16(0),
            Err(EncryptionMethodParseError)
        );
        assert_eq!(
            EncryptionMethod::from_u16(3),
            Err(EncryptionMethodParseError)
        );
    }
}