1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Copyright 2015-2016 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND AND THE AUTHORS DISCLAIM ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

//! Public key signatures: signing and verification.
//!
//! Use the `verify` function to verify signatures, passing a reference to the
//! algorithm that identifies the algorithm. See the documentation for `verify`
//! for examples.
//!
//! For signature verification, this API treats each combination of parameters
//! as a separate algorithm. For example, instead of having a single "RSA"
//! algorithm with a verification function that takes a bunch of parameters,
//! there are `RSA_PKCS1_2048_8192_SHA256`, `RSA_PKCS1_2048_8192_SHA384`, etc.,
//! which encode sets of parameter choices into objects. This is designed to
//! reduce the risks of algorithm agility and to provide consistency with ECDSA
//! and EdDSA.
//!
//! Currently this module does not support digesting the message to be signed
//! separately from the public key operation, as it is currently being
//! optimized for Ed25519 and for the implementation of protocols that do not
//! requiring signing large messages. An interface for efficiently supporting
//! larger messages may be added later.
//!
//! # Examples
//!
//! ## Signing and verifying with Ed25519
//!
//! ```
//! extern crate ring;
//! extern crate untrusted;
//!
//! use ring::{rand, signature};
//!
//! # fn sign_and_verify_ed25519() -> Result<(), ring::error::Unspecified> {
//! // Generate a key pair.
//! let rng = rand::SystemRandom::new();
//! let (generated, generated_bytes) =
//!     try!(signature::Ed25519KeyPair::generate_serializable(&rng));
//!
//! // Normally after generating the key pair, the application would extract
//! // the private and public components and store them persistently for future
//! // use.
//!
//! // Normally the application would later deserialize the private and public
//! // key from storage and then create an `Ed25519KeyPair` from the
//! // deserialized bytes.
//! let key_pair =
//!    try!(signature::Ed25519KeyPair::from_bytes(&generated_bytes.private_key,
//!                                               &generated_bytes.public_key));
//!
//! // Sign the message "hello, world".
//! const MESSAGE: &'static [u8] = b"hello, world";
//! let sig = key_pair.sign(MESSAGE);
//!
//! // Normally, an application would extract the bytes of the signature and
//! // send them in a protocol message to the peer(s). Here we just use the
//! // public key from the private key we just generated.
//! let peer_public_key_bytes = &generated_bytes.public_key;
//! let sig_bytes = sig.as_slice();
//!
//! // Verify the signature of the message using the public key. Normally the
//! // verifier of the message would parse the inputs to `signature::verify`
//! // out of the protocol message(s) sent by the signer.
//! let peer_public_key = untrusted::Input::from(peer_public_key_bytes);
//! let msg = untrusted::Input::from(MESSAGE);
//! let sig = untrusted::Input::from(sig_bytes);
//!
//! try!(signature::verify(&signature::ED25519, peer_public_key, msg, sig));
//!
//! # Ok(())
//! # }
//!
//! # fn main() { sign_and_verify_ed25519().unwrap() }
//! ```
//!
//! ## Signing and verifying with RSA (PKCS#1 1.5 padding)
//!
//! RSA signing (but not verification) requires the `rsa_signing` feature to
//! be enabled.
//!
//! ```
//! extern crate ring;
//! extern crate untrusted;
//!
//! use ring::{rand, signature};
//!
//! # #[cfg(all(feature = "rsa_signing", feature = "use_heap"))]
//! # fn sign_and_verify_rsa() -> Result<(), ring::error::Unspecified> {
//!
//! // Create an `RSAKeyPair` from the DER-encoded bytes. This example uses
//! // a 2048-bit key, but larger keys are also supported.
//! let key_bytes_der =
//!    untrusted::Input::from(
//!         include_bytes!("src/rsa/signature_rsa_example_private_key.der"));
//! let key_pair =
//!    try!(signature::RSAKeyPair::from_der(key_bytes_der));
//!
//! // Create a signing state.
//! let key_pair = std::sync::Arc::new(key_pair);
//! let mut signing_state = try!(signature::RSASigningState::new(key_pair));
//!
//! // Sign the message "hello, world", using PKCS#1 v1.5 padding and the
//! // SHA256 digest algorithm.
//! const MESSAGE: &'static [u8] = b"hello, world";
//! let rng = rand::SystemRandom::new();
//! let mut signature = vec![0; signing_state.key_pair().public_modulus_len()];
//! try!(signing_state.sign(&signature::RSA_PKCS1_SHA256, &rng, MESSAGE,
//!                         &mut signature));
//!
//! // Verify the signature.
//! let public_key_bytes_der =
//!     untrusted::Input::from(
//!         include_bytes!("src/rsa/signature_rsa_example_public_key.der"));
//! let message = untrusted::Input::from(MESSAGE);
//! let signature = untrusted::Input::from(&signature);
//! try!(signature::verify(&signature::RSA_PKCS1_2048_8192_SHA256,
//!                        public_key_bytes_der, message, signature));
//! # Ok(())
//! # }
//! #
//! # #[cfg(not(all(feature = "rsa_signing", feature = "use_heap")))]
//! # fn sign_and_verify_rsa() -> Result<(), ring::error::Unspecified> {
//! #     Ok(())
//! # }
//! #
//! # fn main() { sign_and_verify_rsa().unwrap() }
//! ```


