Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,3 +5,5 @@ mutants.out*/

.idea/
.vscode/

.claude/*
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ version = "0.1.3"

# *** Internal Dependencies ***
bouncycastle = { path = "./" }
bouncycastle-ascon = { path = "./crypto/ascon" }
bouncycastle-base64 = { path = "./crypto/base64" }
bouncycastle-core = { path = "crypto/core" }
bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" }
Expand DownExpand Up@@ -41,6 +42,7 @@ version.workspace = true
edition.workspace = true

[dependencies]
bouncycastle-ascon.workspace = true
bouncycastle-base64.workspace = true
bouncycastle-core.workspace = true
bouncycastle-factory.workspace = true
Expand Down
152 changes: 152 additions & 0 deletions cli/src/ascon_cmd.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
use std::io::{Read, Write};
use std::process::exit;
use std::{fs, io};

use bouncycastle::ascon::ascon_aead128::AsconAead128;
use bouncycastle::ascon::ascon_cxof128::AsconCXof128;
use bouncycastle::ascon::ascon_hash256::AsconHash256;
use bouncycastle::ascon::ascon_xof128::AsconXof128;
use bouncycastle::core::traits::{Hash, XOF};
use bouncycastle::hex;

/// Write `data` to stdout, either as hex or raw binary, followed by a newline.
fn emit(data: &[u8], output_hex: bool) {
if output_hex {
for b in data.iter() {
print!("{b:02x}");
}
} else {
io::stdout().write_all(data).unwrap();
}
println!();
}

/// Read all of stdin into a Vec.
fn read_stdin() -> Vec<u8> {
let mut data = Vec::new();
io::stdin().read_to_end(&mut data).expect("Failed to read from stdin");
data
}

/// Load a hex string or a binary file into bytes; exits with an error if neither is supplied.
fn load_bytes(value: &Option<String>, value_file: &Option<String>, label: &str) -> Vec<u8> {
if let Some(file) = value_file {
fs::read(file).unwrap_or_else(|e| {
eprintln!("Error: failed to read {label} file: {e}");
exit(-1)
})
} else if let Some(v) = value {
hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: {label} is not valid hex.");
exit(-1)
})
} else {
eprintln!("Error: {label} must be supplied.");
exit(-1)
}
}

fn require_16(bytes: Vec<u8>, label: &str) -> [u8; 16] {
bytes.try_into().unwrap_or_else(|_: Vec<u8>| {
eprintln!("Error: {label} must be exactly 16 bytes.");
exit(-1)
})
}

/// Ascon-Hash256 of stdin. Streaming update; 256-bit digest.
pub(crate) fn hash256_cmd(output_hex: bool) {
let mut h = AsconHash256::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
h.do_update(&buf[..bytes_read]);
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = h.do_final();
emit(&out, output_hex);
}

/// Ascon-XOF128 of stdin, producing `output_len` bytes. Streaming absorb.
pub(crate) fn xof128_cmd(output_len: usize, output_hex: bool) {
let mut x = AsconXof128::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-CXOF128 of stdin with a hex customization string, producing `output_len` bytes.
pub(crate) fn cxof128_cmd(customization: &Option<String>, output_len: usize, output_hex: bool) {
let z = match customization {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: customization is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let mut x = AsconCXof128::with_customization(&z);
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-AEAD128 of stdin. Encrypts (stdin = plaintext, output = ciphertext||tag) or, with
/// `decrypt`, decrypts (stdin = ciphertext||tag, output = plaintext). Decryption exits with a
/// non-zero status if the authentication tag does not verify.
#[allow(clippy::too_many_arguments)]
pub(crate) fn aead128_cmd(
key: &Option<String>,
key_file: &Option<String>,
nonce: &Option<String>,
nonce_file: &Option<String>,
ad: &Option<String>,
decrypt: bool,
output_hex: bool,
) {
let key = require_16(load_bytes(key, key_file, "key"), "key");
let nonce = require_16(load_bytes(nonce, nonce_file, "nonce"), "nonce");
let ad_bytes = match ad {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: associated data is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let ad_opt = if ad_bytes.is_empty() { None } else { Some(ad_bytes.as_slice()) };

let input = read_stdin();

if decrypt {
if input.len() < 16 {
eprintln!("Error: ciphertext is shorter than the 16-byte tag.");
exit(-1);
}
let mut out = vec![0u8; input.len() - 16];
match AsconAead128::decrypt(&key, &nonce, ad_opt, &input, &mut out) {
Ok(n) => {
out.truncate(n);
emit(&out, output_hex);
}
Err(_) => {
eprintln!("Error: Ascon-AEAD128 authentication failed.");
exit(-1);
}
}
} else {
let mut out = vec![0u8; input.len() + 16];
let n = AsconAead128::encrypt(&key, &nonce, ad_opt, &input, &mut out);
out.truncate(n);
emit(&out, output_hex);
}
}
83 changes: 83 additions & 0 deletions cli/src/main.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
mod ascon_cmd;
mod encoders_cmd;
mod helpers;
mod hkdf_cmd;
Expand DownExpand Up@@ -124,6 +125,76 @@ enum Subcommands {
x: bool,
},

/// Perform Ascon-Hash256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
AsconHash256 {
#[arg(short)]
/// Output the digest in hex format.
x: bool,
},

/// Perform Ascon-XOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconXOF128 {
/// Length of the output in bytes.
length: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform Ascon-CXOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconCXOF128 {
/// Length of the output in bytes.
length: usize,

/// Customization string in hex (optional).
#[arg(long)]
customization: Option<String>,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Ascon-AEAD128 authenticated encryption/decryption of the content provided on stdin.
/// Encrypts by default (stdin = plaintext, output = ciphertext||tag); with --decrypt the
/// reverse. Decryption fails with a non-zero exit status if the tag does not verify.
/// Note: in production uses, secrets should not be passed on the command-line because they get
/// logged in shell history. Use the file-based input instead.
AsconAEAD128 {
/// The 128-bit key in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<String>,

/// A file containing the 128-bit key in binary.
#[arg(long)]
key_file: Option<String>,

/// The 128-bit nonce in hex. Must be unique per encryption under a given key.
#[arg(long)]
nonce: Option<String>,

/// A file containing the 128-bit nonce in binary.
#[arg(long)]
nonce_file: Option<String>,

/// Associated data in hex (authenticated but not encrypted).
#[arg(long)]
ad: Option<String>,

/// Decrypt instead of encrypt.
#[arg(short, long)]
decrypt: bool,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform HMAC-SHA256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
/// Note: in production uses, secrets should not be passed on the command-line because they get
Expand DownExpand Up@@ -531,6 +602,18 @@ fn main() {
Some(Subcommands::SHAKE256 { length, x }) => {
sha3_cmd::shake_cmd(256, *length, *x);
}
Some(Subcommands::AsconHash256 { x }) => {
ascon_cmd::hash256_cmd(*x);
}
Some(Subcommands::AsconXOF128 { length, x }) => {
ascon_cmd::xof128_cmd(*length, *x);
}
Some(Subcommands::AsconCXOF128 { length, customization, x }) => {
ascon_cmd::cxof128_cmd(customization, *length, *x);
}
Some(Subcommands::AsconAEAD128 { key, key_file, nonce, nonce_file, ad, decrypt, x }) => {
ascon_cmd::aead128_cmd(key, key_file, nonce, nonce_file, ad, *decrypt, *x);
}
Some(Subcommands::HMAC_SHA256 { key, key_file, verify, x }) => {
mac_cmd::mac_cmd(HMACVariant::SHA256, key, key_file, verify, *x)
}
Expand Down
27 changes: 27 additions & 0 deletions crypto/ascon/Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
[package]
name = "bouncycastle-ascon"
version.workspace = true
edition.workspace = true

[features]
# `std` gates the ergonomic, allocating (`Vec`-returning) one-shot cipher APIs, mirroring the
# `std` feature of `bouncycastle-core`. On by default; a future `--no-default-features` build is
# what will let the crate move toward `#![no_std]`.
default = ["std"]
std = ["bouncycastle-core/std"]

[dependencies]
bouncycastle-core.workspace = true
bouncycastle-rng.workspace = true
bouncycastle-utils.workspace = true

[dev-dependencies]
bouncycastle-core-test-framework.workspace = true
bouncycastle-hex.workspace = true
bouncycastle-rng.workspace = true
criterion.workspace = true
serde_json = "1.0" # todo -- why?

[[bench]]
name = "ascon_benches"
harness = false
90 changes: 90 additions & 0 deletions crypto/ascon/benches/ascon_benches.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
use bouncycastle_rng as rng;
use criterion::{Criterion, Throughput, criterion_group, criterion_main};
use std::hint::black_box;

use bouncycastle_ascon::ascon_aead128::AsconAead128;
use bouncycastle_ascon::ascon_cxof128::AsconCXof128;
use bouncycastle_ascon::ascon_hash256::AsconHash256;
use bouncycastle_ascon::ascon_xof128::AsconXof128;
use bouncycastle_core::traits::{Hash, RNG, XOF};

const DATA_LEN: usize = 16 * 1024;

fn random_data(len: usize) -> Vec<u8> {
let mut data = vec![0u8; len];
rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap();
data
}

fn bench_aead128_encrypt(c: &mut Criterion) {
let key = [0x42u8; 16];
let nonce = [0x24u8; 16];
let data = random_data(DATA_LEN);
let mut out = vec![0u8; DATA_LEN + 16];

let mut group = c.benchmark_group("ascon::AsconAead128");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::encrypt()"), |b| {
b.iter(|| {
AsconAead128::encrypt(&key, &nonce, None, black_box(&data), &mut out);
black_box(&out);
})
});
group.finish();
}

fn bench_hash256(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut digest = [0u8; 32];

let mut group = c.benchmark_group("ascon::AsconHash256");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::hash_out()"), |b| {
b.iter(|| {
AsconHash256::new().hash_out(black_box(&data), &mut digest);
black_box(&digest);
})
});
group.finish();
}

fn bench_xof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconXof128::new().hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

fn bench_cxof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let customization = b"bench-customization";
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconCXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconCXof128::with_customization(customization)
.hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

criterion_group!(benches, bench_aead128_encrypt, bench_hash256, bench_xof128, bench_cxof128);
criterion_main!(benches);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,3 +5,5 @@ mutants.out*/

.idea/
.vscode/

