Skip to content

Commit

Permalink
Revert "fix(openssl): Update to 0.9.x"
Browse files Browse the repository at this point in the history
The patch introduced an unwrap() failure in a test.

This reverts commit fe0a094.
  • Loading branch information
dermesser committed Jan 30, 2017
1 parent 11e2b5b commit 1639b16
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions src/service_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ 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 @@ -39,6 +38,33 @@ 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 @@ -95,16 +121,12 @@ impl JWT {
fn sign(&self, private_key: &str) -> Result<String, Box<error::Error>> {
let mut jwt_head = self.encode_claims();

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();
let key = try!(decode_rsa_key(private_key));
let hash = hash_sha256(&jwt_head.as_bytes());
let signature = sign_rsa(&key, &hash);

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

Ok(jwt_head)
}
Expand Down

0 comments on commit 1639b16

Please sign in to comment.