This commit is contained in:
Fritz Schmid 2022-06-15 13:24:45 +02:00
commit 73dd812daa

159
src/ophe.rs Normal file
View File

@ -0,0 +1,159 @@
#[macro_use] extern crate rocket;
extern crate bls12_381;
extern crate rand;
use rocket_okapi::settings::UrlObject;
use rocket_okapi::{openapi, openapi_get_routes, rapidoc::*, swagger_ui::*};
use rocket::serde::json::Json;
use rocket::Request;
use ophe::core::{RatelimiterResponse,PublicParameters};
use ophe::core;
use rocket::State;
use serde::{Deserialize, Serialize};
use rocket_okapi::okapi::schemars;
use rocket_okapi::okapi::schemars::JsonSchema;
use bls12_381::Scalar;
use bls12_381::Gt;
use ophe::serializers;
use serde_with::serde_as;
use rocket::http::Status;
#[rocket::main]
async fn main() {
let client = reqwest::Client::new();
let res = client.get("http://localhost:9999/get_public_parameters").send()
.await.map_err(|x|{format!("Cryptoservice not reachable: {}",x)}).unwrap().text().await.unwrap();
let pp: PublicParameters = serde_json::from_str(&res).map_err(|x|{format!("Cryptoservice not reachable: {}",x)}).unwrap();
println!("Received public parameters from crytoservice");
let launch_result = rocket::build().mount("/", openapi_get_routes![make_request,decrypt])
.manage(pp)
.mount(
"/swagger-ui/",
make_swagger_ui(&SwaggerUIConfig {
url: "../openapi.json".to_owned(),
..Default::default()
}),
) .mount(
"/rapidoc/",
make_rapidoc(&RapiDocConfig {
general: GeneralConfig {
spec_urls: vec![UrlObject::new("General", "../openapi.json")],
..Default::default()
},
hide_show: HideShowConfig {
allow_spec_url_load: false,
allow_spec_file_load: false,
..Default::default()
},
..Default::default()
}),
)
.register("/",catchers![serialize_failed])
.launch()
.await;
match launch_result {
Ok(_) => println!("Rocket shut down gracefully."),
Err(err) => println!("Rocket had an error: {}", err),
};
}
#[derive(Serialize,Deserialize,JsonSchema)]
struct UsernamePw{
username: String,
password: String
}
#[catch(422)]
fn serialize_failed(_req: &Request) -> String {
format!("Malformed Request")
}
#[serde_as]
#[derive(Serialize, Deserialize, JsonSchema)]
pub struct EnrollResponse{
#[serde_as(as = "serializers::SerializeScalar")]
#[schemars(with = "String")]
n: Scalar,
#[serde_as(as = "Vec<serializers::SerializeGt>")]
#[schemars(with = "Vec<String>")]
ciphertext: Vec<Gt>
}
#[openapi()]
#[post("/make_request",format = "json", data = "<request>")]
async fn make_request(request: Json<UsernamePw>,pp: &State<core::PublicParameters>) -> Result<Json<EnrollResponse>,(Status, Json<String>)> {
let (ss,request1) = core::phe_init(&request.username,&request.password);
let client = reqwest::Client::new();
let res = client.post("http://localhost:9999/phe_help")
.json(&request1)
.send()
.await.map_err(|_x| {(Status::InternalServerError,Json("Cryptoserice unreachable.".to_string()))})?.text().await.map_err(|_x| {(Status::InternalServerError,Json("Cryptoserice unreachable.".to_string()))})?;
let response: RatelimiterResponse = serde_json::from_str(&res).map_err(|_x| {(Status::InternalServerError,Json("Invalid cryptoservice response.".to_string()))})?;
let mut msg = Vec::new();
for _x in 0..32{
msg.push(0u8);
}
let ciphertext = core::phe_enc_finish(&msg,&pp,&response,&ss).map_err(|x| {(Status::InternalServerError,Json("Decryption failed.".to_string()+&x))})?;
Ok(Json(EnrollResponse{n:ss.n,ciphertext}))
}
#[serde_as]
#[derive(Serialize, Deserialize, JsonSchema)]
pub struct DecryptRequest{
#[serde_as(as = "serializers::SerializeScalar")]
#[schemars(with = "String")]
n: Scalar,
username: String,
password: String,
#[serde_as(as = "Vec<serializers::SerializeGt>")]
#[schemars(with = "Vec<String>")]
ciphertext: Vec<Gt>
}
#[openapi()]
#[post("/decrypt",format = "json", data = "<request>")]
async fn decrypt(request: Json<DecryptRequest>,pp: &State<core::PublicParameters>) -> Result<Json<bool>,(Status, Json<String>)>{
let res = decrypt_err(request,pp).await;
res
}
async fn decrypt_err(request: Json<DecryptRequest>,pp: &State<core::PublicParameters>) -> Result<Json<bool>,(Status, Json<String>)> {
let (ss,request1) = core::phe_init_decrypt(&request.username,&request.password,&request.n);
let client = reqwest::Client::new();
let res = client.post("http://localhost:9999/phe_help")
.json(&request1)
.send()
.await.map_err(|_x| {(Status::InternalServerError,Json("Cryptoserice unreachable.".to_string()))})?.text().await.map_err(|_x| {(Status::InternalServerError,Json("Internal Error.".to_string()))})?;
let response: RatelimiterResponse = serde_json::from_str(&res).map_err(|_x| {(Status::InternalServerError,Json("Invalid cryptoservice response.".to_string()))})?;
let mut msg = Vec::new();
for _x in 0..32{
msg.push(0u8);
}
let expected = core::phe_dec_finish_simple(&request.ciphertext,&pp,&response,&ss).map_err(|x| {(Status::InternalServerError,Json("Decryption failed.".to_string()+&x))})?;
println!("{:?}",expected);
Ok(Json(true))
}