Skip to main content

wechat_pay_rust_sdk/
util.rs

1use base64::engine::general_purpose;
2use base64::{DecodeError, Engine};
3use std::error::Error;
4use uuid::Uuid;
5
6pub fn random_trade_no() -> String {
7    Uuid::new_v4().simple().to_string()
8}
9
10pub fn base64_encode<S>(content: S) -> String
11where
12    S: AsRef<[u8]>,
13{
14    general_purpose::STANDARD.encode(content)
15}
16
17pub fn base64_decode<S>(content: S) -> Result<Vec<u8>, DecodeError>
18where
19    S: AsRef<[u8]>,
20{
21    general_purpose::STANDARD.decode(content.as_ref())
22}
23
24pub fn x509_to_pem(content: &[u8]) -> Result<String, Box<dyn Error>> {
25    let pem = pem::parse(content)?;
26    let (_, cert) = x509_parser::parse_x509_certificate(pem.contents())?;
27    let pub_key = base64_encode(cert.public_key().raw);
28    let pub_key_lines = pub_key
29        .chars()
30        .collect::<Vec<char>>()
31        .chunks(64)
32        .map(|chunk| chunk.iter().collect::<String>())
33        .collect::<Vec<String>>()
34        .join("\n");
35    Ok(format!(
36        "-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----\n",
37        pub_key_lines
38    ))
39}
40
41pub fn x509_is_valid(content: &[u8]) -> Result<(bool, i64), Box<dyn Error>> {
42    let pem = pem::parse(content)?;
43    let (_, cert) = x509_parser::parse_x509_certificate(pem.contents())?;
44    //读取到证书的有效期
45    let expire_time = cert.validity().is_valid();
46    Ok((expire_time, cert.validity.not_after.timestamp()))
47}