.claude/*
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ version = "0.1.3"

# *** Internal Dependencies ***
bouncycastle = { path = "./" }
bouncycastle-ascon = { path = "./crypto/ascon" }
bouncycastle-base64 = { path = "./crypto/base64" }
bouncycastle-core = { path = "crypto/core" }
bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" }
Expand DownExpand Up@@ -41,6 +42,7 @@ version.workspace = true
edition.workspace = true

[dependencies]
bouncycastle-ascon.workspace = true
bouncycastle-base64.workspace = true
bouncycastle-core.workspace = true
bouncycastle-factory.workspace = true
Expand Down
152 changes: 152 additions & 0 deletions cli/src/ascon_cmd.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
use std::io::{Read, Write};
use std::process::exit;
use std::{fs, io};

use bouncycastle::ascon::ascon_aead128::AsconAead128;
use bouncycastle::ascon::ascon_cxof128::AsconCXof128;
use bouncycastle::ascon::ascon_hash256::AsconHash256;
use bouncycastle::ascon::ascon_xof128::AsconXof128;
use bouncycastle::core::traits::{Hash, XOF};
use bouncycastle::hex;

/// Write `data` to stdout, either as hex or raw binary, followed by a newline.
fn emit(data: &[u8], output_hex: bool) {
if output_hex {
for b in data.iter() {
print!("{b:02x}");
}
} else {
io::stdout().write_all(data).unwrap();
}
println!();
}

/// Read all of stdin into a Vec.
fn read_stdin() -> Vec<u8> {
let mut data = Vec::new();
io::stdin().read_to_end(&mut data).expect("Failed to read from stdin");
data
}

/// Load a hex string or a binary file into bytes; exits with an error if neither is supplied.
fn load_bytes(value: &Option<String>, value_file: &Option<String>, label: &str) -> Vec<u8> {
if let Some(file) = value_file {
fs::read(file).unwrap_or_else(|e| {
eprintln!("Error: failed to read {label} file: {e}");
exit(-1)
})
} else if let Some(v) = value {
hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: {label} is not valid hex.");
exit(-1)
})
} else {
eprintln!("Error: {label} must be supplied.");
exit(-1)
}
}

fn require_16(bytes: Vec<u8>, label: &str) -> [u8; 16] {
bytes.try_into().unwrap_or_else(|_: Vec<u8>| {
eprintln!("Error: {label} must be exactly 16 bytes.");
exit(-1)
})
}

/// Ascon-Hash256 of stdin. Streaming update; 256-bit digest.
pub(crate) fn hash256_cmd(output_hex: bool) {
let mut h = AsconHash256::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
h.do_update(&buf[..bytes_read]);
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = h.do_final();
emit(&out, output_hex);
}

/// Ascon-XOF128 of stdin, producing `output_len` bytes. Streaming absorb.
pub(crate) fn xof128_cmd(output_len: usize, output_hex: bool) {
let mut x = AsconXof128::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-CXOF128 of stdin with a hex customization string, producing `output_len` bytes.
pub(crate) fn cxof128_cmd(customization: &Option<String>, output_len: usize, output_hex: bool) {
let z = match customization {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: customization is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let mut x = AsconCXof128::with_customization(&z);
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-AEAD128 of stdin. Encrypts (stdin = plaintext, output = ciphertext||tag) or, with
/// `decrypt`, decrypts (stdin = ciphertext||tag, output = plaintext). Decryption exits with a
/// non-zero status if the authentication tag does not verify.
#[allow(clippy::too_many_arguments)]
pub(crate) fn aead128_cmd(
key: &Option<String>,
key_file: &Option<String>,
nonce: &Option<String>,
nonce_file: &Option<String>,
ad: &Option<String>,
decrypt: bool,
output_hex: bool,
) {
let key = require_16(load_bytes(key, key_file, "key"), "key");
let nonce = require_16(load_bytes(nonce, nonce_file, "nonce"), "nonce");
let ad_bytes = match ad {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: associated data is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let ad_opt = if ad_bytes.is_empty() { None } else { Some(ad_bytes.as_slice()) };

let input = read_stdin();

if decrypt {
if input.len() < 16 {
eprintln!("Error: ciphertext is shorter than the 16-byte tag.");
exit(-1);
}
let mut out = vec![0u8; input.len() - 16];
match AsconAead128::decrypt(&key, &nonce, ad_opt, &input, &mut out) {
Ok(n) => {
out.truncate(n);
emit(&out, output_hex);
}
Err(_) => {
eprintln!("Error: Ascon-AEAD128 authentication failed.");
exit(-1);
}
}
} else {
let mut out = vec![0u8; input.len() + 16];
let n = AsconAead128::encrypt(&key, &nonce, ad_opt, &input, &mut out);
out.truncate(n);
emit(&out, output_hex);
}
}
83 changes: 83 additions & 0 deletions cli/src/main.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
mod ascon_cmd;
mod encoders_cmd;
mod helpers;
mod hkdf_cmd;
Expand DownExpand Up@@ -124,6 +125,76 @@ enum Subcommands {
x: bool,
},

/// Perform Ascon-Hash256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
AsconHash256 {
#[arg(short)]
/// Output the digest in hex format.
x: bool,
},

/// Perform Ascon-XOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconXOF128 {
/// Length of the output in bytes.
length: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform Ascon-CXOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconCXOF128 {
/// Length of the output in bytes.
length: usize,

/// Customization string in hex (optional).
#[arg(long)]
customization: Option<String>,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Ascon-AEAD128 authenticated encryption/decryption of the content provided on stdin.
/// Encrypts by default (stdin = plaintext, output = ciphertext||tag); with --decrypt the
/// reverse. Decryption fails with a non-zero exit status if the tag does not verify.
/// Note: in production uses, secrets should not be passed on the command-line because they get
/// logged in shell history. Use the file-based input instead.
AsconAEAD128 {
/// The 128-bit key in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<String>,

/// A file containing the 128-bit key in binary.
#[arg(long)]
key_file: Option<String>,

/// The 128-bit nonce in hex. Must be unique per encryption under a given key.
#[arg(long)]
nonce: Option<String>,

/// A file containing the 128-bit nonce in binary.
#[arg(long)]
nonce_file: Option<String>,

/// Associated data in hex (authenticated but not encrypted).
#[arg(long)]
ad: Option<String>,

/// Decrypt instead of encrypt.
#[arg(short, long)]
decrypt: bool,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform HMAC-SHA256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
/// Note: in production uses, secrets should not be passed on the command-line because they get
Expand DownExpand Up@@ -531,6 +602,18 @@ fn main() {
Some(Subcommands::SHAKE256 { length, x }) => {
sha3_cmd::shake_cmd(256, *length, *x);
}
Some(Subcommands::AsconHash256 { x }) => {
ascon_cmd::hash256_cmd(*x);
}
Some(Subcommands::AsconXOF128 { length, x }) => {
ascon_cmd::xof128_cmd(*length, *x);
}
Some(Subcommands::AsconCXOF128 { length, customization, x }) => {
ascon_cmd::cxof128_cmd(customization, *length, *x);
}
Some(Subcommands::AsconAEAD128 { key, key_file, nonce, nonce_file, ad, decrypt, x }) => {
ascon_cmd::aead128_cmd(key, key_file, nonce, nonce_file, ad, *decrypt, *x);
}
Some(Subcommands::HMAC_SHA256 { key, key_file, verify, x }) => {
mac_cmd::mac_cmd(HMACVariant::SHA256, key, key_file, verify, *x)
}
Expand Down
27 changes: 27 additions & 0 deletions crypto/ascon/Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
[package]
name = "bouncycastle-ascon"
version.workspace = true
edition.workspace = true

[features]
# `std` gates the ergonomic, allocating (`Vec`-returning) one-shot cipher APIs, mirroring the
# `std` feature of `bouncycastle-core`. On by default; a future `--no-default-features` build is
# what will let the crate move toward `#![no_std]`.
default = ["std"]
std = ["bouncycastle-core/std"]

[dependencies]
bouncycastle-core.workspace = true
bouncycastle-rng.workspace = true
bouncycastle-utils.workspace = true

[dev-dependencies]
bouncycastle-core-test-framework.workspace = true
bouncycastle-hex.workspace = true
bouncycastle-rng.workspace = true
criterion.workspace = true
serde_json = "1.0" # todo -- why?

[[bench]]
name = "ascon_benches"
harness = false
90 changes: 90 additions & 0 deletions crypto/ascon/benches/ascon_benches.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
use bouncycastle_rng as rng;
use criterion::{Criterion, Throughput, criterion_group, criterion_main};
use std::hint::black_box;

use bouncycastle_ascon::ascon_aead128::AsconAead128;
use bouncycastle_ascon::ascon_cxof128::AsconCXof128;
use bouncycastle_ascon::ascon_hash256::AsconHash256;
use bouncycastle_ascon::ascon_xof128::AsconXof128;
use bouncycastle_core::traits::{Hash, RNG, XOF};

const DATA_LEN: usize = 16 * 1024;

fn random_data(len: usize) -> Vec<u8> {
let mut data = vec![0u8; len];
rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap();
data
}

fn bench_aead128_encrypt(c: &mut Criterion) {
let key = [0x42u8; 16];
let nonce = [0x24u8; 16];
let data = random_data(DATA_LEN);
let mut out = vec![0u8; DATA_LEN + 16];

let mut group = c.benchmark_group("ascon::AsconAead128");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::encrypt()"), |b| {
b.iter(|| {
AsconAead128::encrypt(&key, &nonce, None, black_box(&data), &mut out);
black_box(&out);
})
});
group.finish();
}

fn bench_hash256(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut digest = [0u8; 32];

let mut group = c.benchmark_group("ascon::AsconHash256");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::hash_out()"), |b| {
b.iter(|| {
AsconHash256::new().hash_out(black_box(&data), &mut digest);
black_box(&digest);
})
});
group.finish();
}

fn bench_xof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconXof128::new().hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

fn bench_cxof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let customization = b"bench-customization";
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconCXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconCXof128::with_customization(customization)
.hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

criterion_group!(benches, bench_aead128_encrypt, bench_hash256, bench_xof128, bench_cxof128);
criterion_main!(benches);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,3 +5,5 @@ mutants.out*/

.idea/
.vscode/

