Skip to content

Commit

Permalink
feat: add pem dependency and implement public key parsing from PEM fo…
Browse files Browse the repository at this point in the history
…rmat
  • Loading branch information
incubator4 committed Feb 12, 2025
1 parent 7bac393 commit 7c4cb6f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 18 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ solana-sdk = { version = "2.1.13" }
thiserror = "2.0.11"
tracing = "0.1"
tokio = { version = "1.0", features = ["full"] }
base64 = "0.22.1"
pem = "3.0.4"

[dev-dependencies]
tokio = { version = "1.0", features = ["full"] }
42 changes: 26 additions & 16 deletions src/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
use core::fmt;
use std::{cell::OnceCell, sync::Arc};

use base64::Engine;
use gcloud_sdk::{
google::cloud::kms::{
// self,
Expand All @@ -24,7 +23,6 @@ use solana_sdk::{
signer::{Signer, SignerError},
};
use thiserror::Error;
// use ed25519::pkcs8::Pubkey;

type Client = GoogleApi<KeyManagementServiceClient<GoogleAuthMiddleware>>;

Expand Down Expand Up @@ -100,7 +98,10 @@ pub enum GcpSignerError {
RequestError(#[from] tonic::Status),

#[error(transparent)]
Base64Error(#[from] base64::DecodeError),
PemError(#[from] pem::PemError),

#[error("Invalid pubkey length {0}")]
InvalidPubkeyLength(usize),
}

impl Into<SignerError> for GcpSignerError {
Expand Down Expand Up @@ -136,22 +137,10 @@ impl GcpSigner {
let key_name = key_specifier.0;
let pubkey = request_get_pubkey(&client, &key_name).await?;

let clean_b64 = pubkey
.pem
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replace('\n', "")
.trim()
.to_string();

let der_bytes = base64::engine::general_purpose::STANDARD.decode(clean_b64)?;

Ok(Self {
client,
key_name,
pubkey: Arc::new(OnceCell::from(Pubkey::from_str_const(
std::str::from_utf8(&der_bytes).unwrap(),
))),
pubkey: Arc::new(OnceCell::from(from_public_key_pem(pubkey)?)),
address: String::from(""),
})
}
Expand Down Expand Up @@ -182,6 +171,27 @@ async fn request_get_pubkey(
.map_err(Into::into)
}

#[instrument(err)]
fn from_public_key_pem(key: PublicKey) -> Result<Pubkey, GcpSignerError> {
let pkey = pem::parse(key.pem)?;

let content = pkey.contents();

let mut array = [0u8; 32];

match content.len() {
32 => {
array.copy_from_slice(content);
Ok(Pubkey::new_from_array(array))
}
44 => {
array.copy_from_slice(&content[12..]);
Ok(Pubkey::new_from_array(array))
}
size => Err(GcpSignerError::InvalidPubkeyLength(size)),
}
}

#[cfg(test)]
mod test {
use solana_sdk::signer::Signer;
Expand Down

0 comments on commit 7c4cb6f

Please sign in to comment.