| 1 |
use super::CryptoError; |
| 2 |
use openssl::bn::BigNumContext; |
| 3 |
use openssl::derive::Deriver; |
| 4 |
use openssl::ec::{EcGroup, EcKey, PointConversionForm}; |
| 5 |
use openssl::error::ErrorStack; |
| 6 |
use openssl::hash::{hash, MessageDigest}; |
| 7 |
use openssl::nid::Nid; |
| 8 |
use openssl::pkey::{PKey, Private, Public}; |
| 9 |
use openssl::rand::rand_bytes; |
| 10 |
use openssl::sign::Signer; |
| 11 |
use openssl::symm::{Cipher, Crypter, Mode}; |
| 12 |
use std::os::raw::c_int; |
| 13 |
|
| 14 |
#[cfg(test)] |
| 15 |
use openssl::ec::EcPoint; |
| 16 |
|
| 17 |
#[cfg(test)] |
| 18 |
use openssl::bn::BigNum; |
| 19 |
|
| 20 |
const AES_BLOCK_SIZE: usize = 16; |
| 21 |
|
| 22 |
impl From<ErrorStack> for CryptoError { |
| 23 |
fn from(e: ErrorStack) -> Self { |
| 24 |
CryptoError::Backend(format!("{e}")) |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
impl From<&ErrorStack> for CryptoError { |
| 29 |
fn from(e: &ErrorStack) -> Self { |
| 30 |
CryptoError::Backend(format!("{e}")) |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
pub type Result<T> = std::result::Result<T, CryptoError>; |
| 35 |
|
| 36 |
/// ECDH using OpenSSL types. Computes the x coordinate of scalar multiplication of `peer_public` |
| 37 |
/// by `client_private`. |
| 38 |
fn ecdh_openssl_raw(client_private: EcKey<Private>, peer_public: EcKey<Public>) -> Result<Vec<u8>> { |
| 39 |
let client_pkey = PKey::from_ec_key(client_private)?; |
| 40 |
let peer_pkey = PKey::from_ec_key(peer_public)?; |
| 41 |
let mut deriver = Deriver::new(&client_pkey)?; |
| 42 |
deriver.set_peer(&peer_pkey)?; |
| 43 |
let shared_point = deriver.derive_to_vec()?; |
| 44 |
Ok(shared_point) |
| 45 |
} |
| 46 |
|
| 47 |
/// Ephemeral ECDH over P256. Takes a DER SubjectPublicKeyInfo that encodes a public key. Generates |
| 48 |
/// an ephemeral P256 key pair. Returns |
| 49 |
/// 1) the x coordinate of the shared point, and |
| 50 |
/// 2) the uncompressed SEC 1 encoding of the ephemeral public key. |
| 51 |
pub fn ecdhe_p256_raw(peer_spki: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> { |
| 52 |
let peer_public = EcKey::public_key_from_der(peer_spki)?; |
| 53 |
|
| 54 |
// Hard-coding the P256 group here is easier than extracting a group name from peer_public and |
| 55 |
// comparing it with P256. We'll fail in key derivation if peer_public is on the wrong curve. |
| 56 |
let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)?; |
| 57 |
|
| 58 |
let mut bn_ctx = BigNumContext::new()?; |
| 59 |
let client_private = EcKey::generate(&group)?; |
| 60 |
let client_public_sec1 = client_private.public_key().to_bytes( |
| 61 |
&group, |
| 62 |
PointConversionForm::UNCOMPRESSED, |
| 63 |
&mut bn_ctx, |
| 64 |
)?; |
| 65 |
|
| 66 |
let shared_point = ecdh_openssl_raw(client_private, peer_public)?; |
| 67 |
|
| 68 |
Ok((shared_point, client_public_sec1)) |
| 69 |
} |
| 70 |
|
| 71 |
/// AES-256-CBC encryption for data that is a multiple of the AES block size (16 bytes) in length. |
| 72 |
/// Uses the zero IV if `iv` is None. |
| 73 |
pub fn encrypt_aes_256_cbc_no_pad(key: &[u8], iv: Option<&[u8]>, data: &[u8]) -> Result<Vec<u8>> { |
| 74 |
let iv = iv.unwrap_or(&[0u8; AES_BLOCK_SIZE]); |
| 75 |
|
| 76 |
let mut encrypter = Crypter::new(Cipher::aes_256_cbc(), Mode::Encrypt, key, Some(iv))?; |
| 77 |
encrypter.pad(false); |
| 78 |
|
| 79 |
let in_len = data.len(); |
| 80 |
if in_len % AES_BLOCK_SIZE != 0 { |
| 81 |
return Err(CryptoError::LibraryFailure); |
| 82 |
} |
| 83 |
|
| 84 |
// OpenSSL would panic if we didn't allocate an extra block here. |
| 85 |
let mut out = vec![0; in_len + AES_BLOCK_SIZE]; |
| 86 |
let mut out_len = 0; |
| 87 |
out_len += encrypter.update(data, out.as_mut_slice())?; |
| 88 |
out_len += encrypter.finalize(out.as_mut_slice())?; |
| 89 |
debug_assert_eq!(in_len, out_len); |
| 90 |
|
| 91 |
out.truncate(out_len); |
| 92 |
Ok(out) |
| 93 |
} |
| 94 |
|
| 95 |
/// AES-256-CBC decryption for data that is a multiple of the AES block size (16 bytes) in length. |
| 96 |
/// Uses the zero IV if `iv` is None. |
| 97 |
pub fn decrypt_aes_256_cbc_no_pad(key: &[u8], iv: Option<&[u8]>, data: &[u8]) -> Result<Vec<u8>> { |
| 98 |
let iv = iv.unwrap_or(&[0u8; AES_BLOCK_SIZE]); |
| 99 |
|
| 100 |
let mut encrypter = Crypter::new(Cipher::aes_256_cbc(), Mode::Decrypt, key, Some(iv))?; |
| 101 |
encrypter.pad(false); |
| 102 |
|
| 103 |
let in_len = data.len(); |
| 104 |
if in_len % AES_BLOCK_SIZE != 0 { |
| 105 |
return Err(CryptoError::LibraryFailure); |
| 106 |
} |
| 107 |
|
| 108 |
// OpenSSL would panic if we didn't allocate an extra block here. |
| 109 |
let mut out = vec![0; in_len + AES_BLOCK_SIZE]; |
| 110 |
let mut out_len = 0; |
| 111 |
out_len += encrypter.update(data, out.as_mut_slice())?; |
| 112 |
out_len += encrypter.finalize(out.as_mut_slice())?; |
| 113 |
debug_assert_eq!(in_len, out_len); |
| 114 |
|
| 115 |
out.truncate(out_len); |
| 116 |
Ok(out) |
| 117 |
} |
| 118 |
|
| 119 |
/// Textbook HMAC-SHA256 |
| 120 |
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> Result<Vec<u8>> { |
| 121 |
let key = PKey::hmac(key)?; |
| 122 |
let mut signer = Signer::new(MessageDigest::sha256(), &key)?; |
| 123 |
signer.update(data)?; |
| 124 |
Ok(signer.sign_to_vec()?) |
| 125 |
} |
| 126 |
|
| 127 |
pub fn sha256(data: &[u8]) -> Result<Vec<u8>> { |
| 128 |
let digest = hash(MessageDigest::sha256(), data)?; |
| 129 |
Ok(digest.as_ref().to_vec()) |
| 130 |
} |
| 131 |
|
| 132 |
pub fn random_bytes(count: usize) -> Result<Vec<u8>> { |
| 133 |
if count > c_int::MAX as usize { |
| 134 |
return Err(CryptoError::LibraryFailure); |
| 135 |
} |
| 136 |
let mut out = vec![0u8; count]; |
| 137 |
rand_bytes(&mut out)?; |
| 138 |
Ok(out) |
| 139 |
} |
| 140 |
|
| 141 |
#[cfg(test)] |
| 142 |
pub fn test_ecdh_p256_raw( |
| 143 |
peer_spki: &[u8], |
| 144 |
client_public_x: &[u8], |
| 145 |
client_public_y: &[u8], |
| 146 |
client_private: &[u8], |
| 147 |
) -> Result<Vec<u8>> { |
| 148 |
let peer_public = EcKey::public_key_from_der(peer_spki)?; |
| 149 |
let group = peer_public.group(); |
| 150 |
|
| 151 |
let mut client_pub_sec1 = vec![]; |
| 152 |
client_pub_sec1.push(0x04); // SEC 1 encoded uncompressed point |
| 153 |
client_pub_sec1.extend_from_slice(&client_public_x); |
| 154 |
client_pub_sec1.extend_from_slice(&client_public_y); |
| 155 |
|
| 156 |
let mut ctx = BigNumContext::new()?; |
| 157 |
let client_pub_point = EcPoint::from_bytes(&group, &client_pub_sec1, &mut ctx)?; |
| 158 |
let client_priv_bignum = BigNum::from_slice(client_private)?; |
| 159 |
let client_private = |
| 160 |
EcKey::from_private_components(&group, &client_priv_bignum, &client_pub_point)?; |
| 161 |
|
| 162 |
let shared_point = ecdh_openssl_raw(client_private, peer_public)?; |
| 163 |
|
| 164 |
Ok(shared_point) |
| 165 |
} |
| 166 |
|
| 167 |
pub fn gen_p256() -> Result<(Vec<u8>, Vec<u8>)> { |
| 168 |
unimplemented!() |
| 169 |
} |
| 170 |
|
| 171 |
pub fn ecdsa_p256_sha256_sign_raw(_private: &[u8], _data: &[u8]) -> Result<Vec<u8>> { |
| 172 |
unimplemented!() |
| 173 |
} |
| 174 |
|
| 175 |
#[allow(dead_code)] |
| 176 |
#[cfg(test)] |
| 177 |
pub fn test_ecdsa_p256_sha256_verify_raw( |
| 178 |
_public: &[u8], |
| 179 |
_signature: &[u8], |
| 180 |
_data: &[u8], |
| 181 |
) -> Result<()> { |
| 182 |
unimplemented!() |
| 183 |
} |