feat(web): create CipherForm component

This commit is contained in:
Kristofers Solo 2025-11-26 03:43:23 +02:00
parent 5f22690ef7
commit aa4bd9ecec
Signed by: kristoferssolo
GPG Key ID: 8687F2D3EEE6F0ED
16 changed files with 430 additions and 124 deletions

View File

@ -12,6 +12,7 @@ claims = "0.8"
color-eyre = "0.6" color-eyre = "0.6"
rand = "0.9" rand = "0.9"
rstest = "0.26" rstest = "0.26"
strum = "0.27"
thiserror = "2" thiserror = "2"
[workspace.dependencies.aes] [workspace.dependencies.aes]

View File

@ -7,3 +7,7 @@ pub use {
traits::{BlockCipher, BlockParser, InputBlock}, traits::{BlockCipher, BlockParser, InputBlock},
types::{CipherAction, Output}, types::{CipherAction, Output},
}; };
pub mod prelude {
pub use super::{CipherAction, CipherResult, InputBlock, Output};
}

View File

@ -9,6 +9,7 @@ aes.workspace = true
cipher-core.workspace = true cipher-core.workspace = true
clap = { workspace = true, optional = true } clap = { workspace = true, optional = true }
des.workspace = true des.workspace = true
strum = { workspace = true, features = ["derive"] }
[features] [features]
default = [] default = []

View File

@ -74,8 +74,8 @@ impl Algorithm {
impl Display for Algorithm { impl Display for Algorithm {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self { let s = match self {
Self::Des => "Des", Self::Des => "DES",
Self::Aes => "Aes", Self::Aes => "AES",
}; };
f.write_str(s) f.write_str(s)
} }

View File

@ -1,15 +1,34 @@
use crate::{Algorithm, OperationChoice, OutputFormat}; use crate::{Algorithm, OperationMode, OutputFormat};
use cipher_core::{BlockCipher, CipherResult}; use cipher_core::{BlockCipher, CipherResult};
#[derive(Clone)]
pub struct CipherContext { pub struct CipherContext {
pub algorithm: Algorithm, pub algorithm: Algorithm,
pub operation: OperationChoice, pub operation: OperationMode,
pub key: String, pub key: String,
pub input_text: String, pub input_text: String,
pub output_format: OutputFormat, pub output_format: OutputFormat,
} }
impl CipherContext { impl CipherContext {
#[inline]
#[must_use]
pub const fn new(
algorithm: Algorithm,
operation: OperationMode,
key: String,
input_text: String,
output_format: OutputFormat,
) -> Self {
Self {
algorithm,
operation,
key,
input_text,
output_format,
}
}
pub fn process(&self) -> CipherResult<String> { pub fn process(&self) -> CipherResult<String> {
let text_bytes = self.algorithm.parse_text(&self.input_text)?; let text_bytes = self.algorithm.parse_text(&self.input_text)?;
let cipher = self.algorithm.new_cipher(&self.key)?; let cipher = self.algorithm.new_cipher(&self.key)?;
@ -18,13 +37,13 @@ impl CipherContext {
fn execute(&self, cipher: &dyn BlockCipher, text_bytes: &[u8]) -> CipherResult<String> { fn execute(&self, cipher: &dyn BlockCipher, text_bytes: &[u8]) -> CipherResult<String> {
match self.operation { match self.operation {
OperationChoice::Encrypt => { OperationMode::Encrypt => {
let ciphertext = cipher.encrypt(text_bytes)?; let ciphertext = cipher.encrypt(text_bytes)?;
Ok(format!("{ciphertext:X}")) Ok(format!("{ciphertext:X}"))
} }
OperationChoice::Decrypt => { OperationMode::Decrypt => {
let plaintext = cipher.decrypt(text_bytes)?; let plaintext = cipher.decrypt(text_bytes)?;
let output = self.output_format.to_string(&plaintext); let output = self.output_format.format(&plaintext);
Ok(output) Ok(output)
} }
} }

View File

@ -4,5 +4,9 @@ mod operation;
mod output; mod output;
pub use { pub use {
algorithm::Algorithm, context::CipherContext, operation::OperationChoice, output::OutputFormat, algorithm::Algorithm, context::CipherContext, operation::OperationMode, output::OutputFormat,
}; };
pub mod prelude {
pub use super::{Algorithm, CipherContext, OperationMode, OutputFormat};
}

View File

@ -1,6 +1,39 @@
use std::{convert::Infallible, fmt::Display, str::FromStr};
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))] #[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OperationChoice { pub enum OperationMode {
#[default]
Encrypt, Encrypt,
Decrypt, Decrypt,
} }
impl OperationMode {
#[must_use]
pub const fn invert(self) -> Self {
match self {
Self::Encrypt => Self::Decrypt,
Self::Decrypt => Self::Encrypt,
}
}
}
impl Display for OperationMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::Encrypt => "Encrypt",
Self::Decrypt => "Decrypt",
};
f.write_str(s)
}
}
impl FromStr for OperationMode {
type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_lowercase().as_ref() {
"decrypt" => Ok(Self::Decrypt),
_ => Ok(Self::Encrypt),
}
}
}

