aboutsummaryrefslogtreecommitdiff
path: root/src/security/utils.rs
diff options
context:
space:
mode:
authorKatharina Fey <kookie@spacekookie.de>2018-04-02 13:53:30 +0200
committerKatharina Fey <kookie@spacekookie.de>2018-04-02 13:53:30 +0200
commitc789005d19660f9f56b6eab7090a58758b5c7a07 (patch)
treeb2d5b8290486350c432bbaee7f6b72f982bbaf72 /src/security/utils.rs
parent5fe943efec2f7c0210d9b12767876ef3a251dfac (diff)
Refactoring utilities in security module. Definine basic library crate
Diffstat (limited to '')
-rw-r--r--src/security/utils.rs90
1 files changed, 90 insertions, 0 deletions
diff --git a/src/security/utils.rs b/src/security/utils.rs
new file mode 100644
index 0000000..7b38674
--- /dev/null
+++ b/src/security/utils.rs
@@ -0,0 +1,90 @@
+//! A collection of utility submodules
+//!
+//!
+
+/// Encoding module
+pub mod Encoding {
+ use base64;
+ use std::fmt::Write;
+
+ /// Encode a piece of arbitary data into a bse64 string
+ pub fn base64_encode(data: &Vec<u8>) -> String {
+ return base64::encode(data);
+ }
+
+ /// Decode a base64 string into arbitrary data
+ pub fn base64_decode(data: &String) -> Vec<u8> {
+ return base64::decode(data).unwrap();
+ }
+
+ /// Simply encode a byte-string as hexadecimal symbols
+ pub fn encode_hex(data: &str) -> String {
+ let mut s = String::new();
+ for &byte in data.as_bytes() {
+ write!(&mut s, "{:X}", byte).expect("Unable to HEX encode!");
+ }
+
+ return s;
+ }
+}
+
+/// A hashing utility module
+pub mod Hashing {
+ use blake2::Blake2s;
+ use blake2::digest::{Input, VariableOutput};
+
+ const BLAKE_16_LENGTH: usize = 16;
+
+ /// Hash a value with blake2
+ pub fn blake2(data: &str, salt: &str) -> [u8; BLAKE_16_LENGTH] {
+ let mut hasher = match Blake2s::new(BLAKE_16_LENGTH) {
+ Ok(res) => res,
+ Err(some) => panic!(some),
+ };
+
+ let to_hash = format!("{}{}", data, salt);
+ hasher.process(to_hash.as_bytes());
+
+ let mut buffer = [0u8; BLAKE_16_LENGTH];
+ match hasher.variable_result(&mut buffer) {
+ Ok(res) => res,
+ Err(e) => panic!(e),
+ };
+
+ return buffer;
+ }
+}
+
+/// Random number utility module for lockchain
+///
+/// Provides stateless secure random number and byte generation
+pub mod Random {
+ use rand::{thread_rng, Rng};
+
+ /// Generate a random number with an upper bound
+ pub fn number(bound: u64) -> u64 {
+ return thread_rng().next_u64() % bound;
+ }
+
+ /// Generate a sequence of random bytes that are returned
+ /// as a vector.
+ ///
+ /// Can at most allocate 2048 bytes at a time
+ /// FIXME: That shouldn't have a limit!
+ pub fn bytes(length: usize) -> Vec<u8> {
+ let mut vec: Vec<u8> = Vec::new();
+
+ if length > 2048 {
+ return vec;
+ }
+
+ let mut random_data = [0u8; 2048];
+ thread_rng().fill_bytes(&mut random_data);
+
+ for i in 0..length {
+ vec.push(random_data[i]);
+ }
+
+ return vec;
+ }
+}