Skip to content

Commit

Permalink
fix(openssl): Update to 0.9.x
Browse files Browse the repository at this point in the history
This also updates hyper to 0.10.x because it uses openssl
  • Loading branch information
martell committed Jan 26, 2017
1 parent 608b2af commit fe0a094
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 33 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ build = "src/build.rs"
[dependencies]
base64 = "0.2"
chrono = "0.2"
hyper = "0.9.0"
hyper = "0.10.2"
itertools = "0.4"
log = "0.3"
openssl = "0.7"
openssl = "0.9.6"
serde = "0.8"
serde_json = "0.8"
serde_derive = { version = "0.8", optional = true }
Expand Down
40 changes: 9 additions & 31 deletions src/service_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use std::default::Default;
use std::error;
use std::io::{Read, Write};
use std::result;
use std::str;

use authenticator::GetToken;
use types::{StringError, Token};
Expand All @@ -38,33 +39,6 @@ fn encode_base64<T: AsRef<[u8]>>(s: T) -> String {
base64::encode_mode(s.as_ref(), base64::Base64Mode::UrlSafe)
}

// Calculates the SHA256 hash.
fn hash_sha256(data: &[u8]) -> Vec<u8> {
let mut hasher = openssl::crypto::hash::Hasher::new(openssl::crypto::hash::Type::SHA256);
let _ = hasher.write(data);
hasher.finish()
}

// Signs the hash with key.
fn sign_rsa(key: &openssl::crypto::rsa::RSA, hash: &[u8]) -> String {
let signature = key.sign(openssl::crypto::hash::Type::SHA256, hash).unwrap();
let b64_signature = encode_base64(signature);

b64_signature
}

// Reads an RSA key from pem_pkcs8 (the format of the 'private_key' field in the service account
// key).
fn decode_rsa_key(pem_pkcs8: &str) -> Result<openssl::crypto::rsa::RSA, Box<error::Error>> {
let private_key = pem_pkcs8.to_string().replace("\\n", "\n");
let privkey = openssl::crypto::rsa::RSA::private_key_from_pem(&mut private_key.as_bytes());

match privkey {
Err(e) => Err(Box::new(e)),
Ok(key) => Ok(key),
}
}

/// JSON schema of secret service account key. You can obtain the key from
/// the Cloud Console at https://console.cloud.google.com/.
///
Expand Down Expand Up @@ -121,12 +95,16 @@ impl JWT {
fn sign(&self, private_key: &str) -> Result<String, Box<error::Error>> {
let mut jwt_head = self.encode_claims();

let key = try!(decode_rsa_key(private_key));
let hash = hash_sha256(&jwt_head.as_bytes());
let signature = sign_rsa(&key, &hash);
let key = openssl::pkey::PKey::hmac(private_key.as_bytes()).unwrap();

let mut signer =
try!(openssl::sign::Signer::new(
openssl::hash::MessageDigest::sha256(), &key));
signer.update(&jwt_head.as_bytes()).unwrap();
let signature = signer.finish().unwrap();

jwt_head.push_str(".");
jwt_head.push_str(&signature);
jwt_head.push_str(str::from_utf8(&signature).unwrap());

Ok(jwt_head)
}
Expand Down

0 comments on commit fe0a094

Please sign in to comment.