.claude/*
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ version = "0.1.3"

# *** Internal Dependencies ***
bouncycastle = { path = "./" }
bouncycastle-ascon = { path = "./crypto/ascon" }
bouncycastle-base64 = { path = "./crypto/base64" }
bouncycastle-core = { path = "crypto/core" }
bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" }
Expand DownExpand Up@@ -41,6 +42,7 @@ version.workspace = true
edition.workspace = true

[dependencies]
bouncycastle-ascon.workspace = true
bouncycastle-base64.workspace = true
bouncycastle-core.workspace = true
bouncycastle-factory.workspace = true
Expand Down
152 changes: 152 additions & 0 deletions cli/src/ascon_cmd.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
use std::io::{Read, Write};
use std::process::exit;
use std::{fs, io};

use bouncycastle::ascon::ascon_aead128::AsconAead128;
use bouncycastle::ascon::ascon_cxof128::AsconCXof128;
use bouncycastle::ascon::ascon_hash256::AsconHash256;
use bouncycastle::ascon::ascon_xof128::AsconXof128;
use bouncycastle::core::traits::{Hash, XOF};
use bouncycastle::hex;

/// Write `data` to stdout, either as hex or raw binary, followed by a newline.
fn emit(data: &[u8], output_hex: bool) {
if output_hex {
for b in data.iter() {
print!("{b:02x}");
}
} else {
io::stdout().write_all(data).unwrap();
}
println!();
}

/// Read all of stdin into a Vec.
fn read_stdin() -> Vec<u8> {
let mut data = Vec::new();
io::stdin().read_to_end(&mut data).expect("Failed to read from stdin");
data
}

/// Load a hex string or a binary file into bytes; exits with an error if neither is supplied.
fn load_bytes(value: &Option<String>, value_file: &Option<String>, label: &str) -> Vec<u8> {
if let Some(file) = value_file {
fs::read(file).unwrap_or_else(|e| {
eprintln!("Error: failed to read {label} file: {e}");
exit(-1)
})
} else if let Some(v) = value {
hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: {label} is not valid hex.");
exit(-1)
})
} else {
eprintln!("Error: {label} must be supplied.");
exit(-1)
}
}

fn require_16(bytes: Vec<u8>, label: &str) -> [u8; 16] {
bytes.try_into().unwrap_or_else(|_: Vec<u8>| {
eprintln!("Error: {label} must be exactly 16 bytes.");
exit(-1)
})
}

/// Ascon-Hash256 of stdin. Streaming update; 256-bit digest.
pub(crate) fn hash256_cmd(output_hex: bool) {
let mut h = AsconHash256::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
h.do_update(&buf[..bytes_read]);
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = h.do_final();
emit(&out, output_hex);
}

/// Ascon-XOF128 of stdin, producing `output_len` bytes. Streaming absorb.
pub(crate) fn xof128_cmd(output_len: usize, output_hex: bool) {
let mut x = AsconXof128::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-CXOF128 of stdin with a hex customization string, producing `output_len` bytes.
pub(crate) fn cxof128_cmd(customization: &Option<String>, output_len: usize, output_hex: bool) {
let z = match customization {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: customization is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let mut x = AsconCXof128::with_customization(&z);
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-AEAD128 of stdin. Encrypts (stdin = plaintext, output = ciphertext||tag) or, with
/// `decrypt`, decrypts (stdin = ciphertext||tag, output = plaintext). Decryption exits with a
/// non-zero status if the authentication tag does not verify.
#[allow(clippy::too_many_arguments)]
pub(crate) fn aead128_cmd(
key: &Option<String>,
key_file: &Option<String>,
nonce: &Option<String>,
nonce_file: &Option<String>,
ad: &Option<String>,
decrypt: bool,
output_hex: bool,
) {
let key = require_16(load_bytes(key, key_file, "key"), "key");
let nonce = require_16(load_bytes(nonce, nonce_file, "nonce"), "nonce");
let ad_bytes = match ad {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: associated data is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let ad_opt = if ad_bytes.is_empty() { None } else { Some(ad_bytes.as_slice()) };

let input = read_stdin();

if decrypt {
if input.len() < 16 {
eprintln!("Error: ciphertext is shorter than the 16-byte tag.");
exit(-1);
}
let mut out = vec![0u8; input.len() - 16];
match AsconAead128::decrypt(&key, &nonce, ad_opt, &input, &mut out) {
Ok(n) => {
out.truncate(n);
emit(&out, output_hex);
}
Err(_) => {
eprintln!("Error: Ascon-AEAD128 authentication failed.");
exit(-1);
}
}
} else {
let mut out = vec![0u8; input.len() + 16];
let n = AsconAead128::encrypt(&key, &nonce, ad_opt, &input, &mut out);
out.truncate(n);
emit(&out, output_hex);
}
}
83 changes: 83 additions & 0 deletions cli/src/main.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
mod ascon_cmd;
mod encoders_cmd;
mod helpers;
mod hkdf_cmd;
Expand DownExpand Up@@ -124,6 +125,76 @@ enum Subcommands {
x: bool,
},

/// Perform Ascon-Hash256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
AsconHash256 {
#[arg(short)]
/// Output the digest in hex format.
x: bool,
},

/// Perform Ascon-XOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconXOF128 {
/// Length of the output in bytes.
length: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform Ascon-CXOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconCXOF128 {
/// Length of the output in bytes.
length: usize,

/// Customization string in hex (optional).
#[arg(long)]
customization: Option<String>,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Ascon-AEAD128 authenticated encryption/decryption of the content provided on stdin.
/// Encrypts by default (stdin = plaintext, output = ciphertext||tag); with --decrypt the
/// reverse. Decryption fails with a non-zero exit status if the tag does not verify.
/// Note: in production uses, secrets should not be passed on the command-line because they get
/// logged in shell history. Use the file-based input instead.
AsconAEAD128 {
/// The 128-bit key in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<String>,

/// A file containing the 128-bit key in binary.
#[arg(long)]
key_file: Option<String>,

/// The 128-bit nonce in hex. Must be unique per encryption under a given key.
#[arg(long)]
nonce: Option<String>,

/// A file containing the 128-bit nonce in binary.
#[arg(long)]
nonce_file: Option<String>,

/// Associated data in hex (authenticated but not encrypted).
#[arg(long)]
ad: Option<String>,

/// Decrypt instead of encrypt.
#[arg(short, long)]
decrypt: bool,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform HMAC-SHA256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
/// Note: in production uses, secrets should not be passed on the command-line because they get
Expand DownExpand Up@@ -531,6 +602,18 @@ fn main() {
Some(Subcommands::SHAKE256 { length, x }) => {
sha3_cmd::shake_cmd(256, *length, *x);
}
Some(Subcommands::AsconHash256 { x }) => {
ascon_cmd::hash256_cmd(*x);
}
Some(Subcommands::AsconXOF128 { length, x }) => {
ascon_cmd::xof128_cmd(*length, *x);
}
Some(Subcommands::AsconCXOF128 { length, customization, x }) => {
ascon_cmd::cxof128_cmd(customization, *length, *x);
}
Some(Subcommands::AsconAEAD128 { key, key_file, nonce, nonce_file, ad, decrypt, x }) => {
ascon_cmd::aead128_cmd(key, key_file, nonce, nonce_file, ad, *decrypt, *x);
}
Some(Subcommands::HMAC_SHA256 { key, key_file, verify, x }) => {
mac_cmd::mac_cmd(HMACVariant::SHA256, key, key_file, verify, *x)
}
Expand Down
27 changes: 27 additions & 0 deletions crypto/ascon/Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
[package]
name = "bouncycastle-ascon"
version.workspace = true
edition.workspace = true

[features]
# `std` gates the ergonomic, allocating (`Vec`-returning) one-shot cipher APIs, mirroring the
# `std` feature of `bouncycastle-core`. On by default; a future `--no-default-features` build is
# what will let the crate move toward `#![no_std]`.
default = ["std"]
std = ["bouncycastle-core/std"]

[dependencies]
bouncycastle-core.workspace = true
bouncycastle-rng.workspace = true
bouncycastle-utils.workspace = true

[dev-dependencies]
bouncycastle-core-test-framework.workspace = true
bouncycastle-hex.workspace = true
bouncycastle-rng.workspace = true
criterion.workspace = true
serde_json = "1.0" # todo -- why?

[[bench]]
name = "ascon_benches"
harness = false
90 changes: 90 additions & 0 deletions crypto/ascon/benches/ascon_benches.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
use bouncycastle_rng as rng;
use criterion::{Criterion, Throughput, criterion_group, criterion_main};
use std::hint::black_box;

use bouncycastle_ascon::ascon_aead128::AsconAead128;
use bouncycastle_ascon::ascon_cxof128::AsconCXof128;
use bouncycastle_ascon::ascon_hash256::AsconHash256;
use bouncycastle_ascon::ascon_xof128::AsconXof128;
use bouncycastle_core::traits::{Hash, RNG, XOF};

const DATA_LEN: usize = 16 * 1024;

fn random_data(len: usize) -> Vec<u8> {
let mut data = vec![0u8; len];
rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap();
data
}

fn bench_aead128_encrypt(c: &mut Criterion) {
let key = [0x42u8; 16];
let nonce = [0x24u8; 16];
let data = random_data(DATA_LEN);
let mut out = vec![0u8; DATA_LEN + 16];

let mut group = c.benchmark_group("ascon::AsconAead128");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::encrypt()"), |b| {
b.iter(|| {
AsconAead128::encrypt(&key, &nonce, None, black_box(&data), &mut out);
black_box(&out);
})
});
group.finish();
}

fn bench_hash256(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut digest = [0u8; 32];

let mut group = c.benchmark_group("ascon::AsconHash256");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::hash_out()"), |b| {
b.iter(|| {
AsconHash256::new().hash_out(black_box(&data), &mut digest);
black_box(&digest);
})
});
group.finish();
}

fn bench_xof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconXof128::new().hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

fn bench_cxof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let customization = b"bench-customization";
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconCXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconCXof128::with_customization(customization)
.hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

criterion_group!(benches, bench_aead128_encrypt, bench_hash256, bench_xof128, bench_cxof128);
criterion_main!(benches);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,3 +5,5 @@ mutants.out*/

.idea/
.vscode/

