Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JWT VC support for RSA keys; enable ZKP tests #24

Merged
merged 4 commits into from
Aug 28, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ serde_json = "1.0"
pest = "2.1"
pest_derive = "2.1"
derive_builder = "0.9"
base64 = "0.12"
jsonwebtoken = "7"
19 changes: 17 additions & 2 deletions src/bin/ssi-vc-test/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,22 @@
"presentationGenerator": "../ssi/target/debug/ssi-vc-test generate-presentation",
"generatorOptions": "",
"sectionsNotSupported": [
"jwt",
"zkp"
]
],
"jwt": {
"rs256PrivateKeyJwk": {
"kty": "RSA",
"n": "ALG1_NjU1eiMpcQoezH1eIZcr2p4gmo7j_exsjqkr05qBHQTn5Rb2dOpEf_Q-nLbeORZOobJH52oNhhuvTQC1R9qOEQkerUIi0aSnDEbQ2BP7YRJnwbw85v1VZDiGH8bviKbqPSf0uVwzQ43M8dr_t6A4efgiB5FOOobxXgr6VEvi_EyUm4F9JI1ZP5uHiG_cIet67Zg-lM_ygbQqOZpkeExLXC2SmHajKd8Aozfk5YB4s_-KFV1mx1HnwhHvKxZ19YkJ6Qx1OPf0ml0KLndYwmnsRZ9uZ_gGvH_G3OVZvuUnkcInR2uhK7xIU739Xc-hqDT6dokb5vsCdYMcFiRGD0=",
"e": "AQAB",
"d": "Eym3sT4KLwBzo5pl5nY83-hAti92iLQRizkrKe22RbNi9Y1kKOBatdtGaJqFVztZZu5ERGKNuTd5VdsjJeekSbXviVGRtdHNCvgmRZlWA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-scrHAuACE567YQ4VurpNorPKtZ5UENXIn74DEmt4l5m6902VF3X5Wo=",
"alg": "RS256",
"kid": "rsa2048-2020-08-25"
},
"aud": "did:example:0xcafe"
}
}
144 changes: 108 additions & 36 deletions src/bin/ssi-vc-test/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use ssi::jwk::JWTKeys;
use ssi::vc::Contexts;
use ssi::vc::Credential;
use ssi::vc::Presentation;
Expand All @@ -11,6 +12,12 @@ fn generate(data: String) -> String {
if !doc.type_.contains(&"VerifiableCredential".to_string()) {
panic!("Missing type VerifiableCredential");
}
if doc.issuer.is_none() {
panic!("Missing issuer");
}
if doc.issuance_date.is_none() {
panic!("Missing issuance date");
}

// work around https://github.com/w3c/vc-test-suite/issues/96
if doc.type_.len() > 1 {
Expand All @@ -21,12 +28,25 @@ fn generate(data: String) -> String {
}
}

// @TODO: sign/verify
return serde_json::to_string_pretty(&doc).unwrap();
serde_json::to_string_pretty(&doc).unwrap()
}

fn generate_jwt(data: &String, keys: &JWTKeys, aud: &String, sign: bool) -> String {
let vc: Credential = serde_json::from_str(data).unwrap();
if sign {
vc.encode_sign_jwt(keys, aud).unwrap()
} else {
vc.encode_jwt_unsigned(aud).unwrap()
}
}

fn decode_jwt_unsigned(data: &String) -> String {
let vc = Credential::from_jwt_unsigned(data).unwrap();
serde_json::to_string_pretty(&vc).unwrap()
}

