2018-04-29 17:40:10 +02:00
|
|
|
use base64;
|
2018-05-03 19:12:01 +02:00
|
|
|
use diesel::PgConnection;
|
2018-04-29 17:40:10 +02:00
|
|
|
use hex;
|
|
|
|
use chrono::Utc;
|
2018-04-29 20:06:10 +02:00
|
|
|
use openssl::sha::sha256;
|
2018-04-29 17:40:10 +02:00
|
|
|
use serde_json;
|
|
|
|
|
|
|
|
pub trait Signer {
|
2018-05-03 19:12:01 +02:00
|
|
|
fn get_key_id(&self, conn: &PgConnection) -> String;
|
2018-04-29 17:40:10 +02:00
|
|
|
|
|
|
|
/// Sign some data with the signer keypair
|
2018-05-03 19:12:01 +02:00
|
|
|
fn sign(&self, to_sign: String) -> Vec<u8>;
|
2018-04-29 17:40:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
pub trait Signable {
|
2018-05-03 19:12:01 +02:00
|
|
|
fn sign<T>(&mut self, creator: T, conn: &PgConnection) -> &mut Self where T: Signer;
|
2018-04-29 17:40:10 +02:00
|
|
|
|
|
|
|
fn hash(data: String) -> String {
|
|
|
|
let bytes = data.into_bytes();
|
|
|
|
hex::encode(sha256(&bytes[..]))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Signable for serde_json::Value {
|
2018-05-03 19:12:01 +02:00
|
|
|
fn sign<T: Signer>(&mut self, creator: T, conn: &PgConnection) -> &mut serde_json::Value {
|
|
|
|
let creation_date = Utc::now().to_rfc3339();
|
2018-04-29 17:40:10 +02:00
|
|
|
let mut options = json!({
|
|
|
|
"type": "RsaSignature2017",
|
2018-05-03 19:12:01 +02:00
|
|
|
"creator": creator.get_key_id(conn),
|
|
|
|
"created": creation_date
|
2018-04-29 17:40:10 +02:00
|
|
|
});
|
|
|
|
|
2018-05-03 19:12:01 +02:00
|
|
|
let options_hash = Self::hash(json!({
|
|
|
|
"@context": "https://w3id.org/identity/v1",
|
|
|
|
"created": creation_date
|
|
|
|
}).to_string());
|
2018-04-29 17:40:10 +02:00
|
|
|
let document_hash = Self::hash(self.to_string());
|
|
|
|
let to_be_signed = options_hash + &document_hash;
|
|
|
|
|
|
|
|
let signature = base64::encode(&creator.sign(to_be_signed));
|
|
|
|
|
|
|
|
options["signaureValue"] = serde_json::Value::String(signature);
|
|
|
|
self["signature"] = options;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|