.claude/*
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ version = "0.1.3"

# *** Internal Dependencies ***
bouncycastle = { path = "./" }
bouncycastle-ascon = { path = "./crypto/ascon" }
bouncycastle-base64 = { path = "./crypto/base64" }
bouncycastle-core = { path = "crypto/core" }
bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" }
Expand DownExpand Up@@ -41,6 +42,7 @@ version.workspace = true
edition.workspace = true

[dependencies]
bouncycastle-ascon.workspace = true
bouncycastle-base64.workspace = true
bouncycastle-core.workspace = true
bouncycastle-factory.workspace = true
Expand Down
152 changes: 152 additions & 0 deletions cli/src/ascon_cmd.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
use std::io::{Read, Write};
use std::process::exit;
use std::{fs, io};

use bouncycastle::ascon::ascon_aead128::AsconAead128;
use bouncycastle::ascon::ascon_cxof128::AsconCXof128;
use bouncycastle::ascon::ascon_hash256::AsconHash256;
use bouncycastle::ascon::ascon_xof128::AsconXof128;
use bouncycastle::core::traits::{Hash, XOF};
use bouncycastle::hex;

/// Write `data` to stdout, either as hex or raw binary, followed by a newline.
fn emit(data: &[u8], output_hex: bool) {
if output_hex {
for b in data.iter() {
print!("{b:02x}");
}
} else {
io::stdout().write_all(data).unwrap();
}
println!();
}

/// Read all of stdin into a Vec.
fn read_stdin() -> Vec<u8> {
let mut data = Vec::new();
io::stdin().read_to_end(&mut data).expect("Failed to read from stdin");
data
}

/// Load a hex string or a binary file into bytes; exits with an error if neither is supplied.
fn load_bytes(value: &Option<String>, value_file: &Option<String>, label: &str) -> Vec<u8> {
if let Some(file) = value_file {
fs::read(file).unwrap_or_else(|e| {
eprintln!("Error: failed to read {label} file: {e}");
exit(-1)
})
} else if let Some(v) = value {
hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: {label} is not valid hex.");
exit(-1)
})
} else {
eprintln!("Error: {label} must be supplied.");
exit(-1)
}
}

fn require_16(bytes: Vec<u8>, label: &str) -> [u8; 16] {
bytes.try_into().unwrap_or_else(|_: Vec<u8>| {
eprintln!("Error: {label} must be exactly 16 bytes.");
exit(-1)
})
}

/// Ascon-Hash256 of stdin. Streaming update; 256-bit digest.
pub(crate) fn hash256_cmd(output_hex: bool) {
let mut h = AsconHash256::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
h.do_update(&buf[..bytes_read]);
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = h.do_final();
emit(&out, output_hex);
}

/// Ascon-XOF128 of stdin, producing `output_len` bytes. Streaming absorb.
pub(crate) fn xof128_cmd(output_len: usize, output_hex: bool) {
let mut x = AsconXof128::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-CXOF128 of stdin with a hex customization string, producing `output_len` bytes.
pub(crate) fn cxof128_cmd(customization: &Option<String>, output_len: usize, output_hex: bool) {
let z = match customization {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: customization is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let mut x = AsconCXof128::with_customization(&z);
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-AEAD128 of stdin. Encrypts (stdin = plaintext, output = ciphertext||tag) or, with
/// `decrypt`, decrypts (stdin = ciphertext||tag, output = plaintext). Decryption exits with a
/// non-zero status if the authentication tag does not verify.
#[allow(clippy::too_many_arguments)]
pub(crate) fn aead128_cmd(
key: &Option<String>,
key_file: &Option<String>,
nonce: &Option<String>,
nonce_file: &Option<String>,
ad: &Option<String>,
decrypt: bool,
output_hex: bool,
) {
let key = require_16(load_bytes(key, key_file, "key"), "key");
let nonce = require_16(load_bytes(nonce, nonce_file, "nonce"), "nonce");
let ad_bytes = match ad {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: associated data is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let ad_opt = if ad_bytes.is_empty() { None } else { Some(ad_bytes.as_slice()) };

let input = read_stdin();

if decrypt {
if input.len() < 16 {
eprintln!("Error: ciphertext is shorter than the 16-byte tag.");
exit(-1);
}
let mut out = vec![0u8; input.len() - 16];
match AsconAead128::decrypt(&key, &nonce, ad_opt, &input, &mut out) {
Ok(n) => {
out.truncate(n);
emit(&out, output_hex);
}
Err(_) => {
eprintln!("Error: Ascon-AEAD128 authentication failed.");
exit(-1);
}
}
} else {
let mut out = vec![0u8; input.len() + 16];
let n = AsconAead128::encrypt(&key, &nonce, ad_opt, &input, &mut out);
out.truncate(n);
emit(&out, output_hex);
}
}
83 changes: 83 additions & 0 deletions cli/src/main.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
mod ascon_cmd;
mod encoders_cmd;
mod helpers;
mod hkdf_cmd;
Expand DownExpand Up@@ -124,6 +125,76 @@ enum Subcommands {
x: bool,
},

/// Perform Ascon-Hash256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
AsconHash256 {
#[arg(short)]
/// Output the digest in hex format.
x: bool,
},

/// Perform Ascon-XOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconXOF128 {
/// Length of the output in bytes.
length: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform Ascon-CXOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconCXOF128 {
/// Length of the output in bytes.
length: usize,

/// Customization string in hex (optional).
#[arg(long)]
customization: Option<String>,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Ascon-AEAD128 authenticated encryption/decryption of the content provided on stdin.
/// Encrypts by default (stdin = plaintext, output = ciphertext||tag); with --decrypt the
/// reverse. Decryption fails with a non-zero exit status if the tag does not verify.
/// Note: in production uses, secrets should not be passed on the command-line because they get
/// logged in shell history. Use the file-based input instead.
AsconAEAD128 {
/// The 128-bit key in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<String>,

/// A file containing the 128-bit key in binary.
#[arg(long)]
key_file: Option<String>,

/// The 128-bit nonce in hex. Must be unique per encryption under a given key.
#[arg(long)]
nonce: Option<String>,

/// A file containing the 128-bit nonce in binary.
#[arg(long)]
nonce_file: Option<String>,

/// Associated data in hex (authenticated but not encrypted).
#[arg(long)]
ad: Option<String>,

/// Decrypt instead of encrypt.
#[arg(short, long)]
decrypt: bool,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform HMAC-SHA256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
/// Note: in production uses, secrets should not be passed on the command-line because they get
Expand DownExpand Up@@ -531,6 +602,18 @@ fn main() {
Some(Subcommands::SHAKE256 { length, x }) => {
sha3_cmd::shake_cmd(256, *length, *x);
}
Some(Subcommands::AsconHash256 { x }) => {
ascon_cmd::hash256_cmd(*x);
}
Some(Subcommands::AsconXOF128 { length, x }) => {
ascon_cmd::xof128_cmd(*length, *x);
}
Some(Subcommands::AsconCXOF128 { length, customization, x }) => {
ascon_cmd::cxof128_cmd(customization, *length, *x);
}
Some(Subcommands::AsconAEAD128 { key, key_file, nonce, nonce_file, ad, decrypt, x }) => {
ascon_cmd::aead128_cmd(key, key_file, nonce, nonce_file, ad, *decrypt, *x);
}
Some(Subcommands::HMAC_SHA256 { key, key_file, verify, x }) => {
mac_cmd::mac_cmd(HMACVariant::SHA256, key, key_file, verify, *x)
}
Expand Down
27 changes: 27 additions & 0 deletions crypto/ascon/Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
[package]
name = "bouncycastle-ascon"
version.workspace = true
edition.workspace = true

[features]
# `std` gates the ergonomic, allocating (`Vec`-returning) one-shot cipher APIs, mirroring the
# `std` feature of `bouncycastle-core`. On by default; a future `--no-default-features` build is
# what will let the crate move toward `#![no_std]`.
default = ["std"]
std = ["bouncycastle-core/std"]

[dependencies]
bouncycastle-core.workspace = true
bouncycastle-rng.workspace = true
bouncycastle-utils.workspace = true

[dev-dependencies]
bouncycastle-core-test-framework.workspace = true
bouncycastle-hex.workspace = true
bouncycastle-rng.workspace = true
criterion.workspace = true
serde_json = "1.0" # todo -- why?

[[bench]]
name = "ascon_benches"
harness = false
90 changes: 90 additions & 0 deletions crypto/ascon/benches/ascon_benches.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
use bouncycastle_rng as rng;
use criterion::{Criterion, Throughput, criterion_group, criterion_main};
use std::hint::black_box;

use bouncycastle_ascon::ascon_aead128::AsconAead128;
use bouncycastle_ascon::ascon_cxof128::AsconCXof128;
use bouncycastle_ascon::ascon_hash256::AsconHash256;
use bouncycastle_ascon::ascon_xof128::AsconXof128;
use bouncycastle_core::traits::{Hash, RNG, XOF};

const DATA_LEN: usize = 16 * 1024;

fn random_data(len: usize) -> Vec<u8> {
let mut data = vec![0u8; len];
rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap();
data
}

fn bench_aead128_encrypt(c: &mut Criterion) {
let key = [0x42u8; 16];
let nonce = [0x24u8; 16];
let data = random_data(DATA_LEN);
let mut out = vec![0u8; DATA_LEN + 16];

let mut group = c.benchmark_group("ascon::AsconAead128");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::encrypt()"), |b| {
b.iter(|| {
AsconAead128::encrypt(&key, &nonce, None, black_box(&data), &mut out);
black_box(&out);
})
});
group.finish();
}

fn bench_hash256(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut digest = [0u8; 32];

let mut group = c.benchmark_group("ascon::AsconHash256");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::hash_out()"), |b| {
b.iter(|| {
AsconHash256::new().hash_out(black_box(&data), &mut digest);
black_box(&digest);
})
});
group.finish();
}

fn bench_xof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconXof128::new().hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

fn bench_cxof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let customization = b"bench-customization";
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconCXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconCXof128::with_customization(customization)
.hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

criterion_group!(benches, bench_aead128_encrypt, bench_hash256, bench_xof128, bench_cxof128);
criterion_main!(benches);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,3 +5,5 @@ mutants.out*/

.idea/
.vscode/

