Skip to content

Commit

Permalink
Add create_timestamp_request
Browse files Browse the repository at this point in the history
  • Loading branch information
DarkaMaul committed Sep 25, 2024
1 parent c2dbe78 commit 92807c5
Show file tree
Hide file tree
Showing 3 changed files with 209 additions and 2 deletions.
156 changes: 156 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ crate-type = ["cdylib"]
pyo3 = "0.22.0"
asn1 = "0.17"
self_cell = "1"
hex = "0.4"
hex = "0.4"
sha2 = "0.10.8"
rand = "0.8.5"
51 changes: 50 additions & 1 deletion rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ pub mod name;
pub mod oid;
pub mod tsp;

use pyo3::prelude::*;
use pyo3::{exceptions::PyValueError, prelude::*};
use rand::Rng;
use sha2::{Sha512, Digest};
use tsp::{RawTimeStampReq, RawTimeStampResp};

self_cell::self_cell!(
Expand Down Expand Up @@ -76,12 +78,59 @@ pub(crate) fn parse_timestamp_request(
Ok(TimeStampReq { raw: raw.into() })
}

#[pyo3::pyfunction]
#[pyo3(signature = (data))]
pub(crate) fn create_timestamp_request(
py: pyo3::Python<'_>,
data: pyo3::Py<pyo3::types::PyBytes>,
) -> PyResult<TimeStampReq> {

let data_bytes = data.as_bytes(py);
let hash = sha2::Sha512::digest(data_bytes);

let message_imprint = tsp::MessageImprint {
hash_algorithm: common::AlgorithmIdentifier {
oid: asn1::DefinedByMarker::marker(),
params: common::AlgorithmParameters::Sha512(Some(()))
},
hashed_message: hash.as_slice(),
};

let mut rng = rand::thread_rng();
let nonce: u64 = rng.gen();
let nonce_bytes = nonce.to_be_bytes();

let nonce_biguint = asn1::BigUint::new(&nonce_bytes);

let timestamp_request = RawTimeStampReq {
version: 1,
message_imprint: message_imprint,
nonce: nonce_biguint,
req_policy: None,
cert_req: false,
extensions: None,
};

let request_bytes = asn1::write_single(&timestamp_request)
.map_err(|e| PyValueError::new_err(format!("Serialization error: {:?}", e)));
let py_bytes = pyo3::types::PyBytes::new_bound(py, &request_bytes.unwrap()).unbind();

let raw = OwnedTimeStamReq::try_new(py_bytes, |data| asn1::parse_single(data.as_bytes(py)))
.map_err(|e| {
pyo3::exceptions::PyValueError::new_err(format!("ASN.1 parse error: {:?}", e))
})?;

Ok(TimeStampReq { raw: raw.into() })

}

/// A Python module implemented in Rust.
#[pymodule]
fn sigstore_tsp(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<TimeStampReq>()?;
m.add_class::<TimeStampResp>()?;
m.add_function(wrap_pyfunction!(parse_timestamp_response, m)?)?;
m.add_function(wrap_pyfunction!(create_timestamp_request, m)?)?;
m.add_function(wrap_pyfunction!(parse_timestamp_request, m)?)?;
Ok(())
}
Expand Down

0 comments on commit 92807c5

Please sign in to comment.