--- /dev/null
+/target/
+**/*.rs.bk
+Cargo.lock
--- /dev/null
+language: rust
+rust:
+ - stable
+ - beta
+ - nightly
+matrix:
+ allow_failures:
+ - rust: nightly
+script: cargo test --release --verbose
--- /dev/null
+[package]
+name = "srp"
+version = "0.1.0"
+authors = ["RustCrypto Developers"]
+
+[dependencies]
+num = "*"
+generic-array = "*"
+rand = "0.3"
+digest = "*"
+
+[dev-dependencies]
+sha2 = "*"
--- /dev/null
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
--- /dev/null
+Copyright (c) 2017 Artyom Pavlov
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
--- /dev/null
+# SRP [![Build Status](https://travis-ci.org/RustCrypto/SRP.svg?branch=master)](https://travis-ci.org/RustCrypto/SRP) [![crates.io](https://img.shields.io/crates/v/srp.svg)](https://crates.io/crates/srp) [![Documentation](https://docs.rs/srp/badge.svg)](https://docs.rs/srp)
+[Secure Remote Password][1] (SRP) protocol implementation.
+
+This implementation uses little-endian representation of big integers and is
+generic over hash functions using [`Digest`][2] trait, so you will need to
+choose a hash function, e.g. `Sha256` from [`sha2`][3] crate. Additionally this
+crate allows to use a specialized password hashing algorithms for private key
+computation instead of method described in the SRP literature.
+
+Currently compatability with over implementations was not tested.
+
+## Warnings
+
+This crate have not yet received any formal cryptographic and security reviews.
+
+No efforts were yet taken in regards of [blinding][4] or erasing secrets from
+the memory.
+
+**USE AT YOUR OWN RISK.**
+
+## License
+
+This crate licensed under either of
+
+ * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
+ * [MIT license](http://opensource.org/licenses/MIT)
+
+at your option.
+
+
+[1]: https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol
+[2]: https://crates.io/crates/digest
+[3]: https://crates.io/crates/sha2
+[4]: https://en.wikipedia.org/wiki/Blinding_(cryptography)
\ No newline at end of file
--- /dev/null
+//! SRP client implementation.
+//!
+//! # Usage
+//! First create SRP client struct by passing to it SRP parameters (shared
+//! between client and server) and RNG instance (OS RNG is recommended):
+//!
+//! ```ignore
+//! let srp_params = SrpParams{n, g, k};
+//! let mut rng = rand::os::OsRng::new().unwrap();
+//! let client = SrpClient::<Sha256>::new(&srp_params, &mut rng);
+//! ```
+//!
+//! Next send handshake data (username and `a_pub`) to the server and receive
+//! `salt` and `b_pub`:
+//!
+//! ```ignore
+//! let a_pub = client.get_a_pub();
+//! let (salt, b_pub) = conn.send_handshake(username, a_pub);
+//! ```
+//!
+//! Compute private key using `salt` with any password hashing function.
+//! You can use method from SRP-6a, but it's recommended to use specialized
+//! password hashing algorithm instead (e.g. PBKDF2, argon2 or scrypt).
+//! Next create verifier instance, note that `get_verifier` consumes client and
+//! can return error in case of malicious `b_pub`.
+//!
+//! ```ignore
+//! let private_key = srp6a_private_key::<Sha256>(username, password, salt);
+//! let verifier = client.get_verifier(&private_key, &b_pub)?;
+//! ```
+//!
+//! Finally verify the server: first generate user proof,
+//! send it to the server and verify server proof in the reply. Note that
+//! `verify_server` method will return error in case of incorrect server reply.
+//!
+//! ```ignore
+//! let user_proof = verifier.get_proof();
+//! let server_proof = conn.send_proof(user_proof);
+//! let key = verifier.verify_server(server_proof)?;
+//! ```
+//!
+//! `key` contains shared secret key between user and the server. Alternatively
+//! you can directly extract shared secret key using `get_key()` method and
+//! handle authentification through different (secure!) means (e.g. by using
+//! authentificated cipher mode).
+//!
+//! For user registration on the server first generate salt (e.g. 32 bytes long)
+//! and get password verifier which depends on private key. Send useranme, salt
+//! and password verifier over protected channel to protect against MitM for
+//! registration.
+//!
+//! ```ignore
+//! let pwd_verifier = SrpClient::<Sha256>::register(&private_key, &srp_params);
+//! conn.send_registration_data(username, salt, pwd_verifier);
+//! ```
+use std::marker::PhantomData;
+
+use rand::Rng;
+use num::{BigUint, Zero};
+use digest::Digest;
+use generic_array::GenericArray;
+
+use tools::powm;
+use types::{SrpAuthError, SrpParams};
+
+/// SRP client state before handshake with the server.
+pub struct SrpClient<'a, D: Digest> {
+ params: &'a SrpParams,
+
+ a: BigUint,
+ a_pub: BigUint,
+
+ d: PhantomData<D>
+}
+
+/// SRP client state after handshake with the server.
+pub struct SrpClientVerifier<D: Digest> {
+ proof: GenericArray<u8, D::OutputSize>,
+ server_proof: GenericArray<u8, D::OutputSize>,
+ key: GenericArray<u8, D::OutputSize>,
+}
+
+/// Compute user private key as described in the SRP6a. Consider using proper
+/// password hashing algorithm instead.
+pub fn srp6a_private_key<D: Digest>(username: &[u8], password: &[u8],
+ salt: &[u8]
+ ) -> GenericArray<u8, D::OutputSize>
+{
+ let p = {
+ let mut d = D::new();
+ d.input(username);
+ d.input(b":");
+ d.input(password);
+ d.result()
+ };
+ let mut d = D::new();
+ d.input(salt);
+ d.input(&p);
+ d.result()
+}
+
+impl<'a, D: Digest> SrpClient<'a, D> {
+ /// Create new SRP client instance.
+ pub fn new<R: Rng>(params: &'a SrpParams, rng: &mut R) -> Self {
+ let l = params.n.bits()/8;
+ let buf = rng.gen_iter::<u8>().take(l).collect::<Vec<u8>>();
+ let a = BigUint::from_bytes_le(&buf);
+ let a_pub = params.powm(&a);
+
+ Self { params, a, a_pub, d: Default::default() }
+ }
+
+ /// Get password verfier for user registration on the server
+ pub fn get_password_verifier(&self, private_key: &[u8]) -> Vec<u8> {
+ let x = BigUint::from_bytes_le(&private_key);
+ let v = self.params.powm(&x);
+ v.to_bytes_le()
+ }
+
+ fn calc_key(&self, b_pub: &BigUint, x: &BigUint, u: &BigUint)
+ -> GenericArray<u8, D::OutputSize>
+ {
+ let n = &self.params.n;
+ let interm = (&self.params.k * self.params.powm(x)) % n;
+ // Because we do operation in modulo N we can get: (kv + g^b) < kv
+ let v = if b_pub > &interm {
+ (b_pub - &interm) % n
+ } else {
+ (n + b_pub - &interm) % n
+ };
+ // S = |B - kg^x| ^ (a + ux)
+ let s = powm(&v, &(&self.a + (u*x) % n ), n);
+ D::digest(&s.to_bytes_le())
+ }
+
+ /// Process server reply to the handshake.
+ pub fn process_reply(self, private_key: &[u8], b_pub: &[u8])
+ -> Result<SrpClientVerifier<D>, SrpAuthError>
+ {
+ let u = {
+ let mut d = D::new();
+ d.input(&self.a_pub.to_bytes_le());
+ d.input(b_pub);
+ BigUint::from_bytes_le(&d.result())
+ };
+
+ let b_pub = BigUint::from_bytes_le(b_pub);
+
+ // Safeguard against malicious B
+ if &b_pub % &self.params.n == BigUint::zero() {
+ return Err(SrpAuthError{ description: "Malicious b_pub value" })
+ }
+
+ let x = BigUint::from_bytes_le(&private_key);
+ let key = self.calc_key(&b_pub, &x, &u);
+ // M1 = H(A, B, K)
+ let proof = {
+ let mut d = D::new();
+ d.input(&self.a_pub.to_bytes_le());
+ d.input(&b_pub.to_bytes_le());
+ d.input(&key);
+ d.result()
+ };
+
+ // M2 = H(A, M1, K)
+ let server_proof = {
+ let mut d = D::new();
+ d.input(&self.a_pub.to_bytes_le());
+ d.input(&proof);
+ d.input(&key);
+ d.result()
+ };
+
+ Ok(SrpClientVerifier {
+ proof: proof,
+ server_proof: server_proof,
+ key: key,
+ })
+ }
+
+ /// Get public ephemeral value for handshaking with the server.
+ pub fn get_a_pub(&self) -> Vec<u8> {
+ self.a_pub.to_bytes_le()
+ }
+}
+
+impl<D: Digest> SrpClientVerifier<D> {
+ /// Get shared secret key without authenticating server, e.g. for using with
+ /// authenticated encryption modes. DO NOT USE this method without
+ /// some kind of secure authentification.
+ pub fn get_key(self) -> GenericArray<u8, D::OutputSize> {
+ self.key
+ }
+
+ /// Verification data for sending to the server.
+ pub fn get_proof(&self) -> GenericArray<u8, D::OutputSize> {
+ self.proof.clone()
+ }
+
+ /// Verify server reply to verification data. It will return shared secret
+ /// key in case of success.
+ pub fn verify_server(self, reply: &[u8])
+ -> Result<GenericArray<u8, D::OutputSize>, SrpAuthError>
+ {
+ if self.server_proof.as_slice() != reply {
+ Err(SrpAuthError{ description: "Incorrect server proof" })
+ } else {
+ Ok(self.key)
+ }
+ }
+}
--- /dev/null
+//! [Secure Remote Password][1] (SRP) protocol implementation.
+//!
+//! This implementation uses little-endian serialization of big integers and is
+//! generic over hash functions using `Digest` trait, so you will need to choose
+//! a hash function, e.g. `Sha256` from `sha2` crate. Additionally this crate
+//! allows to use a specialized password hashing algorithms for private key
+//! computation instead of method described in the SRP literature.
+//!
+//! Currently compatability with over implementations was not tested.
+//!
+//! # Algorithm description
+//! Here we briefly describe implemented algroithm. For additionall information
+//! refer to SRP literature. All arithmetic is done modulo `N`, where `N` is a
+//! large safe prime (`N = 2q+1`, where `q` is prime).
+//!
+//! Client | | Server
+//! -------|-------|--------
+//! | — `I` —> | (lookup `s`, `v`)
+//! `x = PH(P, s)` | <— `s`, `v` — |
+//! `a_pub = g^a` | — `a_pub` —> | `b_pub = k*v + g^b`
+//! `u = H(a_pub || b_pub)` | <— `b_pub` — | `u = H(a_pub || b_pub)`
+//! `s = (b_pub - k*g^x)^(a+u*x)` | | `S = (b_pub - k*g^x)^(a+u*x)`
+//! `K = H(s)` | | `K = H(s)`
+//! `M1 = H(A || B || K)` | — `M1` —> | (verify `M1`)
+//! (verify `M2`) | <— `M2` — | `M2 = H(A || M1 || K)`
+//!
+//! `||` denotes concatenation, variables and notations have the following
+//! meaning:
+//!
+//! - `I` — user identity (username)
+//! - `P` — user password
+//! - `H` — one-way hash function
+//! - `HP` — password hashing algroithm, in the SRP described as
+//! `H(s || I || P)` or `H(s || P)`
+//! - `^` — (modular) exponentiation
+//! - `x` — user private key
+//! - `s` — salt generated by user and stored on the server
+//! - `v` — password verifier equal to `g^x` and stored on the server
+//! - `a`, `b` — secret ephemeral values
+//! - `A`, `B` — Public ephemeral values
+//! - `u` — scrambling parameter
+//! - `g` — a generator modulo `N`
+//! - `k` — multiplier parameter (`k = H(N || g)` in SRP-6a)
+//!
+//! [1]: https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol
+extern crate num;
+extern crate digest;
+extern crate generic_array;
+extern crate rand;
+
+mod tools;
+pub mod client;
+pub mod server;
+pub mod types;
+
+/// 1024 bit prime number which can be used as `n` in the `SrpParams`.
+///
+/// For conversion to `BigUint` use `BigUint::from_bytes_le(SRP_PRIME)`.
+pub const PRIME: &'static [u8] = include_bytes!("prime.bin");
--- /dev/null
+ã_\88\vP<ÊÔÐ=\9cè\13yC\18\16p^ >H\9ah\84w\rÃâ¼Bñè\18b{+\162\ 5,Z\9bu\9a©HEX«øõÉrç\1cÓ\8b\15tý×\7fÑo\1f Ç'³ßTw¿¸§ü;¦\86äª\97\81D\88ýl'$ ¿Óð2\12\eÂ/\fA\8a-í\8ftùc\1a¸¤\eK2£-\1cæ\87\982´\88uÃ7À
\ No newline at end of file
--- /dev/null
+//! SRP server implementation
+//!
+//! # Usage
+//! First receive user's username and public value `a_pub`, retrieve from a
+//! database `UserRecord` for a given username and initialize SRP server state:
+//!
+//! ```ignore
+//! let mut rng = rand::os::OsRng::new().unwrap();
+//! let (username, a_pub) = conn.receive_handshake();
+//! let user = db.retrieve_user_record(username);
+//! let server = SrpServer::<Sha256>::new(&user, &a_pub, &srp_params, &mut rng)?;
+//! ```
+//!
+//! Next send to user `b_pub` and `salt` from user record:
+//!
+//! ```ignore
+//! let b_pub = server.get_b_pub();
+//! conn.reply_to_handshake(&user.salt, b_pub);
+//! ```
+//!
+//! And finally recieve user proof, verify it and send server proof as reply:
+//!
+//! ```ignore
+//! let user_proof = conn.receive_proof();
+//! let server_proof = server.verify(user_proof)?;
+//! conn.send_proof(server_proof);
+//! ```
+//!
+//! To get the shared secret use `get_key` method. As alternative to using
+//! `verify` method it's also possible to use this key for authentificated
+//! encryption.
+use std::marker::PhantomData;
+
+use rand::Rng;
+use num::{BigUint, Zero};
+use digest::Digest;
+use generic_array::GenericArray;
+
+use tools::powm;
+use types::{SrpAuthError, SrpParams};
+
+/// Data provided by users upon registration, usually stored in the database.
+pub struct UserRecord<'a> {
+ pub username: &'a [u8],
+ pub salt: &'a [u8],
+ /// Password verifier
+ pub verifier: &'a [u8],
+}
+
+/// SRP server state
+pub struct SrpServer<D: Digest> {
+ b: BigUint,
+ a_pub: BigUint,
+ b_pub: BigUint,
+
+ key: GenericArray<u8, D::OutputSize>,
+
+ d: PhantomData<D>
+}
+
+impl< D: Digest> SrpServer< D> {
+ /// Create new server state with randomly generated `b`.
+ pub fn new<R: Rng>(user: &UserRecord, a_pub: &[u8], params: &SrpParams,
+ rng: &mut R)
+ -> Result<Self, SrpAuthError>
+ {
+ let l = params.n.bits()/8;
+ let b = rng.gen_iter::<u8>().take(l).collect::<Vec<u8>>();
+ Self::new_with_b(user, a_pub, &b, params)
+ }
+
+ /// Create new server state with given `b`.
+ ///
+ /// Usefull if it's not convenient to keep `SrpServer` state between
+ /// handshake and verification steps. (e.g. when working over HTTP and
+ /// storing `b` in a database)
+ pub fn new_with_b(user: &UserRecord, a_pub: &[u8], b: &[u8],
+ params: &SrpParams)
+ -> Result<Self, SrpAuthError>
+ {
+ let a_pub = BigUint::from_bytes_le(a_pub);
+ // Safeguard against malicious A
+ if &a_pub % ¶ms.n == BigUint::zero() {
+ return Err(SrpAuthError { description: "Malicious a_pub value" })
+ }
+ let v = BigUint::from_bytes_le(user.verifier);
+ let b = BigUint::from_bytes_le(b) % ¶ms.n;
+ // kv + g^b
+ let interm = (¶ms.k * &v) % ¶ms.n;
+ let b_pub = (interm + ¶ms.powm(&b)) % ¶ms.n;
+ // H(A || B)
+ let u = {
+ let mut d = D::new();
+ d.input(&a_pub.to_bytes_le());
+ d.input(&b_pub.to_bytes_le());
+ d.result()
+ };
+ let d = Default::default();
+ //(Av^u) ^ b
+ let key = {
+ let u = BigUint::from_bytes_le(&u);
+ let t = (&a_pub * powm(&v, &u, ¶ms.n)) % ¶ms.n;
+ let s = powm(&t, &b, ¶ms.n);
+ D::digest(&s.to_bytes_le())
+ };
+ Ok(Self { b, a_pub, b_pub, key, d})
+ }
+
+ /// Get private `b` value. (see `new_with_b` documentation)
+ pub fn get_b(&self) -> Vec<u8> {
+ self.b.to_bytes_le()
+ }
+
+ /// Get public `b_pub` value for sending to the user.
+ pub fn get_b_pub(&self) -> Vec<u8> {
+ self.b_pub.to_bytes_le()
+ }
+
+ /// Get shared secret between user and the server. (do not forget to verify
+ /// that keys are the same!)
+ pub fn get_key(&self) -> GenericArray<u8, D::OutputSize> {
+ self.key.clone()
+ }
+
+ /// Process user proof of having the same shared secret and compute
+ /// server proof for sending to the user.
+ pub fn verify(&self, user_proof: &[u8])
+ -> Result<GenericArray<u8, D::OutputSize>, SrpAuthError>
+ {
+ // M = H(A, B, K)
+ let mut d = D::new();
+ d.input(&self.a_pub.to_bytes_le());
+ d.input(&self.b_pub.to_bytes_le());
+ d.input(&self.key);
+
+ if user_proof == d.result().as_slice() {
+ // H(A, M, K)
+ let mut d = D::new();
+ d.input(&self.a_pub.to_bytes_le());
+ d.input(user_proof);
+ d.input(&self.key);
+ Ok(d.result())
+ } else {
+ Err(SrpAuthError { description: "Incorrect user proof" })
+ }
+ }
+}
--- /dev/null
+use num::BigUint;
+
+pub fn powm(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint {
+ let zero = BigUint::new(vec![0]);
+ let one = BigUint::new(vec![1]);
+ let two = BigUint::new(vec![2]);
+ let mut exp = exp.clone();
+ let mut result = one.clone();
+ let mut base = base % modulus;
+
+ while exp > zero {
+ if &exp % &two == one {
+ result = (result * &base) % modulus;
+ }
+ exp = exp >> 1;
+ base = (&base * &base) % modulus;
+ }
+ result
+}
--- /dev/null
+//! Additional SRP types.
+use std::{fmt, error};
+use num::BigUint;
+use tools::powm;
+
+/// SRP authentification error.
+#[derive(Debug, Copy, Clone, Eq, PartialEq)]
+pub struct SrpAuthError {
+ pub(crate) description: &'static str
+}
+
+impl fmt::Display for SrpAuthError {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "SRP authentification error")
+ }
+}
+
+impl error::Error for SrpAuthError {
+ fn description(&self) -> &str {
+ self.description
+ }
+}
+
+/// Parameters of SRP shared between client and server.
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct SrpParams {
+ /// A large safe prime (N = 2q+1, where q is prime)
+ pub n: BigUint,
+ /// A generator modulo N (e.g. 2)
+ pub g: BigUint,
+ /// Multiplier parameter (k = H(N, g) in SRP-6a, k = 3 for legacy SRP-6)
+ pub k: BigUint,
+}
+
+impl SrpParams {
+ pub(crate) fn powm(&self, v: &BigUint) -> BigUint {
+ powm(&self.g, v, &self.n)
+ }
+}
--- /dev/null
+extern crate num;
+extern crate sha2;
+extern crate rand;
+extern crate srp;
+
+use num::BigUint;
+use sha2::Sha256;
+use rand::Rng;
+
+use srp::types::SrpParams;
+use srp::client::{ SrpClient, srp6a_private_key };
+use srp::server::{SrpServer, UserRecord};
+
+fn auth_test(reg_pwd: &[u8], auth_pwd: &[u8]) {
+ let mut rng = rand::os::OsRng::new().unwrap();
+ let username = "john".as_bytes();
+ let srp_params = SrpParams{
+ n: BigUint::from_bytes_le(srp::PRIME),
+ k: BigUint::from_bytes_be(&[1, 2, 3]),
+ g: BigUint::new(vec![2]),
+ };
+
+ // Client instance creation
+ let client = SrpClient::<Sha256>::new(&srp_params, &mut rng);
+
+ // Registration
+ let salt: [u8; 16] = rng.gen();
+ let reg_priv_key = srp6a_private_key::<Sha256>(username, reg_pwd, &salt);
+ let verif = client.get_password_verifier(®_priv_key);
+
+ // User sends handshake
+ let a_pub = client.get_a_pub();
+
+ // Server retrieve user record from db and processes handshake
+ let user = UserRecord { username, salt: &salt, verifier: &verif };
+ let server = SrpServer::<Sha256>::new(&user, &a_pub, &srp_params, &mut rng)
+ .unwrap();
+ let (salt, b_pub) = (&user.salt, server.get_b_pub());
+
+ // Client processes handshake reply
+ let auth_priv_key = srp6a_private_key::<Sha256>(username, auth_pwd, &salt);
+ let client2 = client.process_reply(&auth_priv_key, &b_pub).unwrap();
+ let proof = client2.get_proof();
+
+ // Server processes verification data
+ println!("Client verification");
+ let proof2 = server.verify(&proof).unwrap();
+ let server_key = server.get_key();
+
+ // Client verifies server
+ println!("Server verification");
+ let user_key = client2.verify_server(&proof2).unwrap();
+ assert_eq!(server_key, user_key, "server and client keys are not equal");
+}
+
+#[test]
+fn good_password() {
+ auth_test("password".as_bytes(), "password".as_bytes());
+}
+
+#[test]
+#[should_panic]
+fn bad_password() {
+ auth_test("password".as_bytes(), "paSsword".as_bytes());
+}