feat: ecdh encrypt

This commit is contained in:
2023-09-30 00:23:20 +08:00
parent 86c0ed7230
commit c317a80119
7 changed files with 92 additions and 206 deletions

View File

@@ -2,18 +2,16 @@ use std::fs;
use std::path::PathBuf;
use clap::Args;
use p256::{PublicKey, EncodedPoint};
use p256::ecdh::EphemeralSecret;
use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
use rand::random;
use rand::rngs::OsRng;
use rsa::Pkcs1v15Encrypt;
use rust_util::{debugging, failure, opt_result, simple_error, success, XResult};
use crate::config::{TinyEncryptConfig, TinyEncryptConfigEnvelop};
use crate::crypto_aes::aes_gcm_encrypt;
use crate::crypto_rsa::parse_spki;
use crate::spec::{EncMetadata, TinyEncryptEnvelop, TinyEncryptEnvelopType, TinyEncryptMeta};
use crate::util::{encode_base64, simple_kdf, TINY_ENC_CONFIG_FILE};
use crate::util::{ENC_AES256_GCM_P256, encode_base64, make_key256_and_nonce, simple_kdf, TINY_ENC_CONFIG_FILE, zeroize};
use crate::util_ecdh::compute_shared_secret;
use crate::wrap_key::{WrapKey, WrapKeyHeader};
#[derive(Debug, Args)]
pub struct CmdEncrypt {
@@ -54,9 +52,12 @@ fn encrypt_single(path: &PathBuf, envelops: &[&TinyEncryptConfigEnvelop]) -> XRe
compress: false,
};
let _encrypt_meta = TinyEncryptMeta::new(&file_metadata, &enc_metadata, &nonce, envelops);
let encrypt_meta = TinyEncryptMeta::new(&file_metadata, &enc_metadata, &nonce, envelops);
debugging!("Encrypted meta: {:?}", encrypt_meta);
// TODO write to file and do encrypt
zeroize(key);
zeroize(nonce);
Ok(())
}
@@ -78,49 +79,31 @@ fn encrypt_envelops(key: &[u8], envelops: &[&TinyEncryptConfigEnvelop]) -> XResu
fn encrypt_envelop_ecdh(key: &[u8], envelop: &TinyEncryptConfigEnvelop) -> XResult<TinyEncryptEnvelop> {
let public_key_point_hex = &envelop.public_part;
let public_key_point_bytes = opt_result!(hex::decode(public_key_point_hex), "Parse public key point hex failed: {}");
let encoded_point = opt_result!(EncodedPoint::from_bytes(&public_key_point_bytes), "Parse public key point failed: {}");
let public_key = PublicKey::from_encoded_point(&encoded_point).unwrap();
let (shared_secret, ephemeral_spki) = compute_shared_secret(public_key_point_hex)?;
let shared_key = simple_kdf(shared_secret.as_slice());
let (_, nonce) = make_key256_and_nonce();
let esk = EphemeralSecret::random(&mut OsRng);
let epk = esk.public_key();
let epk_bytes = EphemeralKeyBytes::from_public_key(&epk);
let public_key_encoded_point = public_key.to_encoded_point(false);
let shared_secret = esk.diffie_hellman(&public_key);
let key = simple_kdf(shared_secret.raw_secret_bytes().as_slice());
let encrypted_key = aes_gcm_encrypt(&shared_key, &nonce, key)?;
// PORT Java Implementation
// public static WrapKey encryptEcdhP256(String kid, PublicKey publicKey, byte[] data) {
// AssertUtil.isTrue(publicKey instanceof ECPublicKey, "Public key must be EC public key");
// if (data == null || data.length == 0) {
// return null;
// }
// final Tuple2<PublicKey, byte[]> ecdh = ECUtil.ecdh(ECUtil.CURVE_SECP256R1, publicKey);
// final byte[] ePublicKeyBytes = ecdh.getVal1().getEncoded();
// final byte[] key = KdfUtil.simpleKdf256(ecdh.getVal2());
//
// final byte[] nonce = RandomTool.secureRandom().nextbytes(AESCryptTool.GCM_NONCE_LENGTH);
// final byte[] encryptedData = AESCryptTool.gcmEncrypt(key, nonce).from(Bytes.from(data)).toBytes().bytes();
// final WrapKey wrapKey = new WrapKey();
// final WrapKeyHeader wrapKeyHeader = new WrapKeyHeader();
// wrapKeyHeader.setKid(kid);
// wrapKeyHeader.setEnc(ENC_AES256_GCM_P256);
// wrapKeyHeader.setePubKey(Base64s.uriCompatible().encode(ePublicKeyBytes));
// wrapKey.setHeader(wrapKeyHeader);
// wrapKey.setNonce(nonce);
// wrapKey.setEncrytpedData(encryptedData);
// return wrapKey;
// }
let wrap_key = WrapKey {
header: WrapKeyHeader {
kid: Some(envelop.kid.clone()),
enc: ENC_AES256_GCM_P256.to_string(),
e_pub_key: encode_base64(&ephemeral_spki),
},
nonce,
encrypted_data: encrypted_key,
};
let encoded_wrap_key = wrap_key.encode()?;
Ok(TinyEncryptEnvelop {
r#type: envelop.r#type,
kid: envelop.kid.clone(),
desc: envelop.desc.clone(),
encrypted_key: "".to_string(), // TODO ...
encrypted_key: encoded_wrap_key,
})
}
fn encrypt_envelop_pgp(key: &[u8], envelop: &TinyEncryptConfigEnvelop) -> XResult<TinyEncryptEnvelop> {
let pgp_public_key = opt_result!(parse_spki(&envelop.public_part), "Parse PGP public key failed: {}");
let mut rng = rand::thread_rng();
@@ -132,24 +115,3 @@ fn encrypt_envelop_pgp(key: &[u8], envelop: &TinyEncryptConfigEnvelop) -> XResul
encrypted_key: encode_base64(&encrypted_key),
})
}
fn make_key256_and_nonce() -> (Vec<u8>, Vec<u8>) {
let key: [u8; 32] = random();
let nonce: [u8; 12] = random();
(key.into(), nonce.into())
}
#[derive(Debug)]
pub struct EphemeralKeyBytes(EncodedPoint);
impl EphemeralKeyBytes {
fn from_public_key(epk: &PublicKey) -> Self {
EphemeralKeyBytes(epk.to_encoded_point(true))
}
fn decompress(&self) -> EncodedPoint {
// EphemeralKeyBytes is a valid compressed encoding by construction.
let p = PublicKey::from_encoded_point(&self.0).unwrap();
p.to_encoded_point(false)
}
}