.claude/*
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ version = "0.1.3"

# *** Internal Dependencies ***
bouncycastle = { path = "./" }
bouncycastle-ascon = { path = "./crypto/ascon" }
bouncycastle-base64 = { path = "./crypto/base64" }
bouncycastle-core = { path = "crypto/core" }
bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" }
Expand DownExpand Up@@ -41,6 +42,7 @@ version.workspace = true
edition.workspace = true

[dependencies]
bouncycastle-ascon.workspace = true
bouncycastle-base64.workspace = true
bouncycastle-core.workspace = true
bouncycastle-factory.workspace = true
Expand Down
152 changes: 152 additions & 0 deletions cli/src/ascon_cmd.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
use std::io::{Read, Write};
use std::process::exit;
use std::{fs, io};

use bouncycastle::ascon::ascon_aead128::AsconAead128;
use bouncycastle::ascon::ascon_cxof128::AsconCXof128;
use bouncycastle::ascon::ascon_hash256::AsconHash256;
use bouncycastle::ascon::ascon_xof128::AsconXof128;
use bouncycastle::core::traits::{Hash, XOF};
use bouncycastle::hex;

/// Write `data` to stdout, either as hex or raw binary, followed by a newline.
fn emit(data: &[u8], output_hex: bool) {
if output_hex {
for b in data.iter() {
print!("{b:02x}");
}
} else {
io::stdout().write_all(data).unwrap();
}
println!();
}

/// Read all of stdin into a Vec.
fn read_stdin() -> Vec<u8> {
let mut data = Vec::new();
io::stdin().read_to_end(&mut data).expect("Failed to read from stdin");
data
}

/// Load a hex string or a binary file into bytes; exits with an error if neither is supplied.
fn load_bytes(value: &Option<String>, value_file: &Option<String>, label: &str) -> Vec<u8> {
if let Some(file) = value_file {
fs::read(file).unwrap_or_else(|e| {
eprintln!("Error: failed to read {label} file: {e}");
exit(-1)
})
} else if let Some(v) = value {
hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: {label} is not valid hex.");
exit(-1)
})
} else {
eprintln!("Error: {label} must be supplied.");
exit(-1)
}
}

fn require_16(bytes: Vec<u8>, label: &str) -> [u8; 16] {
bytes.try_into().unwrap_or_else(|_: Vec<u8>| {
eprintln!("Error: {label} must be exactly 16 bytes.");
exit(-1)
})
}

/// Ascon-Hash256 of stdin. Streaming update; 256-bit digest.
pub(crate) fn hash256_cmd(output_hex: bool) {
let mut h = AsconHash256::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
h.do_update(&buf[..bytes_read]);
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = h.do_final();
emit(&out, output_hex);
}

/// Ascon-XOF128 of stdin, producing `output_len` bytes. Streaming absorb.
pub(crate) fn xof128_cmd(output_len: usize, output_hex: bool) {
let mut x = AsconXof128::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-CXOF128 of stdin with a hex customization string, producing `output_len` bytes.
pub(crate) fn cxof128_cmd(customization: &Option<String>, output_len: usize, output_hex: bool) {
let z = match customization {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: customization is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let mut x = AsconCXof128::with_customization(&z);
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-AEAD128 of stdin. Encrypts (stdin = plaintext, output = ciphertext||tag) or, with
/// `decrypt`, decrypts (stdin = ciphertext||tag, output = plaintext). Decryption exits with a
/// non-zero status if the authentication tag does not verify.
#[allow(clippy::too_many_arguments)]
pub(crate) fn aead128_cmd(
key: &Option<String>,
key_file: &Option<String>,
nonce: &Option<String>,
nonce_file: &Option<String>,
ad: &Option<String>,
decrypt: bool,
output_hex: bool,
) {
let key = require_16(load_bytes(key, key_file, "key"), "key");
let nonce = require_16(load_bytes(nonce, nonce_file, "nonce"), "nonce");
let ad_bytes = match ad {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: associated data is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let ad_opt = if ad_bytes.is_empty() { None } else { Some(ad_bytes.as_slice()) };

let input = read_stdin();

if decrypt {
if input.len() < 16 {
eprintln!("Error: ciphertext is shorter than the 16-byte tag.");
exit(-1);
}
let mut out = vec![0u8; input.len() - 16];
match AsconAead128::decrypt(&key, &nonce, ad_opt, &input, &mut out) {
Ok(n) => {
out.truncate(n);
emit(&out, output_hex);
}
Err(_) => {
eprintln!("Error: Ascon-AEAD128 authentication failed.");
exit(-1);
}
}
} else {
let mut out = vec![0u8; input.len() + 16];
let n = AsconAead128::encrypt(&key, &nonce, ad_opt, &input, &mut out);
out.truncate(n);
emit(&out, output_hex);
}
}
83 changes: 83 additions & 0 deletions cli/src/main.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
mod ascon_cmd;
mod encoders_cmd;
mod helpers;
mod hkdf_cmd;
Expand DownExpand Up@@ -124,6 +125,76 @@ enum Subcommands {
x: bool,
},

/// Perform Ascon-Hash256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
AsconHash256 {
#[arg(short)]
/// Output the digest in hex format.
x: bool,
},

/// Perform Ascon-XOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconXOF128 {
/// Length of the output in bytes.
length: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform Ascon-CXOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconCXOF128 {
/// Length of the output in bytes.
length: usize,

/// Customization string in hex (optional).
#[arg(long)]
customization: Option<String>,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Ascon-AEAD128 authenticated encryption/decryption of the content provided on stdin.
/// Encrypts by default (stdin = plaintext, output = ciphertext||tag); with --decrypt the
/// reverse. Decryption fails with a non-zero exit status if the tag does not verify.
/// Note: in production uses, secrets should not be passed on the command-line because they get
/// logged in shell history. Use the file-based input instead.
AsconAEAD128 {
/// The 128-bit key in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<String>,

/// A file containing the 128-bit key in binary.
#[arg(long)]
key_file: Option<String>,

/// The 128-bit nonce in hex. Must be unique per encryption under a given key.
#[arg(long)]
nonce: Option<String>,

/// A file containing the 128-bit nonce in binary.
#[arg(long)]
nonce_file: Option<String>,

/// Associated data in hex (authenticated but not encrypted).
#[arg(long)]
ad: Option<String>,

/// Decrypt instead of encrypt.
#[arg(short, long)]
decrypt: bool,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform HMAC-SHA256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
/// Note: in production uses, secrets should not be passed on the command-line because they get
Expand DownExpand Up@@ -531,6 +602,18 @@ fn main() {
Some(Subcommands::SHAKE256 { length, x }) => {
sha3_cmd::shake_cmd(256, *length, *x);
}
Some(Subcommands::AsconHash256 { x }) => {
ascon_cmd::hash256_cmd(*x);
}
Some(Subcommands::AsconXOF128 { length, x }) => {
ascon_cmd::xof128_cmd(*length, *x);
}
Some(Subcommands::AsconCXOF128 { length, customization, x }) => {
ascon_cmd::cxof128_cmd(customization, *length, *x);
}
Some(Subcommands::AsconAEAD128 { key, key_file, nonce, nonce_file, ad, decrypt, x }) => {
ascon_cmd::aead128_cmd(key, key_file, nonce, nonce_file, ad, *decrypt, *x);
}
Some(Subcommands::HMAC_SHA256 { key, key_file, verify, x }) => {
mac_cmd::mac_cmd(HMACVariant::SHA256, key, key_file, verify, *x)
}
Expand Down
27 changes: 27 additions & 0 deletions crypto/ascon/Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
[package]
name = "bouncycastle-ascon"
version.workspace = true
edition.workspace = true

[features]
# `std` gates the ergonomic, allocating (`Vec`-returning) one-shot cipher APIs, mirroring the
# `std` feature of `bouncycastle-core`. On by default; a future `--no-default-features` build is
# what will let the crate move toward `#![no_std]`.
default = ["std"]
std = ["bouncycastle-core/std"]

[dependencies]
bouncycastle-core.workspace = true
bouncycastle-rng.workspace = true
bouncycastle-utils.workspace = true

[dev-dependencies]
bouncycastle-core-test-framework.workspace = true
bouncycastle-hex.workspace = true
bouncycastle-rng.workspace = true
criterion.workspace = true
serde_json = "1.0" # todo -- why?

[[bench]]
name = "ascon_benches"
harness = false
90 changes: 90 additions & 0 deletions crypto/ascon/benches/ascon_benches.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
use bouncycastle_rng as rng;
use criterion::{Criterion, Throughput, criterion_group, criterion_main};
use std::hint::black_box;

use bouncycastle_ascon::ascon_aead128::AsconAead128;
use bouncycastle_ascon::ascon_cxof128::AsconCXof128;
use bouncycastle_ascon::ascon_hash256::AsconHash256;
use bouncycastle_ascon::ascon_xof128::AsconXof128;
use bouncycastle_core::traits::{Hash, RNG, XOF};

const DATA_LEN: usize = 16 * 1024;

fn random_data(len: usize) -> Vec<u8> {
let mut data = vec![0u8; len];
rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap();
data
}

fn bench_aead128_encrypt(c: &mut Criterion) {
let key = [0x42u8; 16];
let nonce = [0x24u8; 16];
let data = random_data(DATA_LEN);
let mut out = vec![0u8; DATA_LEN + 16];

let mut group = c.benchmark_group("ascon::AsconAead128");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::encrypt()"), |b| {
b.iter(|| {
AsconAead128::encrypt(&key, &nonce, None, black_box(&data), &mut out);
black_box(&out);
})
});
group.finish();
}

fn bench_hash256(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut digest = [0u8; 32];

let mut group = c.benchmark_group("ascon::AsconHash256");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::hash_out()"), |b| {
b.iter(|| {
AsconHash256::new().hash_out(black_box(&data), &mut digest);
black_box(&digest);
})
});
group.finish();
}

fn bench_xof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconXof128::new().hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

fn bench_cxof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let customization = b"bench-customization";
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconCXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconCXof128::with_customization(customization)
.hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

criterion_group!(benches, bench_aead128_encrypt, bench_hash256, bench_xof128, bench_cxof128);
criterion_main!(benches);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,3 +5,5 @@ mutants.out*/

.idea/
.vscode/

