Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 57 additions & 29 deletions ed25519/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")]
#![allow(non_snake_case)]
#![forbid(unsafe_code)]
#![warn(
clippy::unwrap_used,
Expand Down Expand Up @@ -276,23 +277,32 @@ use core::{fmt, str};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;

/// Length of an Ed25519 signature in bytes.
#[deprecated(since = "1.3.0", note = "use ed25519::Signature::BYTE_SIZE instead")]
pub const SIGNATURE_LENGTH: usize = Signature::BYTE_SIZE;

/// Ed25519 signature serialized as a byte array.
pub type SignatureBytes = [u8; Signature::BYTE_SIZE];

/// Size of an `R` or `s` component of an Ed25519 signature when serialized
/// as bytes.
pub type ComponentBytes = [u8; COMPONENT_SIZE];

/// Size of a single component of an Ed25519 signature.
const COMPONENT_SIZE: usize = 32;

/// Ed25519 signature.
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Signature(SignatureBytes);
#[repr(C)]
pub struct Signature {
R: ComponentBytes,
s: ComponentBytes,
}

impl Signature {
/// Size of an encoded Ed25519 signature in bytes.
pub const BYTE_SIZE: usize = 64;
pub const BYTE_SIZE: usize = COMPONENT_SIZE * 2;

/// Parse an Ed25519 signature from a byte slice.
pub fn from_bytes(bytes: &[u8; Self::BYTE_SIZE]) -> signature::Result<Self> {
let (R, s) = bytes.split_at(COMPONENT_SIZE);

// Perform a partial reduction check on the signature's `s` scalar.
// When properly reduced, at least the three highest bits of the scalar
// will be unset so as to fit within the order of ~2^(252.5).
Expand All @@ -301,49 +311,60 @@ impl Signature {
// full reduction check in the event that the 4th most significant bit
// is set), however it will catch a number of invalid signatures
// relatively inexpensively.
if bytes[Signature::BYTE_SIZE - 1] & 0b1110_0000 != 0 {
if s[COMPONENT_SIZE - 1] & 0b1110_0000 != 0 {
return Err(Error::new());
}

Ok(Self(*bytes))
Ok(Self {
R: R.try_into().map_err(|_| Error::new())?,
s: s.try_into().map_err(|_| Error::new())?,
})
}

/// Bytes for the `R` component of a signature.
pub fn r_bytes(&self) -> &ComponentBytes {
&self.R
}

/// Bytes for the `s` component of a signature.
pub fn s_bytes(&self) -> &ComponentBytes {
&self.s
}

/// Return the inner byte array.
pub fn to_bytes(self) -> [u8; Self::BYTE_SIZE] {
self.0
pub fn to_bytes(&self) -> SignatureBytes {
let mut ret = [0u8; Self::BYTE_SIZE];
let (R, s) = ret.split_at_mut(COMPONENT_SIZE);
R.copy_from_slice(&self.R);
s.copy_from_slice(&self.s);
ret
}

/// Convert this signature into a byte vector.
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn to_vec(&self) -> Vec<u8> {
self.0.to_vec()
self.to_bytes().to_vec()
}
}

impl SignatureEncoding for Signature {
type Repr = SignatureBytes;

fn to_bytes(&self) -> SignatureBytes {
self.0
self.to_bytes()
}
}

impl AsRef<[u8]> for Signature {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
impl From<Signature> for SignatureBytes {
fn from(sig: Signature) -> SignatureBytes {
sig.to_bytes()
}
}

impl From<Signature> for [u8; Signature::BYTE_SIZE] {
fn from(sig: Signature) -> [u8; Signature::BYTE_SIZE] {
sig.0
}
}

impl From<&Signature> for [u8; Signature::BYTE_SIZE] {
fn from(sig: &Signature) -> [u8; Signature::BYTE_SIZE] {
sig.0
impl From<&Signature> for SignatureBytes {
fn from(sig: &Signature) -> SignatureBytes {
sig.to_bytes()
}
}

Expand All @@ -357,7 +378,10 @@ impl TryFrom<&[u8]> for Signature {

impl fmt::Debug for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ed25519::Signature({})", self)
f.debug_struct("ed25519::Signature")
.field("R", self.r_bytes())
.field("s", self.s_bytes())
.finish()
}
}

Expand All @@ -369,17 +393,21 @@ impl fmt::Display for Signature {

impl fmt::LowerHex for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in &self.0 {
write!(f, "{:02x}", byte)?;
for component in [&self.R, &self.s] {
for byte in component {
write!(f, "{:02x}", byte)?;
}
}
Ok(())
}
}

impl fmt::UpperHex for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for byte in &self.0 {
write!(f, "{:02X}", byte)?;
for component in [&self.R, &self.s] {
for byte in component {
write!(f, "{:02X}", byte)?;
}
}
Ok(())
}
Expand Down
14 changes: 7 additions & 7 deletions ed25519/src/serde.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! `serde` support.

use crate::Signature;
use crate::{Signature, SignatureBytes};
use ::serde::{de, ser, Deserialize, Serialize};
use core::fmt;

Expand All @@ -14,8 +14,8 @@ impl Serialize for Signature {

let mut seq = serializer.serialize_tuple(Signature::BYTE_SIZE)?;

for byte in &self.0[..] {
seq.serialize_element(byte)?;
for byte in self.to_bytes() {
seq.serialize_element(&byte)?;
}

seq.end()
Expand Down Expand Up @@ -65,7 +65,7 @@ impl serde_bytes::Serialize for Signature {
where
S: serde::Serializer,
{
serializer.serialize_bytes(&self.0)
serializer.serialize_bytes(&self.to_bytes())
}
}

Expand All @@ -79,7 +79,7 @@ impl<'de> serde_bytes::Deserialize<'de> for Signature {
struct ByteArrayVisitor;

impl<'de> de::Visitor<'de> for ByteArrayVisitor {
type Value = [u8; Signature::BYTE_SIZE];
type Value = SignatureBytes;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("bytestring of length 64")
Expand All @@ -104,10 +104,10 @@ impl<'de> serde_bytes::Deserialize<'de> for Signature {

#[cfg(test)]
mod tests {
use crate::Signature;
use crate::{Signature, SignatureBytes};
use hex_literal::hex;

const SIGNATURE_BYTES: [u8; Signature::BYTE_SIZE] = hex!(
const SIGNATURE_BYTES: SignatureBytes = hex!(
"
e5564300c360ac729086e2cc806e828a
84877f1eb8e5d974d873e06522490155
Expand Down
4 changes: 2 additions & 2 deletions ed25519/tests/hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ fn upper_hex() {
#[test]
fn from_str_lower() {
let sig = Signature::from_str("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b").unwrap();
assert_eq!(sig.as_ref(), TEST_1_SIGNATURE);
assert_eq!(sig.to_bytes(), TEST_1_SIGNATURE);
}

#[test]
fn from_str_upper() {
let sig = Signature::from_str("E5564300C360AC729086E2CC806E828A84877F1EB8E5D974D873E065224901555FB8821590A33BACC61E39701CF9B46BD25BF5F0595BBE24655141438E7A100B").unwrap();
assert_eq!(sig.as_ref(), TEST_1_SIGNATURE);
assert_eq!(sig.to_bytes(), TEST_1_SIGNATURE);
}

#[test]
Expand Down
16 changes: 8 additions & 8 deletions ed25519/tests/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

#![cfg(feature = "serde")]

use ed25519::Signature;
use ed25519::{Signature, SignatureBytes};
use hex_literal::hex;

#[cfg(feature = "serde_bytes")]
use serde_bytes_crate as serde_bytes;

const EXAMPLE_SIGNATURE: [u8; Signature::BYTE_SIZE] = [
63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40,
39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16,
15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
];
const EXAMPLE_SIGNATURE: SignatureBytes = hex!(
"3f3e3d3c3b3a393837363534333231302f2e2d2c2b2a29282726252423222120"
"1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100"
);

#[test]
fn test_serialize() {
Expand All @@ -23,7 +23,7 @@ fn test_serialize() {
#[test]
fn test_deserialize() {
let signature = bincode::deserialize::<Signature>(&EXAMPLE_SIGNATURE).unwrap();
assert_eq!(&EXAMPLE_SIGNATURE[..], signature.as_ref());
assert_eq!(EXAMPLE_SIGNATURE, signature.to_bytes());
}

#[cfg(feature = "serde_bytes")]
Expand Down Expand Up @@ -60,5 +60,5 @@ fn test_deserialize_bytes() {

let signature: Signature = serde_bytes::deserialize(&mut deserializer).unwrap();

assert_eq!(&EXAMPLE_SIGNATURE[..], signature.as_ref());
assert_eq!(EXAMPLE_SIGNATURE, signature.to_bytes());
}