View File

@@ -1,4 +1,4 @@
use aes_gcm_stream::Aes256GcmStreamDecryptor;
use aes_gcm_stream::{Aes256GcmStreamDecryptor, Aes256GcmStreamEncryptor};
use rust_util::{opt_result, XResult};
pub fn aes_gcm_decrypt(key: &[u8], nonce: &[u8], message: &[u8]) -> XResult<Vec<u8>> {
@@ -10,10 +10,18 @@ pub fn aes_gcm_decrypt(key: &[u8], nonce: &[u8], message: &[u8]) -> XResult<Vec<
Ok(b1)
}
pub fn aes_gcm_encrypt(key: &[u8], nonce: &[u8], message: &[u8]) -> XResult<Vec<u8>> {
let key: [u8; 32] = opt_result!(key.try_into(), "Invalid envelop: {}");
let mut aes256_gcm = Aes256GcmStreamEncryptor::new(key, nonce);
let mut b1 = aes256_gcm.update(message);
let (b2, tag) = aes256_gcm.finalize();
b1.extend_from_slice(&b2);
b1.extend_from_slice(&tag);
Ok(b1)
}
#[test]
fn test_aes_gcm_01() {
use aes_gcm_stream::Aes256GcmStreamEncryptor;
let data_key = hex::decode("0001020304050607080910111213141516171819202122232425262728293031").unwrap();
let nonce = hex::decode("000102030405060708091011").unwrap();
@@ -44,8 +52,6 @@ fn test_aes_gcm_01() {
#[test]
fn test_aes_gcm_02() {
use aes_gcm_stream::Aes256GcmStreamDecryptor;
let data_key = hex::decode("aa01020304050607080910111213141516171819202122232425262728293031").unwrap();
let nonce = hex::decode("aa0102030405060708091011").unwrap();

View File

@@ -8,6 +8,7 @@ use crate::cmd_encrypt::CmdEncrypt;
use crate::cmd_info::CmdInfo;
mod util;
mod util_ecdh;
mod compress;
mod config;
mod spec;

View File

@@ -4,6 +4,7 @@ use std::path::Path;
use base64::Engine;
use base64::engine::general_purpose;
use rand::random;
use rust_util::{simple_error, warning, XResult};
use zeroize::Zeroize;
@@ -37,6 +38,12 @@ pub fn require_file_not_exists(path: impl AsRef<Path>) -> XResult<()> {
}
}
pub fn make_key256_and_nonce() -> (Vec<u8>, Vec<u8>) {
let key: [u8; 32] = random();
let nonce: [u8; 12] = random();
(key.into(), nonce.into())
}
pub fn simple_kdf(input: &[u8]) -> Vec<u8> {
let input = hex::decode(sha256::digest(input)).unwrap();
let input = hex::decode(sha256::digest(input)).unwrap();

34
src/util_ecdh.rs Normal file
View File

@@ -0,0 +1,34 @@
use p256::ecdh::EphemeralSecret;
use rand::rngs::OsRng;
use rust_util::{opt_result, XResult};
use p256::pkcs8::EncodePublicKey;
use p256::{EncodedPoint, PublicKey};
use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
#[derive(Debug)]
pub struct EphemeralKeyBytes(EncodedPoint);
impl EphemeralKeyBytes {
pub fn from_public_key(epk: &PublicKey) -> Self {
EphemeralKeyBytes(epk.to_encoded_point(true))
}
pub fn decompress(&self) -> EncodedPoint {
// EphemeralKeyBytes is a valid compressed encoding by construction.
let p = PublicKey::from_encoded_point(&self.0).unwrap();
p.to_encoded_point(false)
}
}
pub fn compute_shared_secret(public_key_point_hex: &str) -> XResult<(Vec<u8>, Vec<u8>)> {
let public_key_point_bytes = opt_result!(hex::decode(public_key_point_hex), "Parse public key point hex failed: {}");
let encoded_point = opt_result!(EncodedPoint::from_bytes(&public_key_point_bytes), "Parse public key point failed: {}");
let public_key = PublicKey::from_encoded_point(&encoded_point).unwrap();
let esk = EphemeralSecret::random(&mut OsRng);
let epk = esk.public_key();
let shared_secret = esk.diffie_hellman(&public_key);
let epk_public_key_der = opt_result!(epk.to_public_key_der(), "Convert epk to SPKI failed: {}");
Ok((shared_secret.raw_secret_bytes().as_slice().to_vec(), epk_public_key_der.to_vec()))
}