.claude/*
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ version = "0.1.3"

# *** Internal Dependencies ***
bouncycastle = { path = "./" }
bouncycastle-ascon = { path = "./crypto/ascon" }
bouncycastle-base64 = { path = "./crypto/base64" }
bouncycastle-core = { path = "crypto/core" }
bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" }
Expand DownExpand Up@@ -41,6 +42,7 @@ version.workspace = true
edition.workspace = true

[dependencies]
bouncycastle-ascon.workspace = true
bouncycastle-base64.workspace = true
bouncycastle-core.workspace = true
bouncycastle-factory.workspace = true
Expand Down
152 changes: 152 additions & 0 deletions cli/src/ascon_cmd.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
use std::io::{Read, Write};
use std::process::exit;
use std::{fs, io};

use bouncycastle::ascon::ascon_aead128::AsconAead128;
use bouncycastle::ascon::ascon_cxof128::AsconCXof128;
use bouncycastle::ascon::ascon_hash256::AsconHash256;
use bouncycastle::ascon::ascon_xof128::AsconXof128;
use bouncycastle::core::traits::{Hash, XOF};
use bouncycastle::hex;

/// Write `data` to stdout, either as hex or raw binary, followed by a newline.
fn emit(data: &[u8], output_hex: bool) {
if output_hex {
for b in data.iter() {
print!("{b:02x}");
}
} else {
io::stdout().write_all(data).unwrap();
}
println!();
}

/// Read all of stdin into a Vec.
fn read_stdin() -> Vec<u8> {
let mut data = Vec::new();
io::stdin().read_to_end(&mut data).expect("Failed to read from stdin");
data
}

/// Load a hex string or a binary file into bytes; exits with an error if neither is supplied.
fn load_bytes(value: &Option<String>, value_file: &Option<String>, label: &str) -> Vec<u8> {
if let Some(file) = value_file {
fs::read(file).unwrap_or_else(|e| {
eprintln!("Error: failed to read {label} file: {e}");
exit(-1)
})
} else if let Some(v) = value {
hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: {label} is not valid hex.");
exit(-1)
})
} else {
eprintln!("Error: {label} must be supplied.");
exit(-1)
}
}

fn require_16(bytes: Vec<u8>, label: &str) -> [u8; 16] {
bytes.try_into().unwrap_or_else(|_: Vec<u8>| {
eprintln!("Error: {label} must be exactly 16 bytes.");
exit(-1)
})
}

/// Ascon-Hash256 of stdin. Streaming update; 256-bit digest.
pub(crate) fn hash256_cmd(output_hex: bool) {
let mut h = AsconHash256::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
h.do_update(&buf[..bytes_read]);
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = h.do_final();
emit(&out, output_hex);
}

/// Ascon-XOF128 of stdin, producing `output_len` bytes. Streaming absorb.
pub(crate) fn xof128_cmd(output_len: usize, output_hex: bool) {
let mut x = AsconXof128::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-CXOF128 of stdin with a hex customization string, producing `output_len` bytes.
pub(crate) fn cxof128_cmd(customization: &Option<String>, output_len: usize, output_hex: bool) {
let z = match customization {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: customization is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let mut x = AsconCXof128::with_customization(&z);
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-AEAD128 of stdin. Encrypts (stdin = plaintext, output = ciphertext||tag) or, with
/// `decrypt`, decrypts (stdin = ciphertext||tag, output = plaintext). Decryption exits with a
/// non-zero status if the authentication tag does not verify.
#[allow(clippy::too_many_arguments)]
pub(crate) fn aead128_cmd(
key: &Option<String>,
key_file: &Option<String>,
nonce: &Option<String>,
nonce_file: &Option<String>,
ad: &Option<String>,
decrypt: bool,
output_hex: bool,
) {
let key = require_16(load_bytes(key, key_file, "key"), "key");
let nonce = require_16(load_bytes(nonce, nonce_file, "nonce"), "nonce");
let ad_bytes = match ad {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: associated data is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let ad_opt = if ad_bytes.is_empty() { None } else { Some(ad_bytes.as_slice()) };

let input = read_stdin();

if decrypt {
if input.len() < 16 {
eprintln!("Error: ciphertext is shorter than the 16-byte tag.");
exit(-1);
}
let mut out = vec![0u8; input.len() - 16];
match AsconAead128::decrypt(&key, &nonce, ad_opt, &input, &mut out) {
Ok(n) => {
out.truncate(n);
emit(&out, output_hex);
}
Err(_) => {
eprintln!("Error: Ascon-AEAD128 authentication failed.");
exit(-1);
}
}
} else {
let mut out = vec![0u8; input.len() + 16];
let n = AsconAead128::encrypt(&key, &nonce, ad_opt, &input, &mut out);
out.truncate(n);
emit(&out, output_hex);
}
}
83 changes: 83 additions & 0 deletions cli/src/main.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
mod ascon_cmd;
mod encoders_cmd;
mod helpers;
mod hkdf_cmd;
Expand DownExpand Up@@ -124,6 +125,76 @@ enum Subcommands {
x: bool,
},

/// Perform Ascon-Hash256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
AsconHash256 {
#[arg(short)]
/// Output the digest in hex format.
x: bool,
},

/// Perform Ascon-XOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconXOF128 {
/// Length of the output in bytes.
length: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform Ascon-CXOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconCXOF128 {
/// Length of the output in bytes.
length: usize,

/// Customization string in hex (optional).
#[arg(long)]
customization: Option<String>,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Ascon-AEAD128 authenticated encryption/decryption of the content provided on stdin.
/// Encrypts by default (stdin = plaintext, output = ciphertext||tag); with --decrypt the
/// reverse. Decryption fails with a non-zero exit status if the tag does not verify.
/// Note: in production uses, secrets should not be passed on the command-line because they get
/// logged in shell history. Use the file-based input instead.
AsconAEAD128 {
/// The 128-bit key in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<String>,

/// A file containing the 128-bit key in binary.
#[arg(long)]
key_file: Option<String>,

/// The 128-bit nonce in hex. Must be unique per encryption under a given key.
#[arg(long)]
nonce: Option<String>,

/// A file containing the 128-bit nonce in binary.
#[arg(long)]
nonce_file: Option<String>,

/// Associated data in hex (authenticated but not encrypted).
#[arg(long)]
ad: Option<String>,

/// Decrypt instead of encrypt.
#[arg(short, long)]
decrypt: bool,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform HMAC-SHA256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
/// Note: in production uses, secrets should not be passed on the command-line because they get
Expand DownExpand Up@@ -531,6 +602,18 @@ fn main() {
Some(Subcommands::SHAKE256 { length, x }) => {
sha3_cmd::shake_cmd(256, *length, *x);
}
Some(Subcommands::AsconHash256 { x }) => {
ascon_cmd::hash256_cmd(*x);
}
Some(Subcommands::AsconXOF128 { length, x }) => {
ascon_cmd::xof128_cmd(*length, *x);
}
Some(Subcommands::AsconCXOF128 { length, customization, x }) => {
ascon_cmd::cxof128_cmd(customization, *length, *x);
}
Some(Subcommands::AsconAEAD128 { key, key_file, nonce, nonce_file, ad, decrypt, x }) => {
ascon_cmd::aead128_cmd(key, key_file, nonce, nonce_file, ad, *decrypt, *x);
}
Some(Subcommands::HMAC_SHA256 { key, key_file, verify, x }) => {
mac_cmd::mac_cmd(HMACVariant::SHA256, key, key_file, verify, *x)
}
Expand Down
27 changes: 27 additions & 0 deletions crypto/ascon/Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
[package]
name = "bouncycastle-ascon"
version.workspace = true
edition.workspace = true

[features]
# `std` gates the ergonomic, allocating (`Vec`-returning) one-shot cipher APIs, mirroring the
# `std` feature of `bouncycastle-core`. On by default; a future `--no-default-features` build is
# what will let the crate move toward `#![no_std]`.
default = ["std"]
std = ["bouncycastle-core/std"]

[dependencies]
bouncycastle-core.workspace = true
bouncycastle-rng.workspace = true
bouncycastle-utils.workspace = true

[dev-dependencies]
bouncycastle-core-test-framework.workspace = true
bouncycastle-hex.workspace = true
bouncycastle-rng.workspace = true
criterion.workspace = true
serde_json = "1.0" # todo -- why?

[[bench]]
name = "ascon_benches"
harness = false
90 changes: 90 additions & 0 deletions crypto/ascon/benches/ascon_benches.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
use bouncycastle_rng as rng;
use criterion::{Criterion, Throughput, criterion_group, criterion_main};
use std::hint::black_box;

use bouncycastle_ascon::ascon_aead128::AsconAead128;
use bouncycastle_ascon::ascon_cxof128::AsconCXof128;
use bouncycastle_ascon::ascon_hash256::AsconHash256;
use bouncycastle_ascon::ascon_xof128::AsconXof128;
use bouncycastle_core::traits::{Hash, RNG, XOF};

const DATA_LEN: usize = 16 * 1024;

fn random_data(len: usize) -> Vec<u8> {
let mut data = vec![0u8; len];
rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap();
data
}

fn bench_aead128_encrypt(c: &mut Criterion) {
let key = [0x42u8; 16];
let nonce = [0x24u8; 16];
let data = random_data(DATA_LEN);
let mut out = vec![0u8; DATA_LEN + 16];

let mut group = c.benchmark_group("ascon::AsconAead128");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::encrypt()"), |b| {
b.iter(|| {
AsconAead128::encrypt(&key, &nonce, None, black_box(&data), &mut out);
black_box(&out);
})
});
group.finish();
}

fn bench_hash256(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut digest = [0u8; 32];

let mut group = c.benchmark_group("ascon::AsconHash256");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::hash_out()"), |b| {
b.iter(|| {
AsconHash256::new().hash_out(black_box(&data), &mut digest);
black_box(&digest);
})
});
group.finish();
}

fn bench_xof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconXof128::new().hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

fn bench_cxof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let customization = b"bench-customization";
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconCXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconCXof128::with_customization(customization)
.hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

criterion_group!(benches, bench_aead128_encrypt, bench_hash256, bench_xof128, bench_cxof128);
criterion_main!(benches);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,3 +5,5 @@ mutants.out*/

.idea/
.vscode/

