This commit is contained in:
2025-05-13 07:28:02 +03:00
parent 495fe92321
commit 393c4270d4
2 changed files with 29 additions and 25 deletions

View File

@@ -1,6 +1,7 @@
/// Implementation of keypair functionality.
use k256::ecdsa::{SigningKey, VerifyingKey, signature::{Signer, Verifier}, Signature};
use k256::ecdh::EphemeralSecret;
use rand::rngs::OsRng;
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
@@ -214,22 +215,24 @@ impl KeyPair {
let ephemeral_signing_key = SigningKey::random(&mut OsRng);
let ephemeral_public_key = VerifyingKey::from(&ephemeral_signing_key);
// Derive shared secret (this is a simplified ECDH)
// In a real implementation, we would use proper ECDH, but for this example:
let shared_point = recipient_key.to_encoded_point(false);
let shared_secret = {
// Derive shared secret using ECDH
let ephemeral_secret = EphemeralSecret::random(&mut OsRng);
let shared_secret = ephemeral_secret.diffie_hellman(&recipient_key.to_public_key());
// Derive encryption key from the shared secret (e.g., using HKDF or hashing)
// For simplicity, we'll hash the shared secret here
let encryption_key = {
let mut hasher = Sha256::default();
hasher.update(ephemeral_signing_key.to_bytes());
hasher.update(shared_point.as_bytes());
hasher.update(shared_secret.raw_secret_bytes());
hasher.finalize().to_vec()
};
// Encrypt the message using the derived key
let ciphertext = implementation::encrypt_with_key(&shared_secret, message)
let ciphertext = implementation::encrypt_with_key(&encryption_key, message)
.map_err(|e| CryptoError::EncryptionFailed(e.to_string()))?;
// Format: ephemeral_public_key || ciphertext
let mut result = ephemeral_public_key.to_sec1_bytes().to_vec();
let mut result = ephemeral_public_key.to_encoded_point(false).as_bytes().to_vec();
result.extend_from_slice(&ciphertext);
Ok(result)
@@ -252,17 +255,19 @@ impl KeyPair {
let sender_key = VerifyingKey::from_sec1_bytes(ephemeral_public_key)
.map_err(|_| CryptoError::InvalidKeyLength)?;
// Derive shared secret (simplified ECDH)
let shared_point = sender_key.to_encoded_point(false);
let shared_secret = {
// Derive shared secret using ECDH
let recipient_secret = EphemeralSecret::random(&mut OsRng);
let shared_secret = recipient_secret.diffie_hellman(&sender_key.to_public_key());
// Derive decryption key from the shared secret (using the same method as encryption)
let decryption_key = {
let mut hasher = Sha256::default();
hasher.update(self.signing_key.to_bytes());
hasher.update(shared_point.as_bytes());
hasher.update(shared_secret.raw_secret_bytes());
hasher.finalize().to_vec()
};
// Decrypt the message using the derived key
implementation::decrypt_with_key(&shared_secret, actual_ciphertext)
implementation::decrypt_with_key(&decryption_key, actual_ciphertext)
.map_err(|e| CryptoError::DecryptionFailed(e.to_string()))
}
}