Skip to main content

Cipher

Enum Cipher 

Source
pub enum Cipher {
    Aes128Cbc,
    Aes256Cbc,
    Aes128Gcm,
    Aes256Gcm,
}
Expand description

A cipher supported by Laravel’s encrypter.

Variants§

§

Aes128Cbc

aes-128-cbc

§

Aes256Cbc

aes-256-cbc, Laravel’s default.

§

Aes128Gcm

aes-128-gcm

§

Aes256Gcm

aes-256-gcm

Implementations§

Source§

impl Cipher

Source

pub fn name(self) -> &'static str

The cipher’s name as used in Laravel’s config/app.php, in lower case.

Examples found in repository?
examples/genvectors.rs (line 119)
105fn main() {
106    let mut vectors = Vec::new();
107    for cipher in [
108        Cipher::Aes128Cbc,
109        Cipher::Aes256Cbc,
110        Cipher::Aes128Gcm,
111        Cipher::Aes256Gcm,
112    ] {
113        let enc = Encrypter::new(&KEY[..cipher.key_size()], cipher).expect("valid key");
114
115        for (name, plaintext) in strings() {
116            vectors.push(json!({
117                "kind": "string",
118                "name": format!("{cipher}/{name}"),
119                "cipher": cipher.name(),
120                "plaintext_b64": base64(&plaintext),
121                "payload": enc.encrypt_bytes(&plaintext).expect("encrypt"),
122            }));
123        }
124        for (name, value) in cases() {
125            vectors.push(json!({
126                "kind": "serialized",
127                "name": format!("{cipher}/{name}"),
128                "case": name,
129                "cipher": cipher.name(),
130                "payload": enc.encrypt(&value).expect("encrypt"),
131            }));
132        }
133    }
134
135    println!("{}", json!({ "key_b64": base64(&KEY), "vectors": vectors }));
136}
More examples
Hide additional examples
examples/mutations.rs (line 100)
29fn main() {
30    let mut state = 0x1234_5678_9abc_def1_u64;
31    let mut next = move || {
32        state ^= state << 13;
33        state ^= state >> 7;
34        state ^= state << 17;
35        state
36    };
37    let encode = |j: &Value| STANDARD.encode(serde_json::to_vec(j).expect("serialize"));
38
39    let mut cases = Vec::new();
40    for cipher in [
41        Cipher::Aes128Cbc,
42        Cipher::Aes256Cbc,
43        Cipher::Aes128Gcm,
44        Cipher::Aes256Gcm,
45    ] {
46        let enc = Encrypter::new(&vec![0x2b; cipher.key_size()], cipher).expect("valid key");
47
48        for text in ["", "hello", "0123456789abcdef"] {
49            let valid = enc.encrypt_string(text).expect("encrypt");
50            let base: Value =
51                serde_json::from_slice(&STANDARD.decode(&valid).expect("base64")).expect("json");
52
53            let mut payloads = vec![
54                valid.clone(),
55                format!(" {valid}\n"),
56                valid.trim_end_matches('=').to_owned(),
57            ];
58
59            // Field-level edits: odd values, removal, upper case, an extra character.
60            for field in ["iv", "value", "mac", "tag"] {
61                for odd in odd_values() {
62                    let mut j = base.clone();
63                    j[field] = odd;
64                    payloads.push(encode(&j));
65                }
66                let mut j = base.clone();
67                j.as_object_mut().expect("object").remove(field);
68                payloads.push(encode(&j));
69
70                let text = base[field].as_str().expect("string").to_owned();
71                let mut j = base.clone();
72                j[field] = json!(text.to_uppercase());
73                payloads.push(encode(&j));
74                let mut j = base.clone();
75                j[field] = json!(format!("{text}A"));
76                payloads.push(encode(&j));
77            }
78
79            // Byte-level edits of the outer base64 text.
80            for _ in 0..600 {
81                let mut b = valid.clone().into_bytes();
82                let at = next() as usize % b.len();
83                match next() % 5 {
84                    0 => b[at] = b"ABCxyz09+/=!\n "[next() as usize % 14],
85                    1 => {
86                        b.remove(at);
87                    }
88                    2 => b.truncate(at),
89                    3 => b.insert(at, b" \n=*"[next() as usize % 4]),
90                    _ => {
91                        let other = next() as usize % b.len();
92                        b.swap(at, other);
93                    }
94                }
95                payloads.push(String::from_utf8_lossy(&b).into_owned());
96            }
97
98            for payload in payloads {
99                let plain = enc.decrypt_string(&payload).ok();
100                cases.push(json!({ "cipher": cipher.name(), "payload": payload, "plain": plain }));
101            }
102        }
103    }
104
105    // A closed pipe (PHP exited early) is not an error worth a panic.
106    let _ = writeln!(
107        std::io::stdout(),
108        "{}",
109        json!({ "key_b64": STANDARD.encode([0x2b; 32]), "cases": cases })
110    );
111}
Source

