feat: v1.11.15, add convert-jwk-to-pem
This commit is contained in:
@@ -1,8 +1,14 @@
|
||||
use std::collections::HashMap;
|
||||
use openssl::bn::{BigNum, BigNumContext};
|
||||
use openssl::pkey::PKey;
|
||||
use openssl::rsa::{Padding, Rsa};
|
||||
use rsa::RsaPublicKey;
|
||||
use rust_util::{util_msg, XResult};
|
||||
use rust_util::util_msg::MessageType;
|
||||
use spki::DecodePublicKey;
|
||||
use rsa::pkcs1::DecodeRsaPublicKey;
|
||||
use rsa::traits::PublicKeyParts;
|
||||
use crate::util::{base64_decode, base64_encode};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RsaCrt {
|
||||
@@ -151,3 +157,40 @@ fn pkcs1_padding_for_sign(bs: &[u8], bit_len: usize) -> XResult<Vec<u8>> {
|
||||
output.extend_from_slice(bs);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
pub fn convert_rsa_to_jwk(public_key: &str) -> XResult<String> {
|
||||
let rsa_public_key = try_parse_rsa(public_key)?;
|
||||
|
||||
let e_bytes = rsa_public_key.e().to_bytes_be();
|
||||
let n_bytes = rsa_public_key.n().to_bytes_be();
|
||||
|
||||
let mut jwk = HashMap::new();
|
||||
jwk.insert("kty", "RSA".to_string());
|
||||
jwk.insert("n", base64_encode(&n_bytes));
|
||||
jwk.insert("e", base64_encode(&e_bytes));
|
||||
|
||||
Ok(serde_json::to_string(&jwk).unwrap())
|
||||
}
|
||||
|
||||
fn try_parse_rsa(public_key: &str) -> XResult<RsaPublicKey> {
|
||||
debugging!("Try parse RSA public key PEM.");
|
||||
// parse RSA public key PEM not works? why?
|
||||
if let Ok(rsa_public_key) = RsaPublicKey::from_public_key_pem(public_key) {
|
||||
return Ok(rsa_public_key);
|
||||
}
|
||||
debugging!("Try parse RSA PKCS#1 public key PEM.");
|
||||
if let Ok(rsa_public_key) = RsaPublicKey::from_pkcs1_pem(public_key) {
|
||||
return Ok(rsa_public_key);
|
||||
}
|
||||
if let Ok(public_key_der) = base64_decode(public_key) {
|
||||
debugging!("Try parse RSA public key DER.");
|
||||
if let Ok(rsa_public_key) = RsaPublicKey::from_public_key_der(&public_key_der) {
|
||||
return Ok(rsa_public_key);
|
||||
}
|
||||
debugging!("Try parse RSA PKCS#1 public key DER.");
|
||||
if let Ok(rsa_public_key) = RsaPublicKey::from_pkcs1_der(&public_key_der) {
|
||||
return Ok(rsa_public_key);
|
||||
}
|
||||
}
|
||||
simple_error!("Invalid RSA public key.")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user