View File

@ -1,7 +1,9 @@
use cipher_core::Output; use cipher_core::Output;
use std::{convert::Infallible, fmt::Display, str::FromStr};
use strum::EnumIter;
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))] #[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, EnumIter)]
pub enum OutputFormat { pub enum OutputFormat {
/// Binary output /// Binary output
Binary, Binary,
@ -16,7 +18,7 @@ pub enum OutputFormat {
impl OutputFormat { impl OutputFormat {
#[must_use] #[must_use]
pub fn to_string(&self, value: &Output) -> String { pub fn format(&self, value: &Output) -> String {
match self { match self {
Self::Binary => format!("{value:b}"), Self::Binary => format!("{value:b}"),
Self::Octal => format!("{value:o}"), Self::Octal => format!("{value:o}"),
@ -25,3 +27,27 @@ impl OutputFormat {
} }
} }
} }
impl FromStr for OutputFormat {
type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s.trim().to_lowercase().as_ref() {
"binary" | "bin" => Self::Binary,
"octal" | "oct" => Self::Octal,
"text" | "txt" => Self::Text,
_ => Self::Hex,
})
}
}
impl Display for OutputFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::Binary => "Binary",
Self::Octal => "Octal",
Self::Hex => "Hexadecimal",
Self::Text => "Text",
};
f.write_str(s)
}
}

View File

