Rust openssl rsa OAEP Padding not working - rust

I am playing around with RSA encryption and I have just been using the standard PCKS1 padding which works fine, but I would like to use the more advanced OAEP or PSS Padding schemes. But for some reason when I switch the constant from PCKS1 to PKCS1_OAEP, it compiles but I get a run-time error. Which implies to me that the functionality is there but I am doing something wrong.
Here's my code
use openssl::{rsa::{Rsa, Padding}, symm::Cipher};
use bincode;
fn main() {
let rsa = Rsa::generate(512).unwrap();
let password = "password";
let source = "hello paul".to_string();
let data = bincode::serialize(&source).unwrap();
let private = rsa.private_key_to_pem_passphrase(Cipher::aes_128_cbc(), password.as_bytes()).unwrap();
//encrypt
let private_key = Rsa::private_key_from_pem_passphrase(&private, password.as_bytes()).unwrap();
let mut enc_data = vec![0; private_key.size() as usize];
match private_key.private_encrypt(&data, &mut enc_data, Padding::PKCS1_OAEP) {
Ok(_) => {},
Err(e) => {
println!("{e}");
return;
}
}
}
and my Cargo.toml dependencies
[dependencies]
openssl-sys = "0.9.79"
openssl = "0.10.44"
chrono = "0.4"
bincode = "1.0"
serde = { version = "1.0", features = ["derive"] }
and here is the error I am getting.
error:04066076:rsa routines:rsa_ossl_private_encrypt:unknown padding type:crypto/rsa/rsa_ossl.c:273:
So I am getting this from this resource(https://docs.rs/openssl/latest/openssl/rsa/struct.Padding.html#associatedconstant.PKCS1_OAEP)
I ahve also tried it with PKCS1_PSS and get the same error.
Does anyone know whats up, maybe they never actually finished OAEP or PSS, or is there something wrong on my end? Maybe I need to use a different Cipher than aes_128_cbc? Thanks for reading any help is appreciated.

Related

oxipng throwing RuntimeError: unreachable when called

I'm trying to create a small WASM project for image compression.
After some search in github, I noticed that oxipng 2.2.2 has a target for wasm32-unknown-unknown, hence why I'm using that.
I'm using wasm-pack for creating the wasm file + JS bindings with target -t web
This is the code:
extern crate oxipng;
mod utils;
use std::error::Error;
use wasm_bindgen::prelude::*;
use oxipng::*;
#[wasm_bindgen]
extern "C" {
// Use `js_namespace` here to bind `console.log(..)` instead of just
// `log(..)`
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
// Next let's define a macro that's like `println!`, only it works for
// `console.log`. Note that `println!` doesn't actually work on the wasm target
// because the standard library currently just eats all output. To get
// `println!`-like behavior in your app you'll likely want a macro like this.
#[macro_export]
macro_rules! console_log {
// Note that this is using the `log` function imported above during
// `bare_bones`
($($t:tt)*) => (crate::log(&format_args!($($t)*).to_string()))
}
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
pub fn compress(data: &[u8]) -> Vec<u8> {
console_log!("{}", data.len());
let opts = Options::from_preset(6);
console_log!("after options");
let res = match optimize_from_memory(data, &&opts) {
Ok(res) => Ok(res),
Err(err) => Err(err),
};
match &res {
Ok(_) => console_log!("Optimized"),
Err(err) => console_log!("Error: {}", err),
}
return res.unwrap();
}
I don't ever get an error message, the last log I have is "after options".
In a nutshell, I'm using a Flutter web application that gets a PNG file, converts it into a Uint8List, and I send it as an integer List to the JS bindings.
When called, the following error happens:
RuntimeError: unreachable
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[1019]:0x5c6be
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[414]:0x4cd37
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[619]:0x54c96
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[915]:0x5b4ba
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[986]:0x5c139
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[645]:0x55885
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[569]:0x5324b
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[594]:0x53ff1
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[2]:0x554f
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[84]:0x2cbf2
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[73]:0x2a501
at http://localhost:3000/pkg/rust_png_module_bg.wasm:wasm-function[563]:0x52eaa
at compress (http://localhost:3000/pkg/rust_png_module.js:49:14)
at compressImage (http://localhost:3000/packages/rust_wasm/ui/screens/home/home_page.dart.lib.js:568:72)
at compressImage.next (<anonymous>)
at http://localhost:3000/dart_sdk.js:38640:33
at _RootZone.runUnary (http://localhost:3000/dart_sdk.js:38511:59)
at _FutureListener.thenAwait.handleValue (http://localhost:3000/dart_sdk.js:33713:29)
at handleValueCallback (http://localhost:3000/dart_sdk.js:34265:49)
at Function._propagateToListeners (http://localhost:3000/dart_sdk.js:34303:17)
at _Future.new.[_completeWithValue] (http://localhost:3000/dart_sdk.js:34151:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:3000/dart_sdk.js:34172:35)
at Object._microtaskLoop (http://localhost:3000/dart_sdk.js:38778:13)
at _startMicrotaskLoop (http://localhost:3000/dart_sdk.js:38784:13)
at http://localhost:3000/dart_sdk.js:34519:9
Since this version is old, I don't know if I should revert back to an older version of Rust
$ rustup --version
rustup 1.24.3 (ce5817a94 2021-05-31)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.55.0 (c8dfcfe04 2021-09-06)`
Thank you in advance
The problem is you're using a very old version of oxipng (v2.2.2) that didn't support wasm yet. I believe wasm support was added in v2.3.0 (link to issue that was fixed). Anyways, you should be able to use the latest version just fine with wasm, just make sure you disable the default features when adding the crate to your Cargo.toml:
[dependencies]
oxipng = { version = "5", default-features = false }

fltk: failed to resolve GlutWindow

I'm trying to follow example of fltk application which uses openGl, but the build is not functioning:
let app = app::App::default();
let mut win = window::GlutWindow::default().with_size(800, 600);
win.set_mode(enums::Mode::Opengl3);
win.end();
win.show();
unsafe {
let gl = glow::Context::from_loader_function(|s| {
win.get_proc_address(s) as *const _
});
I get: failed to resolve: could not find GlutWindow in window.
I'm using fltk version 1
Thank you
p.s. I'm using Rust
Check your imports which are missing from that snippet.
Also if you’re not enabling the enable-glwindow feature, you should, try changing your Cargo.toml to include the missing feature:
[dependencies]
fltk = { version = "1", features = ["enable-glwindow"] }

Rust: Thread panics when run inside an iframe but not in a regular browser tab

I'm playing around with building an app on Zendesk using Rust. Below is a server-side rust function that gets called in a route
pub fn oktaredirectprocessor(mut cookies: Cookies, code: String, state: String) -> bool {
let cookie_state_string = cookies.get_private("state").unwrap().value().to_string();
println!("cookie retrieved in oktaredirectprocessor is {}", cookie_state_string);
if state != cookie_state_string {
debug!("State did not match");
false
}else if code == ""{
debug!("Code is empty");
false
}else{
let oktarequest: Oktarequest = Oktarequest::new();
let http = reqwest::Client::new();
let config = oidc::discovery::discover(&http, oktarequest.issuer).expect("error in config-discovery-oidc");
let jwks = oidc::discovery::jwks(&http, config.jwks_uri.clone()).expect("error in jwks-discovery-oidc");
let provider = oidc::discovery::Discovered(config);
let client = oidc::Client::new(oktarequest.id, oktarequest.secret, oktarequest.redirect, provider, jwks);
let mut token = client.request_token(&http, code.as_str()).expect("error in request token-oidc");
client.decode_token(&mut token.id_token).expect("error in decode token oidc");
client.validate_token(&token.id_token, Some(cookies.get_private("nonce").unwrap().value()), None).expect("error in validate token oidc"); cookies.add_private(Cookie::new("access_token", token.access_token().to_string()));
true
}
}
It works when I run localhost directly from a browser tab. However, the thread panics if I run the app from inside Zendesk. Below is the backtrace. I'm a novice coder and don't understand it entirely.
thread '<unnamed>' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:214:60
stack backtrace:
0: rust_begin_unwind
at /rustc/7efc097c4fe6e97f54a44cee91c56189e9ddb41c/library/std/src/panicking.rs:493:5
1: core::panicking::panic_fmt
at /rustc/7efc097c4fe6e97f54a44cee91c56189e9ddb41c/library/core/src/panicking.rs:92:14
2: core::panicking::panic
at /rustc/7efc097c4fe6e97f54a44cee91c56189e9ddb41c/library/core/src/panicking.rs:50:5
3: core::option::Option<T>::unwrap
at /rustc/7efc097c4fe6e97f54a44cee91c56189e9ddb41c/library/core/src/option.rs:386:21
4: app_remote::oktaredirecthandler
at ./src/main.rs:214:28
5: app_remote::rocket_route_fn_oktaredirecthandler
at ./src/main.rs:213:4
6: core::ops::function::Fn::call
at /rustc/7efc097c4fe6e97f54a44cee91c56189e9ddb41c/library/core/src/ops/function.rs:70:5
7: <F as rocket::handler::Handler>::handle
at /Users/nalinnarayan/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.5/src/handler.rs:177:9
8: rocket::rocket::Rocket::route
at /Users/nalinnarayan/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.5/src/rocket.rs:296:27
9: rocket::rocket::Rocket::route_and_process
at /Users/nalinnarayan/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.5/src/rocket.rs:242:34
10: rocket::rocket::Rocket::dispatch
at /Users/nalinnarayan/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.5/src/rocket.rs:217:28
11: <rocket::rocket::Rocket as hyper::server::Handler>::handle
at /Users/nalinnarayan/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.5/src/rocket.rs:82:24
12: hyper::server::Worker<H>::keep_alive_loop
at /Users/nalinnarayan/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.10.16/src/server/mod.rs:340:13
13: hyper::server::Worker<H>::handle_connection
at /Users/nalinnarayan/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.10.16/src/server/mod.rs:282:15
14: hyper::server::handle::{{closure}}
at /Users/nalinnarayan/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.10.16/src/server/mod.rs:242:34
15: hyper::server::listener::spawn_with::{{closure}}
at /Users/nalinnarayan/.cargo/registry/src/github.com-1ecc6299db9ec823/hyper-0.10.16/src/server/listener.rs:50:31
Weirdly, the problematic "cookies.get_private("state").unwrap()" works in another function even when run inside Zendesk. Below is the function where it works
fn oktalogin(mut cookies: Cookies) -> Redirect {
let oktarequest: Oktarequest = Oktarequest::new();
cookies.add_private(Cookie::new("state", oktarequest.state.clone()));
cookies.add_private(Cookie::new("nonce", oktarequest.nonce.clone()));
println!("stored state cookie from random gen is: {}", cookies.get_private("state").unwrap().value().to_string());
let http = reqwest::Client::new();
let config = oidc::discovery::discover(&http, oktarequest.issuer).expect("error in config-discovery-oidc");
let jwks = oidc::discovery::jwks(&http, config.jwks_uri.clone()).expect("error in jwks-discovery-oidc");
let provider = oidc::discovery::Discovered(config);
let client = oidc::Client::new(oktarequest.id, oktarequest.secret, oktarequest.redirect, provider, jwks);
let options = Options{
scope: Some("openid profile email".to_string()),
state: Some(oktarequest.state.clone()),
nonce: Some(oktarequest.nonce.clone()),
..Default::default()
};
let auth_url = client.auth_url(&options);
Redirect::to(auth_url.into_string())
}
My cargo.toml
[dependencies]
rocket = { version = "0.4.5", features = ["private-cookies"] }
rocket_codegen = "0.4.5"
serde = "1.0.116"
serde_derive = "1.0.116"
diesel = { version = "1.4.5", features = ["postgres"] }
dotenv = "0.15.0"
serde_urlencoded = "0.7.0"
oidc = "0.3.0"
ring = "=0.16.15"
log = "0.4.8"
rand = "0.7.3"
reqwest = "=0.9.24"
inth-oauth2 = "0.16.0"
url = "=1.7.2"
serde_json = "1.0"
console_log = { version = "0.2", features = ["color"] }
[dependencies.rocket_contrib]
version = "*"
default-features = false
features = ["tera_templates", "json"]
Why it worked in localhost was that cookie remained. To work correctly needs to add code when cookie doesn't exist, without unwrap().
let cookie_state_string = match cookies.get_private("state") {
Ok(v) => v.value().to_string(),
Err(_) => return false,
};

Why do I get the error "there is no reactor running, must be called from the context of Tokio runtime" even though I have #[tokio::main]?

I'm following the mdns Rust documentation and pasted the example code but it throws the following error:
thread 'main' panicked at 'there is no reactor running, must be called from the context of Tokio runtime'
Here's the code that I have:
use futures_util::{pin_mut, stream::StreamExt};
use mdns::{Error, Record, RecordKind};
use std::{net::IpAddr, time::Duration};
const SERVICE_NAME: &'static str = "_googlecast._tcp.local";
#[tokio::main]
async fn main() -> Result<(), Error> {
// Iterate through responses from each Cast device, asking for new devices every 15s
let stream = mdns::discover::all(SERVICE_NAME, Duration::from_secs(15))?.listen();
pin_mut!(stream);
while let Some(Ok(response)) = stream.next().await {
let addr = response.records().filter_map(self::to_ip_addr).next();
if let Some(addr) = addr {
println!("found cast device at {}", addr);
} else {
println!("cast device does not advertise address");
}
}
Ok(())
}
fn to_ip_addr(record: &Record) -> Option<IpAddr> {
match record.kind {
RecordKind::A(addr) => Some(addr.into()),
RecordKind::AAAA(addr) => Some(addr.into()),
_ => None,
}
}
Dependencies:
[dependencies]
mdns = "1.1.0"
futures-util = "0.3.8"
tokio = { version = "0.3.3", features = ["full"] }
What am I missing? I tried looking online but haven't found how to create a reactor for this use case.
You are using a newer version of Tokio, such as 0.3 or 1.x, and many packages, including mdns 1.1.0, rely on an older version of Tokio, such as 0.2.
% cargo tree -d
tokio v0.2.22
└── mdns v1.1.0
└── example_project v0.1.0
tokio v0.3.3
└── example_project v0.1.0
For now, you will need to match versions of the Tokio runtime. The easiest way is to use Tokio 0.2 yourself. The tokio-compat-02 crate may also be useful in some cases.
See also:
Why is a trait not implemented for a type that clearly has it implemented?
Various error messages with the same root cause:
there is no reactor running, must be called from the context of a Tokio 1.x runtime
there is no reactor running, must be called from the context of Tokio runtime
not currently running on the Tokio runtime
Fix for me was adding this to Cargo.toml:
[dependencies]
async-std = { version = "1", features = ["attributes", "tokio1"] }
https://github.com/ATiltedTree/ytextract/issues/25
At the time of writing, a fair amount of crates are already using Tokio v1, but others might still be under an experimental phase. Check your crates for prerelease versions which might have already upgraded their tokio runtime compatibility.
A relevant example of this was actix-web, which uses runtime 1.0 of Tokio since version 4. Although there were prereleases of this major increment since 2022-01-07, version 4.0.0 was only released in 2022-02-25.
actix-web = { version = "4.0.0-beta.10" }

Serve on multiple ports(http,https) simultaneously using warp framework in Rust

I want to serve multiple connections using warp so that I can redirect every http request to https. Here is what I am up to right now.
#[tokio::main]
async fn main() {
let http_routes = warp::path("http").map(|| {
println!("This is http server");
warp::redirect(Uri::from_static("https://127.0.0.1:2443"))
});
let https_routes = warp::any().map(|| {
println!("This is https server");
"Hello, World! You are connected through tls connection."
});
let _http_warp = warp::serve(http_routes)
.run(([127, 0, 0, 1], 2080)).await;
let _https_warp = warp::serve(https_routes)
.tls()
.cert_path("sec/dmp.cert")
.key_path("sec/dmp.key")
.run(([127, 0, 0, 1], 2443)).await;
}
This does not work as expected. It only listens on port 2080 and not on 2443
I also tried future::join
#[tokio::main]
async fn main() {
----snip----
let (_http_addr, http_warp) = warp::serve(http_routes)
.bind_ephemeral(([127, 0, 0, 1], 2080));
let (_https_addr, https_warp) = warp::serve(https_routes)
.tls()
.cert_path("sec/dmp.cert")
.key_path("sec/dmp.key")
.bind_ephemeral(([127, 0, 0, 1], 2443));
future::join(http_warp, https_warp).await?
}
This gives error
error[E0277]: the `?` operator can only be applied to values that implement `std::ops::Try`
--> src/main.rs:27:5
|
27 | future::join(http_wrap, https_wrap).await?
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the `?` operator cannot be applied to type `((), ())`
|
= help: the trait `std::ops::Try` is not implemented for `((), ())`
= note: required by `std::ops::Try::into_result`
Its completely a simple thing to make this run and that is removing ? suffix from await statement at the end and placing a semicolon.
future::join(http_wrap, https_wrap).await? // FROM THIS
future::join(http_wrap, https_wrap).await; // TO THIS
And that's it. Now both the futures run simultaneously and thus it listens on both the ports.
here's kanudo's solution as a complete working example of a tls https redirect in warp
cert.pem
-----BEGIN CERTIFICATE-----
MIIEADCCAmigAwIBAgICAcgwDQYJKoZIhvcNAQELBQAwLDEqMCgGA1UEAwwhcG9u
eXRvd24gUlNBIGxldmVsIDIgaW50ZXJtZWRpYXRlMB4XDTE2MDgxMzE2MDcwNFoX
DTIyMDIwMzE2MDcwNFowGTEXMBUGA1UEAwwOdGVzdHNlcnZlci5jb20wggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpVhh1/FNP2qvWenbZSghari/UThwe
dynfnHG7gc3Jmygk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AHBDdC3OgppUN4
CFj55kzc2HUuiHtmPtx8mK6G+otT7Lww+nLSFL4PvZ6CYxqcio5MPnoYd+pCxrXY
JFo2W7e4FkBOxb5PF5So5plg+d0z/QiA7aFP1osCgYEAtgi1rwC5qkm8prn4tFm6
hkcVCIXc+IWNS0Bu693bXKdGr7RsmIynff1zpf4ntYGpEMaeymClCY0ppDrMYlzU
RBYiFNdlBvDRj6s/H+FTzHRk2DT/99rAhY9nzVY0OQFoQIXK8jlURGrkmI/CYy66
XqBmo5t4zcHM7kaeEBOWEKkCgYAYnO6VaRtPNQfYwhhoFFAcUc+5t+AVeHGW/4AY
M5qlAlIBu64JaQSI5KqwS0T4H+ZgG6Gti68FKPO+DhaYQ9kZdtam23pRVhd7J8y+
xMI3h1kiaBqZWVxZ6QkNFzizbui/2mtn0/JB6YQ/zxwHwcpqx0tHG8Qtm5ZAV7PB
eLCYhQKBgQDALJxU/6hMTdytEU5CLOBSMby45YD/RrfQrl2gl/vA0etPrto4RkVq
UrkDO/9W4mZORClN3knxEFSTlYi8YOboxdlynpFfhcs82wFChs+Ydp1eEsVHAqtu
T+uzn0sroycBiBfVB949LExnzGDFUkhG0i2c2InarQYLTsIyHCIDEA==
-----END RSA PRIVATE KEY-----
Cargo.toml
[dependencies]
tokio = { version = "0.2", features = ["full"] }
warp = { version = "0.2", features = ["tls"] }
futures = "0.3.8"
main.rs
use warp::hyper::Uri;
use warp::Filter;
use futures::future;
#[tokio::main]
async fn main() {
let http_routes = warp::path("http").map(|| {
println!("This is http server");
warp::redirect(Uri::from_static("https://127.0.0.1:2443"))
});
let https_routes = warp::any().map(|| {
println!("This is https server");
"Hello, World! You are connected through tls connection."
});
let (_http_addr, http_warp) = warp::serve(http_routes)
.bind_ephemeral(([127, 0, 0, 1], 2080));
let (_https_addr, https_warp) = warp::serve(https_routes)
.tls()
.cert_path("examples/tls/cert.pem")
.key_path("examples/tls/key.rsa")
.bind_ephemeral(([127, 0, 0, 1], 2443));
future::join(http_warp, https_warp).await;
}
http://localhost:2080/http redirects to: https://127.0.0.1:2443/
Hello, World! You are connected through tls connection.

Resources