test RSA encrypt/decrypt

This commit is contained in:
Evan Feenstra
2022-06-29 11:03:31 -07:00
parent 3def3a2439
commit e28c83fcb8
3 changed files with 43 additions and 0 deletions

View File

@@ -31,6 +31,9 @@ url = "2"
serde_urlencoded = "0.7.1"
serde = { version = "1.0.137", default-features = false }
serde_json = { version = "1.0.81", default-features = false }
rsa = "0.7.0-pre"
rand = "0.8"
hex = "0.4.3"
[patch.crates-io]
# updates the "rand" create to use esp RNG

View File

@@ -7,6 +7,9 @@ use std::sync::{Condvar, Mutex, Arc};
use embedded_svc::httpd::registry::Registry;
use serde::Deserialize;
use rsa::{PublicKey, RsaPrivateKey, RsaPublicKey, PaddingScheme};
use rsa::pkcs8::EncodePublicKey;
#[derive(Clone, Debug, Deserialize)]
pub struct Params {
pub config: String
@@ -15,9 +18,18 @@ pub struct Params {
#[allow(unused_variables)]
pub fn config_server(mutex: Arc<(Mutex<Option<Config>>, Condvar)>) -> Result<idf::Server> {
let mut rng = rand::thread_rng();
let bits = 2048;
let priv_key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
let pub_key = RsaPublicKey::from(&priv_key);
let der = pub_key.to_public_key_der().expect("could not encode DER");
let hexder = der.into_vec();
let server = idf::ServerRegistry::new()
.at("/")
.get(|_| Ok(html::HTML.into()))?
.at("/pubkey")
.get(move |_| Ok(hex::encode(hexder.clone()).into()))?
.at("/config")
.post(move |request| {
let bod = &request.query_string()

View File

@@ -34,6 +34,8 @@ fn main() -> Result<()> {
// or else some patches to the runtime implemented by esp-idf-sys might not link properly.
esp_idf_sys::link_patches();
test_rsa();
let network: Network = if let Some(n) = NETWORK {
match n {
"bitcoin" => Network::Bitcoin,
@@ -96,3 +98,29 @@ fn main() -> Result<()> {
Ok(())
}
fn test_rsa() {
std::thread::spawn(move || {
println!("TEST RSA");
use rsa::{PublicKey, RsaPrivateKey, RsaPublicKey, PaddingScheme};
let mut rng = rand::thread_rng();
println!("TEST RSA1");
let bits = 1024;
println!("TEST RSA2");
let priv_key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
println!("TEST RSA3");
let pub_key = RsaPublicKey::from(&priv_key);
println!("TEST RSA4");
// Encrypt
let data = b"hello world";
println!("TEST RSA5");
let enc_data = pub_key.encrypt(&mut rng, PaddingScheme::new_pkcs1v15_encrypt(), &data[..]).expect("failed to encrypt");
assert_ne!(&data[..], &enc_data[..]);
println!("TEST RSA6");
// Decrypt
let dec_data = priv_key.decrypt(PaddingScheme::new_pkcs1v15_encrypt(), &enc_data).expect("failed to decrypt");
println!("TEST RSA7");
assert_eq!(&data[..], &dec_data[..]);
});
}