core_crypto/
utils.rs

1// Copyright 2021 BlockPuppets developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use rand::RngCore;
10use regex::Regex;
11
12pub fn is_hex(input: &str) -> bool {
13    if input == "" {
14        return false;
15    }
16
17    let re = Regex::new(r"^[a-fA-F0-9]+$").unwrap();
18    re.is_match(input)
19}
20
21/// Decodes a hex string into raw bytes.
22///
23pub fn hex_to_vec(data: &str) -> Vec<u8> {
24    hex::decode(data)
25        .map_err(|err| panic!("Failed to decode hex data {} : {}", data, err))
26        .unwrap()
27}
28
29pub fn random_bytes<const COUNT: usize>() -> [u8; COUNT] {
30    let mut rng = rand::thread_rng();
31    let mut buf = [0u8; COUNT];
32    rng.try_fill_bytes(&mut buf).unwrap();
33    buf
34}