fn generate_presentation(data: String) -> String {
let doc: Presentation = serde_json::from_str(&data).unwrap();
fn generate_presentation(data: &String) -> String {
let doc: Presentation = serde_json::from_str(data).unwrap();
if !doc.type_.contains(&"VerifiablePresentation".to_string()) {
panic!("Missing type VerifiablePresentation");
}
Expand All @@ -36,57 +56,109 @@ fn generate_presentation(data: String) -> String {
panic!("Missing proof");
}

// @TODO: sign/verify
let response = serde_json::to_string_pretty(&doc).unwrap();
return response;
serde_json::to_string_pretty(&doc).unwrap()
}

fn read_json(filename: &String) -> String {
let mut file = match std::fs::File::open(filename) {
Err(err) => panic!("Unable to open {}: {}", filename, err),
Ok(file) => file,
};
let mut data = String::new();
fn generate_jwt_presentation(data: &String, keys: &JWTKeys, aud: &String) -> String {
let vp: Presentation = serde_json::from_str(data).unwrap();
vp.encode_sign_jwt(keys, aud).unwrap()
}

fn read_file(filename: &String) -> String {
let mut file = std::fs::File::open(filename).unwrap();
let mut data = String::new();
use std::io::Read;
let data = match file.read_to_string(&mut data) {
Err(err) => panic!("Unable to read {}: {}", filename, err),
Ok(_) => data,
};
// TODO: parse JSON
file.read_to_string(&mut data).unwrap();
data
}

fn write_json(data: String) {
fn write_out(data: String) {
use std::io::Write;
let stdout = std::io::stdout();
let mut handle = stdout.lock();
match handle.write_all(data.as_bytes()) {
Err(err) => panic!("Unable to write output: {}", err),
Ok(_) => {}
}
stdout.lock().write_all(data.as_bytes()).unwrap();
}

fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
let args = std::env::args();
let mut cmd: Option<String> = None;
let mut filename: Option<String> = None;
let mut jwt_keys: Option<JWTKeys> = None;
let mut jwt_aud: Option<String> = None;
let mut jwt_no_jws = false;
let mut jwt_presentation = false;
let mut jwt_decode = false;
let mut args_iter = args.into_iter();
let _bin = args_iter.next().unwrap();
loop {
match args_iter.next() {
Some(arg) => match (arg.starts_with("--"), arg.as_ref()) {
(true, "--jwt") => match args_iter.next() {
Some(jwt_b64) => {
let jwt_json = base64::decode(jwt_b64).unwrap();
jwt_keys = Option::Some(serde_json::from_slice(&jwt_json).unwrap());
}
None => {}
},
(true, "--jwt-aud") => jwt_aud = args_iter.next(),
(true, "--jwt-no-jws") => jwt_no_jws = true,
(true, "--jwt-presentation") => jwt_presentation = true,
(true, "--jwt-decode") => jwt_decode = true,
(true, _) => panic!("Unexpected option '{}'", arg),
(false, _) => {
if cmd == None {
cmd = Option::Some(arg);
} else if filename == None {
filename = Option::Some(arg);
} else {
panic!("Unexpected argument '{}'", arg);
}
}
},
None => break,
}
}
if cmd == None || filename == None {
return usage();
}
let cmd = &args[1];
let filename = &args[2];
match &cmd[..] {
let cmd_str = cmd.unwrap();
match cmd_str.as_ref() {
"generate" => {
let data: String = read_json(&filename);
let output: String = generate(data);
write_json(output);
let data: String = read_file(&filename.unwrap());
let output: String;
if jwt_decode {
output = decode_jwt_unsigned(&data);
} else if let Some(keys) = jwt_keys {
if let Some(aud) = jwt_aud {
output = generate_jwt(&data, &keys, &aud, !jwt_no_jws);
} else {
panic!("Expected --jwt-aud with --jwt");
}
} else {
output = generate(data);
}
write_out(output);
}
"generate-presentation" => {
let data: String = read_json(&filename);
let output: String = generate_presentation(data);
write_json(output);
let data: String = read_file(&filename.unwrap());
let output: String;
if let Some(keys) = jwt_keys {
if let Some(aud) = jwt_aud {
if !jwt_presentation {
// vc-test-suite says this is optional, but it seems
// to be always used.
panic!("Expected --jwt-presentation with --jwt");
}
output = generate_jwt_presentation(&data, &keys, &aud);
} else {
panic!("Expected --jwt-aud with --jwt");
}
} else {
output = generate_presentation(&data);
}
write_out(output);
}
_ => {
eprintln!("Unexpected command '{}'", cmd);
eprintln!("Unexpected command '{}'", cmd_str);
std::process::exit(1);
}
}
Expand Down
144 changes: 144 additions & 0 deletions src/der.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// http://luca.ntop.org/Teaching/Appunti/asn1.html
// https://tls.mbed.org/kb/cryptography/asn1-key-structures-in-der-and-pem
// https://en.wikipedia.org/wiki/Distinguished_Encoding_Rules#BER_encoding
// https://serde.rs/impl-serializer.html
// ISO/IEC 8825-1:2015 (E)
// https://tools.ietf.org/html/rfc8017#page-55

pub trait ASN1: Clone {
fn as_bytes(self) -> Vec<u8>;
}

#[derive(Debug, Clone)]
pub struct RSAPrivateKey {
pub modulus: Integer,
pub public_exponent: Integer,
pub private_exponent: Integer,
pub prime1: Integer,
pub prime2: Integer,
pub exponent1: Integer,
pub exponent2: Integer,
pub coefficient: Integer,
pub other_prime_infos: Option<OtherPrimeInfos>,
}

#[derive(Debug, Clone)]
pub struct OtherPrimeInfos(pub Vec<OtherPrimeInfo>);

#[derive(Debug, Clone)]
pub struct OtherPrimeInfo {
pub prime: Integer,
pub exponent: Integer,
pub coefficient: Integer,
}

#[derive(Debug, Clone)]
pub struct Integer(pub Vec<u8>);

fn trim_bytes(bytes: &[u8]) -> Vec<u8> {
// Remove leading zeros from an array.
match bytes.into_iter().position(|&x| x != 0) {
Some(n) => bytes[n..].to_vec(),
None => vec![0],
}
}

fn encode(tag: u8, constructed: bool, contents: Vec<u8>) -> Vec<u8> {
// prepare an ASN1 tag-length-value
let id = tag
| match constructed {
true => 0x20,
false => 0,
};
let len = contents.len();
let len_bytes = trim_bytes(&len.to_be_bytes());
if len <= 127 {
return [vec![id, len_bytes[0]], contents].concat();
}
let len_len = len_bytes.len();
if len_len >= 127 {
// This can't really happen, since to_be_bytes returns an array of length 2, 4, or 8.
panic!("Key data too large");
}
let len_len_bytes = trim_bytes(&len_len.to_be_bytes());
[vec![id, 0x80 | len_len_bytes[0]], len_bytes, contents].concat()
}

impl ASN1 for RSAPrivateKey {
fn as_bytes(self) -> Vec<u8> {
let multiprime = self.other_prime_infos.is_some();
let version = Integer(vec![if multiprime { 1 } else { 0 }]);
encode(
0x10,
true,
[
version.as_bytes().to_vec(),
self.modulus.as_bytes().to_vec(),
self.public_exponent.as_bytes().to_vec(),
self.private_exponent.as_bytes().to_vec(),
self.prime1.as_bytes().to_vec(),
self.prime2.as_bytes().to_vec(),
self.exponent1.as_bytes().to_vec(),
self.exponent2.as_bytes().to_vec(),
self.coefficient.as_bytes().to_vec(),
self.other_prime_infos.as_bytes().to_vec(),
]
.concat(),
)
}
}

impl ASN1 for Integer {
fn as_bytes(self) -> Vec<u8> {
encode(0x02, false, self.0)
}
}

impl<T: ASN1> ASN1 for Option<T> {
fn as_bytes(self) -> Vec<u8> {
match self {
Some(t) => t.as_bytes(),
None => vec![],
}
}
}

impl ASN1 for OtherPrimeInfos {
fn as_bytes(self) -> Vec<u8> {
encode(
0x10,
true,
self.0
.into_iter()
.flat_map(|info| info.as_bytes())
.collect(),
)
}
}

impl ASN1 for OtherPrimeInfo {
fn as_bytes(self) -> Vec<u8> {
encode(
0x10,
wyc marked this conversation as resolved.
Show resolved Hide resolved
true,
[
self.prime.as_bytes().to_vec(),
self.exponent.as_bytes().to_vec(),
self.coefficient.as_bytes().to_vec(),
]
.concat(),
)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn encode_integer() {
let integer = Integer(vec![5]);
let expected = vec![0x02, 0x01, 0x05];
assert_eq!(integer.as_bytes(), expected);
}
}
2 changes: 1 addition & 1 deletion src/did.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::collections::HashMap as Map;
use chrono::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json;
use serde_json::{json, Value};
use serde_json::Value;

// ***********************************************
// * Data Structures for Decentralized Identifiers
Expand Down
Loading