@ -1,4 +1,4 @@
use cipher_factory::{Algorithm, CipherContext, OperationChoice, OutputFormat}; use cipher_factory::{Algorithm, CipherContext, OperationMode, OutputFormat};
use clap::Parser; use clap::Parser;
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
@ -6,7 +6,7 @@ use clap::Parser;
pub struct Args { pub struct Args {
/// Operation to perform /// Operation to perform
#[arg(value_name = "OPERATION")] #[arg(value_name = "OPERATION")]
pub operation: OperationChoice, pub operation: OperationMode,
/// Encryption algorithm /// Encryption algorithm
#[arg(short, long)] #[arg(short, long)]

View File

@ -8,14 +8,20 @@ edition.workspace = true
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
leptos = { version = "0.8.0", features = ["nightly"] } aes.workspace = true
leptos_router = { version = "0.8.0", features = ["nightly"] } axum = { version = "0.8", optional = true }
axum = { version = "0.8.0", optional = true } cipher-core.workspace = true
cipher-factory.workspace = true
console_error_panic_hook = { version = "0.1", optional = true } console_error_panic_hook = { version = "0.1", optional = true }
leptos_axum = { version = "0.8.0", optional = true } des.workspace = true
leptos_meta = { version = "0.8.0" } leptos = { version = "0.8", features = ["nightly"] }
leptos_axum = { version = "0.8", optional = true }
leptos_meta = { version = "0.8" }
leptos_router = { version = "0.8", features = ["nightly"] }
strum.workspace = true
tokio = { version = "1", features = ["rt-multi-thread"], optional = true } tokio = { version = "1", features = ["rt-multi-thread"], optional = true }
wasm-bindgen = { version = "=0.2.104", optional = true } wasm-bindgen = { version = "=0.2.104", optional = true }
web-sys = "0.3"
[features] [features]
hydrate = ["leptos/hydrate", "dep:console_error_panic_hook", "dep:wasm-bindgen"] hydrate = ["leptos/hydrate", "dep:console_error_panic_hook", "dep:wasm-bindgen"]

View File

@ -1,10 +1,11 @@
use crate::pages::{des::DesPage, home::Home}; use crate::pages::{aes::AesPage, des::DesPage, home::Home};
use leptos::prelude::*; use leptos::prelude::*;
use leptos_meta::{MetaTags, Stylesheet, Title, provide_meta_context}; use leptos_meta::{MetaTags, Stylesheet, Title, provide_meta_context};
use leptos_router::{ use leptos_router::{
StaticSegment, StaticSegment,
components::{A, Route, Router, Routes}, components::{A, Route, Router, Routes},
}; };
use std::fmt::Display;
#[must_use] #[must_use]
pub fn shell(options: LeptosOptions) -> impl IntoView { pub fn shell(options: LeptosOptions) -> impl IntoView {
@ -25,22 +26,52 @@ pub fn shell(options: LeptosOptions) -> impl IntoView {
} }
} }
#[derive(Clone, Copy, PartialEq)]
enum Theme {
Light,
Dark,
}
impl Theme {
const fn inverse(self) -> Self {
match self {
Self::Light => Self::Dark,
Self::Dark => Self::Light,
}
}
}
impl Display for Theme {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
Self::Light => "☀️ Light",
Self::Dark => "🌙 Dark",
};
f.write_str(s)
}
}
#[component] #[component]
// Provides context that manages stylesheets, titles, meta tags, etc. // Provides context that manages stylesheets, titles, meta tags, etc.
pub fn App() -> impl IntoView { pub fn App() -> impl IntoView {
provide_meta_context(); provide_meta_context();
let (is_light, set_is_light) = signal(false); let (theme, set_theme) = signal(Theme::Dark);
let toggle_theme = move |_| { let toggle_theme = move |_| {
set_is_light.update(|light| *light = !*light); set_theme.update(|t| *t = t.inverse());
if let Some(body) = document().body() { if let Some(body) = document().body() {
let class_list = body.class_list(); let class_list = body.class_list();
if is_light.get() { match theme.get() {
Theme::Light => {
let _ = class_list.remove_1("dark-theme");
let _ = class_list.add_1("light-theme"); let _ = class_list.add_1("light-theme");
} else { }
Theme::Dark => {
let _ = class_list.remove_1("light-theme"); let _ = class_list.remove_1("light-theme");
let _ = class_list.add_1("dark-theme");
}
} }
} }
}; };
@ -69,14 +100,14 @@ pub fn App() -> impl IntoView {
</li> </li>
</ul> </ul>
<button class="theme-toggle" on:click=toggle_theme> <button class="theme-toggle" on:click=toggle_theme>
{move || if is_light.get() { "🌙 Dark" } else { "☀️ Light" }} {move || theme.get().to_string()}
</button> </button>
</nav> </nav>
<main> <main>
<Routes fallback=|| "Page not found.".into_view()> <Routes fallback=|| "Page not found.".into_view()>
<Route path=StaticSegment("/") view=Home /> <Route path=StaticSegment("/") view=Home />
<Route path=StaticSegment("/des") view=DesPage /> <Route path=StaticSegment("/des") view=DesPage />
<Route path=StaticSegment("/aes") view=Home /> <Route path=StaticSegment("/aes") view=AesPage />
</Routes> </Routes>
</main> </main>
</div> </div>

View File

@ -1,62 +1,93 @@
use cipher_factory::prelude::*;
use leptos::prelude::*; use leptos::prelude::*;
type LogicFn = Box<dyn Fn(bool, String, String) -> (String, String)>; use std::str::FromStr;
use strum::IntoEnumIterator;
#[component] #[component]
pub fn CipherForm(title: &'static str, logic: LogicFn) -> impl IntoView { pub fn CipherForm(algorithm: Algorithm) -> impl IntoView {
let (mode, set_mode) = signal("Encrypt".to_string()); let (mode, set_mode) = signal(OperationMode::Encrypt);
let (output_fmt, set_output_fmt) = signal(OutputFormat::Hex);
let (key_input, set_key_input) = signal(String::new()); let (key_input, set_key_input) = signal(String::new());
let (text_input, set_text_input) = signal(String::new()); let (text_input, set_text_input) = signal(String::new());
let (output, set_output) = signal(String::new()); let (output, set_output) = signal(String::new());
let (error_msg, set_error_msg) = signal(String::new()); let (error_msg, set_error_msg) = signal(String::new());
let (copy_feedback, set_copy_feedback) = signal(false);
let handle_submit = move |_| { let handle_submit = move || {
set_error_msg(String::new()); set_error_msg(String::new());
set_output(String::new()); set_output(String::new());
set_copy_feedback(false);
let is_encrypt = mode.get() == "Encrypt";
let key = key_input.get(); let key = key_input.get();
let text = text_input.get(); let text = text_input.get();
if key.is_empty() || text.is_empty() { if key.is_empty() || text.is_empty() {
set_error_msg("Please enter both key and text/hex.".to_string()); set_error_msg("Please enter both key and input text.".to_string());
return; return;
} }
let (res_out, res_err) = logic(is_encrypt, key, text); let context = CipherContext::new(algorithm, mode.get(), key, text, output_fmt.get());
match context.process() {
if !res_err.is_empty() { Ok(out) => set_output(out),
set_error_msg(res_err); Err(e) => set_error_msg(e.to_string()),
return;
} }
set_output(res_out);
}; };
view! { view! {
<div class="cipher-card"> <div class="cipher-card">
<h2>{title} " Encryption"</h2> <div class="card-header">
<h2>{algorithm.to_string()}</h2>
</div>
<div class="form-group"> <div class="form-group">
<label>"Operation Mdoe"</label> <label>"Configuration"</label>
<div class="controls-row">
<div class="radio-group"> <div class="radio-group">
<label> <RadioButton
<input value=OperationMode::Encrypt
type="radio" current=mode
name="mode" set_current=set_mode
value="Encrypt"
checked=move || mode.get() == "Encrypt"
on:change=move |ev| set_mode(event_target_value(&ev))
/> />
"Encrypt" <RadioButton
</label> value=OperationMode::Decrypt
<label> current=mode
<input set_current=set_mode
type="radio"
name="mode"
value="Decrypt"
checked=move || mode.get() == "Decrypt"
on:change=move |ev| set_mode(event_target_value(&ev))
/> />
"Decrypt" </div>
</label> {move || {
if mode.get() != OperationMode::Decrypt {
return view! { <span></span> }.into_any();
}
view! {
<div class="format-controls-box">
<div class="format-controls">
<label>"Output format:"</label>
<select
on:change=move |ev| {
let val = event_target_value(&ev);
let fmt = OutputFormat::from_str(&val).unwrap_or_default();
set_output_fmt(fmt);
if !output.get().is_empty() {
handle_submit();
}
}
prop:value=move || output_fmt.get().to_string()
>
{OutputFormat::iter()
.map(|fmt| {
view! {
<option value=fmt.to_string()>{fmt.to_string()}</option>
}
})
.collect_view()}
</select>
</div>
</div>
}
.into_any()
}}
</div> </div>
</div> </div>
<div class="form-group"> <div class="form-group">
@ -71,10 +102,9 @@ pub fn CipherForm(title: &'static str, logic: LogicFn) -> impl IntoView {
<div class="form-group"> <div class="form-group">
<label> <label>
{move || { {move || {
if mode.get() == "Encrypt" { match mode.get() {
"Plaintext Input" OperationMode::Encrypt => "Plaintext Input",
} else { OperationMode::Decrypt => "Ciphertext (Hex) Input",
"Ciphertext (Hex) Input"
} }
}} }}
</label> </label>
@ -86,31 +116,55 @@ pub fn CipherForm(title: &'static str, logic: LogicFn) -> impl IntoView {
/> />
</div> </div>
<button class="btn-primary" on:click=handle_submit> <button class="btn-primary" on:click=move |_| handle_submit()>
{move || format!("Run {title} {}", mode.get())} {move || format!("{} using {algorithm}", mode.get())}
</button> </button>
{move || { // Output Section
if error_msg.get().is_empty() {
view! { <span></span> }.into_any()
} else {
view! { <div class="error-box">{error_msg.get()}</div> }.into_any()
}
}}
{move || { {move || {
if output.get().is_empty() { if output.get().is_empty() {
view! { <span></span> }.into_any() return view! { <span></span> }.into_any();
} else { }
view! { view! {
<div class="result-box"> <div class="result-box">
<strong>"Output:"</strong> <div class="result-toolbar">
<strong>"Output ("{output_fmt.get().to_string()}")"</strong>
<code>{output.get()}</code> <code>{output.get()}</code>
</div> </div>
</div>
} }
.into_any() .into_any()
}}
// Error Section
{move || {
if error_msg.get().is_empty() {
return view! { <span></span> }.into_any();
} }
view! { <div class="error-box">{error_msg.get()}</div> }.into_any()
}} }}
</div> </div>
} }
} }
#[component]
fn RadioButton(
value: OperationMode,
current: ReadSignal<OperationMode>,
set_current: WriteSignal<OperationMode>,
) -> impl IntoView {
view! {
<div class="radio-button">
<label>
<input
type="radio"
name="crypto-mode"
value=value.to_string()
prop:checked=move || current.get() == value
on:change=move |_| set_current.set(value)
/>
{value.to_string()}
</label>
</div>
}
}

8
web/src/pages/aes.rs Normal file
View File

@ -0,0 +1,8 @@
use crate::components::cipher_form::CipherForm;
use cipher_factory::Algorithm;
use leptos::prelude::*;
#[component]
pub fn AesPage() -> impl IntoView {
view! { <CipherForm algorithm=Algorithm::Aes /> }
}

View File

@ -1,13 +1,8 @@
use crate::components::cipher_form::CipherForm; use crate::components::cipher_form::CipherForm;
use cipher_factory::Algorithm;
use leptos::prelude::*; use leptos::prelude::*;
#[component] #[component]
pub fn DesPage() -> impl IntoView { pub fn DesPage() -> impl IntoView {
let des_logic = Box::new( view! { <CipherForm algorithm=Algorithm::Des /> }
|encrypt: bool, key_str: String, text_str: String| -> (String, String) {
(String::new(), String::new())
},
);
view! { <CipherForm title="DES" logic=des_logic /> }
} }

View File

@ -1,2 +1,3 @@
pub mod aes;
pub mod des; pub mod des;
pub mod home; pub mod home;

View File

@ -26,6 +26,8 @@ $l-iris: #907aa9;
$l-hl-low: #f4ede8; $l-hl-low: #f4ede8;
$l-hl-high: #cecacd; $l-hl-high: #cecacd;
$control-height: 46px;
:root, :root,
body.dark-theme { body.dark-theme {
// Default to Dark Mode // Default to Dark Mode
@ -135,13 +137,116 @@ main {
border-radius: 12px; border-radius: 12px;
padding: 2rem; padding: 2rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}
.card-header {
border-bottom: 1px solid var(--border);
padding-bottom: 1rem;
margin-bottom: 1.5rem;
h2 { h2 {
margin-top: 0; margin: 0;
border: none;
padding: none;
color: var(--secondary); color: var(--secondary);
border-bottom: 1px solid var(--border); font-size: 1.5rem;
padding-bottom: 15px; }
margin-bottom: 25px; }
.controls-row {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 10px;
min-height: $control-height;
}
.radio-group {
display: flex;
justify-content: center;
align-items: center;
gap: 20px;
background: var(--bg-input);
border-radius: 8px;
width: fit-content;
height: $control-height;
padding: 0 16px;
box-sizing: border-box;
.radio-button {
label {
margin: 0;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
color: var(--text-main);
text-transform: none;
height: 100%;
}
input[type="radio"] {
accent-color: var(--primary);
margin: 0;
}
}
}
.format-controls-box {
display: flex;
font-size: 0.9rem;
background: var(--bg-input);
border-radius: 8px;
height: $control-height;
padding: 0 12px;
box-sizing: border-box;
animation: fadeIn 0.2s ease-in-out;
.format-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
label {
margin: 0;
color: var(--text-muted);
font-weight: normal;
white-space: nowrap;
}
select {
height: 32px;
padding: 0 12px;
border-radius: 6px;
border: 1px solid var(--border);
background-color: var(--bg-input);
color: var(--text-main);
cursor: pointer;
font-size: 0.9rem;
box-sizing: border-box;
&:focus {
outline: none;
border-color: var(--primary);
}
}
}
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateX(5px);
}
to {
opacity: 1;
transform: translateX(0);
} }
} }
@ -183,29 +288,6 @@ main {
} }
} }
.radio-group {
display: flex;
gap: 20px;
background: var(--bg-input);
padding: 10px;
border-radius: 8px;
width: fit-content;
label {
margin: 0;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
color: var(--text-main);
text-transform: none;
}
input[type="radio"] {
accent-color: var(--primary);
}
}
.btn-primary { .btn-primary {
background-color: var(--primary); background-color: var(--primary);
color: var(--bg-body); color: var(--bg-body);
@ -232,25 +314,66 @@ main {
border-radius: 6px; border-radius: 6px;
} }
.error-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
background-color: rgba(0, 0, 0, 0.03);
border-bottom: 1px solid var(--border);
strong {
background: transparent;
padding: 0;
color: var(--text-muted);
}
}
.result-box { .result-box {
margin-top: 1.5rem; margin-top: 1.5rem;
background: var(--bg-highlight); background: var(--bg-highlight);
border-radius: 8px; border-radius: 8px;
border: 1px solid var(--border);
overflow: hidden; overflow: hidden;
strong {
display: block;
padding: 8px 12px;
background: rgba(0, 0, 0, 0.1);
color: var(--text-muted);
font-size: 0.85rem;
}
code { code {
display: block; display: block;
padding: 15px; padding: 15px;
word-break: break-all; word-break: break-all;
font-family: "Consolas", "Monaco", monospace; font-family: "Consolas", "Monaco", monospace;
color: var(--accent); color: var(--accent);
background: transparent;
}
}
.result-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 12px;
background-color: rgba(0, 0, 0, 0.05);
border-bottom: 1px solid var(--border);
strong {
font-size: 0.85rem;
color: var(--text-muted);
}
}
.btn-copy {
background: transparent;
border: none;
color: var(--primary);
font-weight: 700;
font-size: 0.85rem;
cursor: pointer;
text-transform: uppercase;
letter-spacing: 0.05em;
padding: 4px 8px;
border-radius: 4px;
transition: all 0.2s;
&:hover {
background-color: rgba(0, 0, 0, 0.05);
} }
} }