feat: v1.0.1, update datakey

This commit is contained in:
2024-11-15 00:24:36 +08:00
parent 9d0e7548e6
commit 82b38a2cf1
6 changed files with 44 additions and 23 deletions

View File

@@ -19,6 +19,7 @@ use serde_json::{Map, Value};
struct DataKeyRequest {
key_type: String,
key_spec: String,
key_name: Option<String>,
return_plaintext: Option<bool>,
}
@@ -38,9 +39,9 @@ async fn inner_generate(req: Request<Body>) -> XResult<(StatusCode, Value)> {
let ret_key_plaintext = request.return_plaintext.unwrap_or(false);
let response_result = match (request.key_type.as_str(), request.key_spec.as_str()) {
("aes", "128") => generate_aes("datakey.aes_128:", key, 16, ret_key_plaintext),
("aes", "192") => generate_aes("datakey.aes_192:", key, 24, ret_key_plaintext),
("aes", "256") => generate_aes("datakey.aes_256:", key, 32, ret_key_plaintext),
("aes", "128") => generate_aes("datakey:aes-128", key, 16, ret_key_plaintext),
("aes", "192") => generate_aes("datakey:aes-192", key, 24, ret_key_plaintext),
("aes", "256") => generate_aes("datakey:aes-256", key, 32, ret_key_plaintext),
// TODO rsa 2048, rsa 3072, rsa 4096
// TODO ec p256, p384, p521, ed25519, cv25519
_ => return serve_common::error("invalid key_type or key_spec"),
@@ -56,22 +57,21 @@ async fn inner_generate(req: Request<Body>) -> XResult<(StatusCode, Value)> {
map.insert("key_plaintext".to_string(), Value::String(STANDARD.encode(&key_plaintext)));
}
map.insert("key_ciphertext".to_string(), Value::String(key_ciphertext));
if let Some(_key_name) = &request.key_name {
// TODO write datakey to db
// TODO let data_key_name = format!("datakey:{}", key_name);
}
Ok((StatusCode::OK, Value::Object(map)))
}
}
}
fn generate_aes(prefix: &str, key: SecBytes, len: i32, ret_key_plaintext: bool) -> XResult<(Option<Vec<u8>>, String)> {
fn generate_aes(data_key_type: &str, key: SecBytes, len: i32, ret_key_plaintext: bool) -> XResult<(Option<Vec<u8>>, String)> {
let bytes: [u8; 32] = random();
let value = &bytes[0..len as usize];
let key_plaintext = iff!(ret_key_plaintext, Some(value.to_vec()), None);
let key_ciphertext = jose::serialize_jwe_aes(&join_prefix_value(prefix, value), &key.read())?;
let key_ciphertext = jose::serialize_jwe_aes_with_data_type(data_key_type, value, &key.read())?;
Ok((key_plaintext, key_ciphertext))
}
fn join_prefix_value(prefix: &str, value: &[u8]) -> Vec<u8> {
let mut ret = Vec::with_capacity(prefix.len() + value.len());
ret.extend_from_slice(prefix.as_bytes());
ret.extend_from_slice(value);
ret
}