use base64ct::{Base64Unpadded, Encoding as _};
use curve25519_dalek::Scalar;
use derive_deftly::Deftly;
use std::fmt::{self, Debug, Display, Formatter};
use subtle::{Choice, ConstantTimeEq};
#[cfg(feature = "memquota-memcost")]
use tor_memquota_cost::derive_deftly_template_HasMemoryCost;
use ed25519_dalek::hazmat::ExpandedSecretKey;
use ed25519_dalek::{Signer as _, Verifier as _};
use crate::util::{
ct::{
CtByteArray, derive_deftly_template_ConstantTimeEq,
derive_deftly_template_PartialEqFromCtEq,
},
rng::RngCompat,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Signature(pub(crate) ed25519_dalek::Signature);
#[derive(Debug, Deftly)]
#[derive_deftly(ConstantTimeEq)]
pub struct Keypair(pub(crate) ed25519_dalek::SigningKey);
#[derive(Clone, Copy, Debug, Eq, Deftly)]
#[derive_deftly(PartialEqFromCtEq)]
pub struct PublicKey(pub(crate) ed25519_dalek::VerifyingKey);
impl<'a> From<&'a Keypair> for PublicKey {
fn from(value: &'a Keypair) -> Self {
PublicKey((&value.0).into())
}
}
impl ConstantTimeEq for PublicKey {
fn ct_eq(&self, other: &Self) -> Choice {
self.as_bytes().ct_eq(other.as_bytes())
}
}
impl PublicKey {
pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, signature::Error> {
Ok(PublicKey(ed25519_dalek::VerifyingKey::from_bytes(bytes)?))
}
pub fn as_bytes(&self) -> &[u8; 32] {
self.0.as_bytes()
}
pub fn to_bytes(&self) -> [u8; 32] {
self.0.to_bytes()
}
pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), signature::Error> {
self.0.verify(message, &signature.0)
}
}
impl Keypair {
pub fn generate<R: rand_core::RngCore + rand_core::CryptoRng>(csprng: &mut R) -> Self {
Self(ed25519_dalek::SigningKey::generate(&mut RngCompat::new(
csprng,
)))
}
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
Self(ed25519_dalek::SigningKey::from_bytes(bytes))
}
pub fn as_bytes(&self) -> &[u8; 32] {
self.0.as_bytes()
}
pub fn to_bytes(&self) -> [u8; 32] {
self.0.to_bytes()
}
pub fn verifying_key(&self) -> PublicKey {
PublicKey(*self.0.as_ref())
}
pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), signature::Error> {
self.0.verify(message, &signature.0)
}
pub fn sign(&self, message: &[u8]) -> Signature {
Signature(self.0.sign(message))
}
}
impl Signature {
pub fn from_bytes(bytes: &[u8; 64]) -> Self {
Self(ed25519_dalek::Signature::from_bytes(bytes))
}
pub fn to_bytes(&self) -> [u8; 64] {
self.0.to_bytes()
}
}
impl<'a> TryFrom<&'a [u8]> for PublicKey {
type Error = signature::Error;
fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
Ok(Self(ed25519_dalek::VerifyingKey::try_from(value)?))
}
}
impl<'a> From<&'a [u8; 32]> for Keypair {
fn from(value: &'a [u8; 32]) -> Self {
Self(ed25519_dalek::SigningKey::from(value))
}
}
impl From<[u8; 64]> for Signature {
fn from(value: [u8; 64]) -> Self {
Signature(value.into())
}
}
impl<'a> From<&'a [u8; 64]> for Signature {
fn from(value: &'a [u8; 64]) -> Self {
Signature(value.into())
}
}
pub const ED25519_ID_LEN: usize = 32;
pub const ED25519_SIGNATURE_LEN: usize = 64;
#[allow(clippy::exhaustive_structs)]
#[derive(Deftly)]
#[derive_deftly(ConstantTimeEq)]
pub struct ExpandedKeypair {
pub(crate) secret: ExpandedSecretKey,
pub(crate) public: PublicKey,
}
impl ExpandedKeypair {
pub fn public(&self) -> &PublicKey {
&self.public
}
pub fn sign(&self, message: &[u8]) -> Signature {
use sha2::Sha512;
Signature(ed25519_dalek::hazmat::raw_sign::<Sha512>(
&self.secret,
message,
&self.public.0,
))
}
pub fn to_secret_key_bytes(&self) -> [u8; 64] {
let mut output = [0_u8; 64];
output[0..32].copy_from_slice(&self.secret.scalar.to_bytes());
output[32..64].copy_from_slice(&self.secret.hash_prefix);
output
}
pub fn from_secret_key_bytes(bytes: [u8; 64]) -> Option<Self> {
let scalar = Option::from(Scalar::from_bytes_mod_order(
bytes[0..32].try_into().expect("wrong length on slice"),
))?;
let hash_prefix = bytes[32..64].try_into().expect("wrong length on slice");
let secret = ExpandedSecretKey {
scalar,
hash_prefix,
};
let public = PublicKey((&secret).into());
Some(Self { secret, public })
}
}
impl<'a> From<&'a Keypair> for ExpandedKeypair {
fn from(kp: &'a Keypair) -> ExpandedKeypair {
ExpandedKeypair {
secret: kp.as_bytes().into(),
public: kp.into(),
}
}
}
impl From<ExpandedKeypair> for PublicKey {
fn from(ekp: ExpandedKeypair) -> PublicKey {
ekp.public
}
}
#[derive(Clone, Copy, Hash, PartialOrd, Ord, Eq, PartialEq)]
#[cfg_attr(
feature = "memquota-memcost",
derive(Deftly),
derive_deftly(HasMemoryCost)
)]
pub struct Ed25519Identity {
id: CtByteArray<ED25519_ID_LEN>,
}
impl Ed25519Identity {
pub fn new(id: [u8; 32]) -> Self {
Ed25519Identity { id: id.into() }
}
pub fn from_bytes(id: &[u8]) -> Option<Self> {
Some(Ed25519Identity::new(id.try_into().ok()?))
}
pub fn as_bytes(&self) -> &[u8] {
&self.id.as_ref()[..]
}
pub fn from_base64(s: &str) -> Option<Self> {
let bytes = Base64Unpadded::decode_vec(s).ok()?;
Ed25519Identity::from_bytes(&bytes)
}
}
impl From<[u8; ED25519_ID_LEN]> for Ed25519Identity {
fn from(id: [u8; ED25519_ID_LEN]) -> Self {
Ed25519Identity::new(id)
}
}
impl From<Ed25519Identity> for [u8; ED25519_ID_LEN] {
fn from(value: Ed25519Identity) -> Self {
value.id.into()
}
}
impl From<PublicKey> for Ed25519Identity {
fn from(pk: PublicKey) -> Self {
(&pk).into()
}
}
impl From<&PublicKey> for Ed25519Identity {
fn from(pk: &PublicKey) -> Self {
Ed25519Identity::from_bytes(pk.as_bytes()).expect("Ed25519 public key had wrong length?")
}
}
impl TryFrom<&Ed25519Identity> for PublicKey {
type Error = ed25519_dalek::SignatureError;
fn try_from(id: &Ed25519Identity) -> Result<PublicKey, Self::Error> {
PublicKey::from_bytes(id.id.as_ref())
}
}
impl TryFrom<Ed25519Identity> for PublicKey {
type Error = ed25519_dalek::SignatureError;
fn try_from(id: Ed25519Identity) -> Result<PublicKey, Self::Error> {
(&id).try_into()
}
}
impl ConstantTimeEq for Ed25519Identity {
fn ct_eq(&self, other: &Self) -> Choice {
self.id.ct_eq(&other.id)
}
}
impl Display for Ed25519Identity {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", Base64Unpadded::encode_string(self.id.as_ref()))
}
}
impl Debug for Ed25519Identity {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Ed25519Identity {{ {} }}", self)
}
}
impl safelog::Redactable for Ed25519Identity {
fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}…",
&Base64Unpadded::encode_string(self.id.as_ref())[..2]
)
}
fn debug_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Ed25519Identity {{ {} }}", self.redacted())
}
}
impl serde::Serialize for Ed25519Identity {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if serializer.is_human_readable() {
serializer.serialize_str(&Base64Unpadded::encode_string(self.id.as_ref()))
} else {
serializer.serialize_bytes(&self.id.as_ref()[..])
}
}
}
impl<'de> serde::Deserialize<'de> for Ed25519Identity {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
if deserializer.is_human_readable() {
struct EdIdentityVisitor;
impl<'de> serde::de::Visitor<'de> for EdIdentityVisitor {
type Value = Ed25519Identity;
fn expecting(&self, fmt: &mut std::fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("base64-encoded Ed25519 public key")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let bytes = Base64Unpadded::decode_vec(s).map_err(E::custom)?;
Ed25519Identity::from_bytes(&bytes)
.ok_or_else(|| E::custom("wrong length for Ed25519 public key"))
}
}
deserializer.deserialize_str(EdIdentityVisitor)
} else {
struct EdIdentityVisitor;
impl<'de> serde::de::Visitor<'de> for EdIdentityVisitor {
type Value = Ed25519Identity;
fn expecting(&self, fmt: &mut std::fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("ed25519 public key")
}
fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ed25519Identity::from_bytes(bytes)
.ok_or_else(|| E::custom("wrong length for ed25519 public key"))
}
}
deserializer.deserialize_bytes(EdIdentityVisitor)
}
}
}
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "memquota-memcost",
derive(Deftly),
derive_deftly(HasMemoryCost)
)]
pub struct ValidatableEd25519Signature {
#[cfg_attr(feature = "memquota-memcost", deftly(has_memory_cost(copy)))]
key: PublicKey,
#[cfg_attr(feature = "memquota-memcost", deftly(has_memory_cost(copy)))]
sig: Signature,
entire_text_of_signed_thing: Vec<u8>,
}
impl ValidatableEd25519Signature {
pub fn new(key: PublicKey, sig: Signature, text: &[u8]) -> Self {
ValidatableEd25519Signature {
key,
sig,
entire_text_of_signed_thing: text.into(),
}
}
pub(crate) fn as_parts(&self) -> (&PublicKey, &Signature, &[u8]) {
(&self.key, &self.sig, &self.entire_text_of_signed_thing[..])
}
pub fn signature(&self) -> &Signature {
&self.sig
}
}
impl super::ValidatableSignature for ValidatableEd25519Signature {
fn is_valid(&self) -> bool {
self.key
.verify(&self.entire_text_of_signed_thing[..], &self.sig)
.is_ok()
}
fn as_ed25519(&self) -> Option<&ValidatableEd25519Signature> {
Some(self)
}
}
pub fn validate_batch(sigs: &[&ValidatableEd25519Signature]) -> bool {
use crate::pk::ValidatableSignature;
if sigs.is_empty() {
true
} else if sigs.len() == 1 {
sigs[0].is_valid()
} else {
let mut ed_msgs = Vec::new();
let mut ed_sigs = Vec::new();
let mut ed_pks = Vec::new();
for ed_sig in sigs {
let (pk, sig, msg) = ed_sig.as_parts();
ed_sigs.push(sig.0);
ed_pks.push(pk.0);
ed_msgs.push(msg);
}
ed25519_dalek::verify_batch(&ed_msgs[..], &ed_sigs[..], &ed_pks[..]).is_ok()
}
}
pub trait Ed25519PublicKey {
fn public_key(&self) -> PublicKey;
}
impl Ed25519PublicKey for Keypair {
fn public_key(&self) -> PublicKey {
Keypair::verifying_key(self)
}
}
pub trait Ed25519SigningKey {
fn sign(&self, message: &[u8]) -> Signature;
}
impl Ed25519SigningKey for Keypair {
fn sign(&self, message: &[u8]) -> Signature {
Keypair::sign(self, message)
}
}
impl Ed25519SigningKey for ExpandedKeypair {
fn sign(&self, message: &[u8]) -> Signature {
ExpandedKeypair::sign(self, message)
}
}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_time_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
use super::*;
#[test]
fn ed_from_base64() {
let id =
Ed25519Identity::from_base64("qpL/LxLYVEXghU76iG3LsSI/UW7MBpIROZK0AB18560").unwrap();
assert_eq!(
id,
Ed25519Identity::from([
0xaa, 0x92, 0xff, 0x2f, 0x12, 0xd8, 0x54, 0x45, 0xe0, 0x85, 0x4e, 0xfa, 0x88, 0x6d,
0xcb, 0xb1, 0x22, 0x3f, 0x51, 0x6e, 0xcc, 0x06, 0x92, 0x11, 0x39, 0x92, 0xb4, 0x00,
0x1d, 0x7c, 0xe7, 0xad
]),
);
}
}