pub fn key_size(self) -> usize

The key length this cipher requires, in bytes.

Examples found in repository?
examples/genvectors.rs (line 113)
105fn main() {
106    let mut vectors = Vec::new();
107    for cipher in [
108        Cipher::Aes128Cbc,
109        Cipher::Aes256Cbc,
110        Cipher::Aes128Gcm,
111        Cipher::Aes256Gcm,
112    ] {
113        let enc = Encrypter::new(&KEY[..cipher.key_size()], cipher).expect("valid key");
114
115        for (name, plaintext) in strings() {
116            vectors.push(json!({
117                "kind": "string",
118                "name": format!("{cipher}/{name}"),
119                "cipher": cipher.name(),
120                "plaintext_b64": base64(&plaintext),
121                "payload": enc.encrypt_bytes(&plaintext).expect("encrypt"),
122            }));
123        }
124        for (name, value) in cases() {
125            vectors.push(json!({
126                "kind": "serialized",
127                "name": format!("{cipher}/{name}"),
128                "case": name,
129                "cipher": cipher.name(),
130                "payload": enc.encrypt(&value).expect("encrypt"),
131            }));
132        }
133    }
134
135    println!("{}", json!({ "key_b64": base64(&KEY), "vectors": vectors }));
136}
More examples
Hide additional examples
examples/mutations.rs (line 46)
29fn main() {
30    let mut state = 0x1234_5678_9abc_def1_u64;
31    let mut next = move || {
32        state ^= state << 13;
33        state ^= state >> 7;
34        state ^= state << 17;
35        state
36    };
37    let encode = |j: &Value| STANDARD.encode(serde_json::to_vec(j).expect("serialize"));
38
39    let mut cases = Vec::new();
40    for cipher in [
41        Cipher::Aes128Cbc,
42        Cipher::Aes256Cbc,
43        Cipher::Aes128Gcm,
44        Cipher::Aes256Gcm,
45    ] {
46        let enc = Encrypter::new(&vec![0x2b; cipher.key_size()], cipher).expect("valid key");
47
48        for text in ["", "hello", "0123456789abcdef"] {
49            let valid = enc.encrypt_string(text).expect("encrypt");
50            let base: Value =
51                serde_json::from_slice(&STANDARD.decode(&valid).expect("base64")).expect("json");
52
53            let mut payloads = vec![
54                valid.clone(),
55                format!(" {valid}\n"),
56                valid.trim_end_matches('=').to_owned(),
57            ];
58
59            // Field-level edits: odd values, removal, upper case, an extra character.
60            for field in ["iv", "value", "mac", "tag"] {
61                for odd in odd_values() {
62                    let mut j = base.clone();
63                    j[field] = odd;
64                    payloads.push(encode(&j));
65                }
66                let mut j = base.clone();
67                j.as_object_mut().expect("object").remove(field);
68                payloads.push(encode(&j));
69
70                let text = base[field].as_str().expect("string").to_owned();
71                let mut j = base.clone();
72                j[field] = json!(text.to_uppercase());
73                payloads.push(encode(&j));
74                let mut j = base.clone();
75                j[field] = json!(format!("{text}A"));
76                payloads.push(encode(&j));
77            }
78
79            // Byte-level edits of the outer base64 text.
80            for _ in 0..600 {
81                let mut b = valid.clone().into_bytes();
82                let at = next() as usize % b.len();
83                match next() % 5 {
84                    0 => b[at] = b"ABCxyz09+/=!\n "[next() as usize % 14],
85                    1 => {
86                        b.remove(at);
87                    }
88                    2 => b.truncate(at),
89                    3 => b.insert(at, b" \n=*"[next() as usize % 4]),
90                    _ => {
91                        let other = next() as usize % b.len();
92                        b.swap(at, other);
93                    }
94                }
95                payloads.push(String::from_utf8_lossy(&b).into_owned());
96            }
97
98            for payload in payloads {
99                let plain = enc.decrypt_string(&payload).ok();
100                cases.push(json!({ "cipher": cipher.name(), "payload": payload, "plain": plain }));
101            }
102        }
103    }
104
105    // A closed pipe (PHP exited early) is not an error worth a panic.
106    let _ = writeln!(
107        std::io::stdout(),
108        "{}",
109        json!({ "key_b64": STANDARD.encode([0x2b; 32]), "cases": cases })
110    );
111}

Trait Implementations§

Source§

impl Clone for Cipher

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Cipher

Source§

impl Debug for Cipher

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Cipher

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Cipher

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Cipher

Source§

impl FromStr for Cipher

Source§

fn from_str(s: &str) -> Result<Self>

Parses a cipher name case-insensitively, so Laravel’s AES-256-CBC works.

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

impl Hash for Cipher

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Cipher

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Cipher

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.