password_hash/encoding.rs
1//! Base64 encoding variants.
2
3use base64ct::{
4 Base64Bcrypt, Base64Crypt, Base64Unpadded as B64, Encoding as _, Error as B64Error,
5};
6
7/// Base64 encoding variants.
8#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
9pub enum Encoding {
10 /// "B64" encoding: standard Base64 without padding.
11 ///
12 /// ```text
13 /// [A-Z] [a-z] [0-9] + /
14 /// 0x41-0x5a, 0x61-0x7a, 0x30-0x39, 0x2b, 0x2f
15 /// ```
16 /// <https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md#b64>
17 B64,
18
19 /// bcrypt encoding.
20 ///
21 /// ```text
22 /// ./ [A-Z] [a-z] [0-9]
23 /// 0x2e-0x2f, 0x41-0x5a, 0x61-0x7a, 0x30-0x39
24 /// ```
25 Bcrypt,
26
27 /// `crypt(3)` encoding.
28 ///
29 /// ```text
30 /// [.-9] [A-Z] [a-z]
31 /// 0x2e-0x39, 0x41-0x5a, 0x61-0x7a
32 /// ```
33 Crypt,
34}
35
36impl Default for Encoding {
37 fn default() -> Self {
38 Self::B64
39 }
40}
41
42impl Encoding {
43 /// Decode a Base64 string into the provided destination buffer.
44 pub fn decode(self, src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], B64Error> {
45 match self {
46 Self::B64 => B64::decode(src, dst),
47 Self::Bcrypt => Base64Bcrypt::decode(src, dst),
48 Self::Crypt => Base64Crypt::decode(src, dst),
49 }
50 }
51
52 /// Encode the input byte slice as Base64.
53 ///
54 /// Writes the result into the provided destination slice, returning an
55 /// ASCII-encoded Base64 string value.
56 pub fn encode<'a>(self, src: &[u8], dst: &'a mut [u8]) -> Result<&'a str, B64Error> {
57 match self {
58 Self::B64 => B64::encode(src, dst),
59 Self::Bcrypt => Base64Bcrypt::encode(src, dst),
60 Self::Crypt => Base64Crypt::encode(src, dst),
61 }
62 .map_err(Into::into)
63 }
64
65 /// Get the length of Base64 produced by encoding the given bytes.
66 pub fn encoded_len(self, bytes: &[u8]) -> usize {
67 match self {
68 Self::B64 => B64::encoded_len(bytes),
69 Self::Bcrypt => Base64Bcrypt::encoded_len(bytes),
70 Self::Crypt => Base64Crypt::encoded_len(bytes),
71 }
72 }
73}