use {error, init, private};
use untrusted;

pub use ec::suite_b::ecdsa::{
    ECDSAParameters,

    ECDSA_P256_SHA1_ASN1,
    ECDSA_P256_SHA256_ASN1,
    ECDSA_P256_SHA384_ASN1,
    ECDSA_P256_SHA512_ASN1,

    ECDSA_P384_SHA1_ASN1,
    ECDSA_P384_SHA256_ASN1,
    ECDSA_P384_SHA384_ASN1,
    ECDSA_P384_SHA512_ASN1,
};

pub use ec::eddsa::{
    EdDSAParameters,

    ED25519,

    Ed25519KeyPair,
    Ed25519KeyPairBytes
};

#[cfg(all(feature = "rsa_signing", feature = "use_heap"))]
pub use rsa::signing::{RSAKeyPair, RSASigningState};

#[cfg(all(feature = "rsa_signing", feature = "use_heap"))]
pub use rsa::{
    // `RSA_PKCS1_SHA1` is intentionally not exposed. At a minimum, we'd need
    // to create test vectors for signing with it, which we don't currently
    // have. But, it's a bad idea to use SHA-1 anyway, so perhaps we just won't
    // ever expose it.
    RSA_PKCS1_SHA256,
    RSA_PKCS1_SHA384,
    RSA_PKCS1_SHA512,
};

#[cfg(feature = "use_heap")]
pub use rsa::RSAParameters;

#[cfg(feature = "use_heap")]
pub use rsa::verification::{
    RSA_PKCS1_2048_8192_SHA1,
    RSA_PKCS1_2048_8192_SHA256,
    RSA_PKCS1_2048_8192_SHA384,
    RSA_PKCS1_2048_8192_SHA512,

    RSA_PKCS1_3072_8192_SHA384,
};

/// Lower-level verification primitives. Usage of `ring::signature::verify()`
/// is preferred when the public key and signature are encoded in standard
/// formats, as it also handles the parsing.
pub mod primitive {
    pub use rsa::verification::verify_rsa;
}

/// A public key signature returned from a signing operation.
pub struct Signature {
    value: [u8; 64],
}

impl<'a> Signature {
    // Initialize a 64-byte signature from slice of bytes. XXX: This is public
    // so that other *ring* submodules can use it, but it isn't intended for
    // public use.
    #[doc(hidden)]
    pub fn new(signature_bytes: [u8; 64]) -> Signature {
        Signature { value: signature_bytes }
    }

    /// Returns a reference to the signature's encoded value.
    pub fn as_slice(&'a self) -> &'a [u8] { &self.value[..] }
}

/// A signature verification algorithm.
pub trait VerificationAlgorithm: Sync + private::Private {
    /// Verify the signature `signature` of message `msg` with the public key
    /// `public_key`.
    fn verify(&self, public_key: untrusted::Input, msg: untrusted::Input,
              signature: untrusted::Input) -> Result<(), error::Unspecified>;
}

/// Verify the signature `signature` of message `msg` with the public key
/// `public_key` using the algorithm `alg`.
///
/// # Examples
///
/// ## Verify a RSA PKCS#1 signature that uses the SHA-256 digest
///
/// ```
/// extern crate ring;
/// extern crate untrusted;
///
/// use ring::signature;
///
/// enum Error {
///     InvalidSignature,
/// }
///
/// # #[cfg(feature = "use_heap")]
/// fn verify_rsa_pkcs1_sha256(public_key: untrusted::Input,
///                            msg: untrusted::Input, sig: untrusted::Input)
///                            -> Result<(), Error> {
///    signature::verify(&signature::RSA_PKCS1_2048_8192_SHA256, public_key,
///                      msg, sig).map_err(|_| Error::InvalidSignature)
/// }
/// # fn main() { }
/// ```
pub fn verify(alg: &VerificationAlgorithm, public_key: untrusted::Input,
              msg: untrusted::Input, signature: untrusted::Input)
              -> Result<(), error::Unspecified> {
    init::init_once();
    alg.verify(public_key, msg, signature)
}


#[cfg(test)]
mod tests {
    // ECDSA tests are in crypto/ec/ecdsa.rs.
    // EdDSA tests are in crypto/ec/eddsa.rs.
}