.claude/*
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ version = "0.1.3"

# *** Internal Dependencies ***
bouncycastle = { path = "./" }
bouncycastle-ascon = { path = "./crypto/ascon" }
bouncycastle-base64 = { path = "./crypto/base64" }
bouncycastle-core = { path = "crypto/core" }
bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" }
Expand DownExpand Up@@ -41,6 +42,7 @@ version.workspace = true
edition.workspace = true

[dependencies]
bouncycastle-ascon.workspace = true
bouncycastle-base64.workspace = true
bouncycastle-core.workspace = true
bouncycastle-factory.workspace = true
Expand Down
152 changes: 152 additions & 0 deletions cli/src/ascon_cmd.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
use std::io::{Read, Write};
use std::process::exit;
use std::{fs, io};

use bouncycastle::ascon::ascon_aead128::AsconAead128;
use bouncycastle::ascon::ascon_cxof128::AsconCXof128;
use bouncycastle::ascon::ascon_hash256::AsconHash256;
use bouncycastle::ascon::ascon_xof128::AsconXof128;
use bouncycastle::core::traits::{Hash, XOF};
use bouncycastle::hex;

/// Write `data` to stdout, either as hex or raw binary, followed by a newline.
fn emit(data: &[u8], output_hex: bool) {
if output_hex {
for b in data.iter() {
print!("{b:02x}");
}
} else {
io::stdout().write_all(data).unwrap();
}
println!();
}

/// Read all of stdin into a Vec.
fn read_stdin() -> Vec<u8> {
let mut data = Vec::new();
io::stdin().read_to_end(&mut data).expect("Failed to read from stdin");
data
}

/// Load a hex string or a binary file into bytes; exits with an error if neither is supplied.
fn load_bytes(value: &Option<String>, value_file: &Option<String>, label: &str) -> Vec<u8> {
if let Some(file) = value_file {
fs::read(file).unwrap_or_else(|e| {
eprintln!("Error: failed to read {label} file: {e}");
exit(-1)
})
} else if let Some(v) = value {
hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: {label} is not valid hex.");
exit(-1)
})
} else {
eprintln!("Error: {label} must be supplied.");
exit(-1)
}
}

fn require_16(bytes: Vec<u8>, label: &str) -> [u8; 16] {
bytes.try_into().unwrap_or_else(|_: Vec<u8>| {
eprintln!("Error: {label} must be exactly 16 bytes.");
exit(-1)
})
}

/// Ascon-Hash256 of stdin. Streaming update; 256-bit digest.
pub(crate) fn hash256_cmd(output_hex: bool) {
let mut h = AsconHash256::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
h.do_update(&buf[..bytes_read]);
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = h.do_final();
emit(&out, output_hex);
}

/// Ascon-XOF128 of stdin, producing `output_len` bytes. Streaming absorb.
pub(crate) fn xof128_cmd(output_len: usize, output_hex: bool) {
let mut x = AsconXof128::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-CXOF128 of stdin with a hex customization string, producing `output_len` bytes.
pub(crate) fn cxof128_cmd(customization: &Option<String>, output_len: usize, output_hex: bool) {
let z = match customization {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: customization is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let mut x = AsconCXof128::with_customization(&z);
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-AEAD128 of stdin. Encrypts (stdin = plaintext, output = ciphertext||tag) or, with
/// `decrypt`, decrypts (stdin = ciphertext||tag, output = plaintext). Decryption exits with a
/// non-zero status if the authentication tag does not verify.
#[allow(clippy::too_many_arguments)]
pub(crate) fn aead128_cmd(
key: &Option<String>,
key_file: &Option<String>,
nonce: &Option<String>,
nonce_file: &Option<String>,
ad: &Option<String>,
decrypt: bool,
output_hex: bool,
) {
let key = require_16(load_bytes(key, key_file, "key"), "key");
let nonce = require_16(load_bytes(nonce, nonce_file, "nonce"), "nonce");
let ad_bytes = match ad {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: associated data is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let ad_opt = if ad_bytes.is_empty() { None } else { Some(ad_bytes.as_slice()) };

let input = read_stdin();

if decrypt {
if input.len() < 16 {
eprintln!("Error: ciphertext is shorter than the 16-byte tag.");
exit(-1);
}
let mut out = vec![0u8; input.len() - 16];
match AsconAead128::decrypt(&key, &nonce, ad_opt, &input, &mut out) {
Ok(n) => {
out.truncate(n);
emit(&out, output_hex);
}
Err(_) => {
eprintln!("Error: Ascon-AEAD128 authentication failed.");
exit(-1);
}
}
} else {
let mut out = vec![0u8; input.len() + 16];
let n = AsconAead128::encrypt(&key, &nonce, ad_opt, &input, &mut out);
out.truncate(n);
emit(&out, output_hex);
}
}
83 changes: 83 additions & 0 deletions cli/src/main.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
mod ascon_cmd;
mod encoders_cmd;
mod helpers;
mod hkdf_cmd;
Expand DownExpand Up@@ -124,6 +125,76 @@ enum Subcommands {
x: bool,
},

/// Perform Ascon-Hash256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
AsconHash256 {
#[arg(short)]
/// Output the digest in hex format.
x: bool,
},

/// Perform Ascon-XOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconXOF128 {
/// Length of the output in bytes.
length: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform Ascon-CXOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconCXOF128 {
/// Length of the output in bytes.
length: usize,

/// Customization string in hex (optional).
#[arg(long)]
customization: Option<String>,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Ascon-AEAD128 authenticated encryption/decryption of the content provided on stdin.
/// Encrypts by default (stdin = plaintext, output = ciphertext||tag); with --decrypt the
/// reverse. Decryption fails with a non-zero exit status if the tag does not verify.
/// Note: in production uses, secrets should not be passed on the command-line because they get
/// logged in shell history. Use the file-based input instead.
AsconAEAD128 {
/// The 128-bit key in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<String>,

/// A file containing the 128-bit key in binary.
#[arg(long)]
key_file: Option<String>,

/// The 128-bit nonce in hex. Must be unique per encryption under a given key.
#[arg(long)]
nonce: Option<String>,

/// A file containing the 128-bit nonce in binary.
#[arg(long)]
nonce_file: Option<String>,

/// Associated data in hex (authenticated but not encrypted).
#[arg(long)]
ad: Option<String>,

/// Decrypt instead of encrypt.
#[arg(short, long)]
decrypt: bool,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform HMAC-SHA256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
/// Note: in production uses, secrets should not be passed on the command-line because they get
Expand DownExpand Up@@ -531,6 +602,18 @@ fn main() {
Some(Subcommands::SHAKE256 { length, x }) => {
sha3_cmd::shake_cmd(256, *length, *x);
}
Some(Subcommands::AsconHash256 { x }) => {
ascon_cmd::hash256_cmd(*x);
}
Some(Subcommands::AsconXOF128 { length, x }) => {
ascon_cmd::xof128_cmd(*length, *x);
}
Some(Subcommands::AsconCXOF128 { length, customization, x }) => {
ascon_cmd::cxof128_cmd(customization, *length, *x);
}
Some(Subcommands::AsconAEAD128 { key, key_file, nonce, nonce_file, ad, decrypt, x }) => {
ascon_cmd::aead128_cmd(key, key_file, nonce, nonce_file, ad, *decrypt, *x);
}
Some(Subcommands::HMAC_SHA256 { key, key_file, verify, x }) => {
mac_cmd::mac_cmd(HMACVariant::SHA256, key, key_file, verify, *x)
}
Expand Down
27 changes: 27 additions & 0 deletions crypto/ascon/Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
[package]
name = "bouncycastle-ascon"
version.workspace = true
edition.workspace = true

[features]
# `std` gates the ergonomic, allocating (`Vec`-returning) one-shot cipher APIs, mirroring the
# `std` feature of `bouncycastle-core`. On by default; a future `--no-default-features` build is
# what will let the crate move toward `#![no_std]`.
default = ["std"]
std = ["bouncycastle-core/std"]

[dependencies]
bouncycastle-core.workspace = true
bouncycastle-rng.workspace = true
bouncycastle-utils.workspace = true

[dev-dependencies]
bouncycastle-core-test-framework.workspace = true
bouncycastle-hex.workspace = true
bouncycastle-rng.workspace = true
criterion.workspace = true
serde_json = "1.0" # todo -- why?

[[bench]]
name = "ascon_benches"
harness = false
90 changes: 90 additions & 0 deletions crypto/ascon/benches/ascon_benches.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
use bouncycastle_rng as rng;
use criterion::{Criterion, Throughput, criterion_group, criterion_main};
use std::hint::black_box;

use bouncycastle_ascon::ascon_aead128::AsconAead128;
use bouncycastle_ascon::ascon_cxof128::AsconCXof128;
use bouncycastle_ascon::ascon_hash256::AsconHash256;
use bouncycastle_ascon::ascon_xof128::AsconXof128;
use bouncycastle_core::traits::{Hash, RNG, XOF};

const DATA_LEN: usize = 16 * 1024;

fn random_data(len: usize) -> Vec<u8> {
let mut data = vec![0u8; len];
rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap();
data
}

fn bench_aead128_encrypt(c: &mut Criterion) {
let key = [0x42u8; 16];
let nonce = [0x24u8; 16];
let data = random_data(DATA_LEN);
let mut out = vec![0u8; DATA_LEN + 16];

let mut group = c.benchmark_group("ascon::AsconAead128");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::encrypt()"), |b| {
b.iter(|| {
AsconAead128::encrypt(&key, &nonce, None, black_box(&data), &mut out);
black_box(&out);
})
});
group.finish();
}

fn bench_hash256(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut digest = [0u8; 32];

let mut group = c.benchmark_group("ascon::AsconHash256");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::hash_out()"), |b| {
b.iter(|| {
AsconHash256::new().hash_out(black_box(&data), &mut digest);
black_box(&digest);
})
});
group.finish();
}

fn bench_xof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconXof128::new().hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

fn bench_cxof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let customization = b"bench-customization";
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconCXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconCXof128::with_customization(customization)
.hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

criterion_group!(benches, bench_aead128_encrypt, bench_hash256, bench_xof128, bench_cxof128);
criterion_main!(benches);
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,3 +5,5 @@ mutants.out*/

.idea/
.vscode/

