Skip to content

Commit

Permalink
adding caesar cipher
Browse files Browse the repository at this point in the history
  • Loading branch information
noahgift committed Jul 21, 2023
1 parent 0666f84 commit 9c7b3d9
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 0 deletions.
8 changes: 8 additions & 0 deletions caesar-cipher/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "caesar-cipher"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
13 changes: 13 additions & 0 deletions caesar-cipher/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
format:
cargo fmt --quiet

lint:
cargo clippy --quiet

test:
cargo test --quiet

run:
cargo run

all: format lint test run
24 changes: 24 additions & 0 deletions caesar-cipher/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
This code defines two functions: encrypt and decrypt.
The encrypt function takes a plaintext string and a shift value, and returns the ciphertext string. The decrypt function takes a ciphertext string and a shift value,
and returns the plaintext string.
*/

pub fn encrypt(text: &str, shift: u8) -> String {
let mut result = String::new();
for c in text.chars() {
if c.is_ascii_alphabetic() {
let base = if c.is_ascii_lowercase() { b'a' } else { b'A' };
let offset = (c as u8 - base + shift) % 26;
result.push((base + offset) as char);
} else {
result.push(c);
}
}
result
}

pub fn decrypt(text: &str, shift: u8) -> String {
encrypt(text, 26 - shift)
}
21 changes: 21 additions & 0 deletions caesar-cipher/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
This code defines two functions: encrypt and decrypt.
The encrypt function takes a plaintext string and a shift value,
and returns the ciphertext string.
The decrypt function takes a ciphertext string and a shift value,
and returns the plaintext string.
*/

use caesar_cipher::decrypt;
use caesar_cipher::encrypt;

fn main() {
let plaintext = "the quick brown fox jumps over the lazy dog";
let shift = 3;
let ciphertext = encrypt(plaintext, shift);
let decrypted_text = decrypt(&ciphertext, shift);
println!("Plaintext: {}", plaintext);
println!("Ciphertext: {}", ciphertext);
println!("Decrypted text: {}", decrypted_text);
}

0 comments on commit 9c7b3d9

Please sign in to comment.