.claude/*
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ version = "0.1.3"

# *** Internal Dependencies ***
bouncycastle = { path = "./" }
bouncycastle-ascon = { path = "./crypto/ascon" }
bouncycastle-base64 = { path = "./crypto/base64" }
bouncycastle-core = { path = "crypto/core" }
bouncycastle-core-test-framework = { path = "./crypto/core-test-framework" }
Expand DownExpand Up@@ -41,6 +42,7 @@ version.workspace = true
edition.workspace = true

[dependencies]
bouncycastle-ascon.workspace = true
bouncycastle-base64.workspace = true
bouncycastle-core.workspace = true
bouncycastle-factory.workspace = true
Expand Down
152 changes: 152 additions & 0 deletions cli/src/ascon_cmd.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
use std::io::{Read, Write};
use std::process::exit;
use std::{fs, io};

use bouncycastle::ascon::ascon_aead128::AsconAead128;
use bouncycastle::ascon::ascon_cxof128::AsconCXof128;
use bouncycastle::ascon::ascon_hash256::AsconHash256;
use bouncycastle::ascon::ascon_xof128::AsconXof128;
use bouncycastle::core::traits::{Hash, XOF};
use bouncycastle::hex;

/// Write `data` to stdout, either as hex or raw binary, followed by a newline.
fn emit(data: &[u8], output_hex: bool) {
if output_hex {
for b in data.iter() {
print!("{b:02x}");
}
} else {
io::stdout().write_all(data).unwrap();
}
println!();
}

/// Read all of stdin into a Vec.
fn read_stdin() -> Vec<u8> {
let mut data = Vec::new();
io::stdin().read_to_end(&mut data).expect("Failed to read from stdin");
data
}

/// Load a hex string or a binary file into bytes; exits with an error if neither is supplied.
fn load_bytes(value: &Option<String>, value_file: &Option<String>, label: &str) -> Vec<u8> {
if let Some(file) = value_file {
fs::read(file).unwrap_or_else(|e| {
eprintln!("Error: failed to read {label} file: {e}");
exit(-1)
})
} else if let Some(v) = value {
hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: {label} is not valid hex.");
exit(-1)
})
} else {
eprintln!("Error: {label} must be supplied.");
exit(-1)
}
}

fn require_16(bytes: Vec<u8>, label: &str) -> [u8; 16] {
bytes.try_into().unwrap_or_else(|_: Vec<u8>| {
eprintln!("Error: {label} must be exactly 16 bytes.");
exit(-1)
})
}

/// Ascon-Hash256 of stdin. Streaming update; 256-bit digest.
pub(crate) fn hash256_cmd(output_hex: bool) {
let mut h = AsconHash256::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
h.do_update(&buf[..bytes_read]);
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = h.do_final();
emit(&out, output_hex);
}

/// Ascon-XOF128 of stdin, producing `output_len` bytes. Streaming absorb.
pub(crate) fn xof128_cmd(output_len: usize, output_hex: bool) {
let mut x = AsconXof128::new();
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-CXOF128 of stdin with a hex customization string, producing `output_len` bytes.
pub(crate) fn cxof128_cmd(customization: &Option<String>, output_len: usize, output_hex: bool) {
let z = match customization {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: customization is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let mut x = AsconCXof128::with_customization(&z);
let mut buf = [0u8; 1024];
let mut bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
while bytes_read != 0 {
// Absorb cannot fail here: we only absorb before any squeeze.
x.absorb(&buf[..bytes_read]).expect("absorb before squeeze is infallible");
bytes_read = io::stdin().read(&mut buf).expect("Failed to read from stdin");
}
let out = x.squeeze(output_len);
emit(&out, output_hex);
}

/// Ascon-AEAD128 of stdin. Encrypts (stdin = plaintext, output = ciphertext||tag) or, with
/// `decrypt`, decrypts (stdin = ciphertext||tag, output = plaintext). Decryption exits with a
/// non-zero status if the authentication tag does not verify.
#[allow(clippy::too_many_arguments)]
pub(crate) fn aead128_cmd(
key: &Option<String>,
key_file: &Option<String>,
nonce: &Option<String>,
nonce_file: &Option<String>,
ad: &Option<String>,
decrypt: bool,
output_hex: bool,
) {
let key = require_16(load_bytes(key, key_file, "key"), "key");
let nonce = require_16(load_bytes(nonce, nonce_file, "nonce"), "nonce");
let ad_bytes = match ad {
Some(v) => hex::decode(v).unwrap_or_else(|_| {
eprintln!("Error: associated data is not valid hex.");
exit(-1)
}),
None => Vec::new(),
};
let ad_opt = if ad_bytes.is_empty() { None } else { Some(ad_bytes.as_slice()) };

let input = read_stdin();

if decrypt {
if input.len() < 16 {
eprintln!("Error: ciphertext is shorter than the 16-byte tag.");
exit(-1);
}
let mut out = vec![0u8; input.len() - 16];
match AsconAead128::decrypt(&key, &nonce, ad_opt, &input, &mut out) {
Ok(n) => {
out.truncate(n);
emit(&out, output_hex);
}
Err(_) => {
eprintln!("Error: Ascon-AEAD128 authentication failed.");
exit(-1);
}
}
} else {
let mut out = vec![0u8; input.len() + 16];
let n = AsconAead128::encrypt(&key, &nonce, ad_opt, &input, &mut out);
out.truncate(n);
emit(&out, output_hex);
}
}
83 changes: 83 additions & 0 deletions cli/src/main.rs
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
mod ascon_cmd;
mod encoders_cmd;
mod helpers;
mod hkdf_cmd;
Expand DownExpand Up@@ -124,6 +125,76 @@ enum Subcommands {
x: bool,
},

/// Perform Ascon-Hash256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
AsconHash256 {
#[arg(short)]
/// Output the digest in hex format.
x: bool,
},

/// Perform Ascon-XOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconXOF128 {
/// Length of the output in bytes.
length: usize,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform Ascon-CXOF128 of the content provided on stdin. Requires the output length in bytes.
/// Supports streaming update for low memory footprint.
AsconCXOF128 {
/// Length of the output in bytes.
length: usize,

/// Customization string in hex (optional).
#[arg(long)]
customization: Option<String>,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Ascon-AEAD128 authenticated encryption/decryption of the content provided on stdin.
/// Encrypts by default (stdin = plaintext, output = ciphertext||tag); with --decrypt the
/// reverse. Decryption fails with a non-zero exit status if the tag does not verify.
/// Note: in production uses, secrets should not be passed on the command-line because they get
/// logged in shell history. Use the file-based input instead.
AsconAEAD128 {
/// The 128-bit key in hex.
/// The `key_file` option is preferred to avoid leaving key material in command history.
#[arg(long)]
key: Option<String>,

/// A file containing the 128-bit key in binary.
#[arg(long)]
key_file: Option<String>,

/// The 128-bit nonce in hex. Must be unique per encryption under a given key.
#[arg(long)]
nonce: Option<String>,

/// A file containing the 128-bit nonce in binary.
#[arg(long)]
nonce_file: Option<String>,

/// Associated data in hex (authenticated but not encrypted).
#[arg(long)]
ad: Option<String>,

/// Decrypt instead of encrypt.
#[arg(short, long)]
decrypt: bool,

#[arg(short)]
/// Output in hex format.
x: bool,
},

/// Perform HMAC-SHA256 of the content provided on stdin.
/// Supports streaming update for low memory footprint.
/// Note: in production uses, secrets should not be passed on the command-line because they get
Expand DownExpand Up@@ -531,6 +602,18 @@ fn main() {
Some(Subcommands::SHAKE256 { length, x }) => {
sha3_cmd::shake_cmd(256, *length, *x);
}
Some(Subcommands::AsconHash256 { x }) => {
ascon_cmd::hash256_cmd(*x);
}
Some(Subcommands::AsconXOF128 { length, x }) => {
ascon_cmd::xof128_cmd(*length, *x);
}
Some(Subcommands::AsconCXOF128 { length, customization, x }) => {
ascon_cmd::cxof128_cmd(customization, *length, *x);
}
Some(Subcommands::AsconAEAD128 { key, key_file, nonce, nonce_file, ad, decrypt, x }) => {
ascon_cmd::aead128_cmd(key, key_file, nonce, nonce_file, ad, *decrypt, *x);
}
Some(Subcommands::HMAC_SHA256 { key, key_file, verify, x }) => {
mac_cmd::mac_cmd(HMACVariant::SHA256, key, key_file, verify, *x)
}
Expand Down
27 changes: 27 additions & 0 deletions crypto/ascon/Cargo.toml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
[package]
name = "bouncycastle-ascon"
version.workspace = true
edition.workspace = true

[features]
# `std` gates the ergonomic, allocating (`Vec`-returning) one-shot cipher APIs, mirroring the
# `std` feature of `bouncycastle-core`. On by default; a future `--no-default-features` build is
# what will let the crate move toward `#![no_std]`.
default = ["std"]
std = ["bouncycastle-core/std"]

[dependencies]
bouncycastle-core.workspace = true
bouncycastle-rng.workspace = true
bouncycastle-utils.workspace = true

[dev-dependencies]
bouncycastle-core-test-framework.workspace = true
bouncycastle-hex.workspace = true
bouncycastle-rng.workspace = true
criterion.workspace = true
serde_json = "1.0" # todo -- why?

[[bench]]
name = "ascon_benches"
harness = false
90 changes: 90 additions & 0 deletions crypto/ascon/benches/ascon_benches.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
use bouncycastle_rng as rng;
use criterion::{Criterion, Throughput, criterion_group, criterion_main};
use std::hint::black_box;

use bouncycastle_ascon::ascon_aead128::AsconAead128;
use bouncycastle_ascon::ascon_cxof128::AsconCXof128;
use bouncycastle_ascon::ascon_hash256::AsconHash256;
use bouncycastle_ascon::ascon_xof128::AsconXof128;
use bouncycastle_core::traits::{Hash, RNG, XOF};

const DATA_LEN: usize = 16 * 1024;

fn random_data(len: usize) -> Vec<u8> {
let mut data = vec![0u8; len];
rng::DefaultRNG::default().next_bytes_out(&mut data).unwrap();
data
}

fn bench_aead128_encrypt(c: &mut Criterion) {
let key = [0x42u8; 16];
let nonce = [0x24u8; 16];
let data = random_data(DATA_LEN);
let mut out = vec![0u8; DATA_LEN + 16];

let mut group = c.benchmark_group("ascon::AsconAead128");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::encrypt()"), |b| {
b.iter(|| {
AsconAead128::encrypt(&key, &nonce, None, black_box(&data), &mut out);
black_box(&out);
})
});
group.finish();
}

fn bench_hash256(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut digest = [0u8; 32];

let mut group = c.benchmark_group("ascon::AsconHash256");
group.throughput(Throughput::Bytes(DATA_LEN as u64));
group.bench_function(format!("{DATA_LEN} bytes -- ::hash_out()"), |b| {
b.iter(|| {
AsconHash256::new().hash_out(black_box(&data), &mut digest);
black_box(&digest);
})
});
group.finish();
}

fn bench_xof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconXof128::new().hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

fn bench_cxof128(c: &mut Criterion) {
let data = random_data(DATA_LEN);
let customization = b"bench-customization";
let mut out = [0u8; 64];

let mut group = c.benchmark_group("ascon::AsconCXof128");
group.throughput(Throughput::Bytes((DATA_LEN + out.len()) as u64));
group.bench_function(
format!("input: {DATA_LEN} bytes, output: 64 bytes -- ::hash_xof_out()"),
|b| {
b.iter(|| {
AsconCXof128::with_customization(customization)
.hash_xof_out(black_box(&data), &mut out);
black_box(&out);
})
},
);
group.finish();
}

criterion_group!(benches, bench_aead128_encrypt, bench_hash256, bench_xof128, bench_cxof128);
criterion_main!(benches);
Loading
Loading