]> git.lizzy.rs Git - PAKEs.git/commitdiff
PAKE repository reorganization
authorАртём Павлов [Artyom Pavlov] <newpavlov@gmail.com>
Mon, 14 Aug 2017 04:37:17 +0000 (07:37 +0300)
committerАртём Павлов [Artyom Pavlov] <newpavlov@gmail.com>
Mon, 14 Aug 2017 04:37:17 +0000 (07:37 +0300)
39 files changed:
.travis.yml
Cargo.toml
LICENSE-APACHE [deleted file]
LICENSE-MIT [deleted file]
src/client.rs [deleted file]
src/groups.rs [deleted file]
src/groups/1024.bin [deleted file]
src/groups/1536.bin [deleted file]
src/groups/2048.bin [deleted file]
src/groups/3072.bin [deleted file]
src/groups/4096.bin [deleted file]
src/groups/6144.bin [deleted file]
src/groups/8192.bin [deleted file]
src/k_sha1_1024.bin [deleted file]
src/lib.rs [deleted file]
src/prime.bin [deleted file]
src/server.rs [deleted file]
src/tools.rs [deleted file]
src/types.rs [deleted file]
srp/Cargo.toml [new file with mode: 0644]
srp/LICENSE-APACHE [new file with mode: 0644]
srp/LICENSE-MIT [new file with mode: 0644]
srp/src/client.rs [new file with mode: 0644]
srp/src/groups.rs [new file with mode: 0644]
srp/src/groups/1024.bin [new file with mode: 0644]
srp/src/groups/1536.bin [new file with mode: 0644]
srp/src/groups/2048.bin [new file with mode: 0644]
srp/src/groups/3072.bin [new file with mode: 0644]
srp/src/groups/4096.bin [new file with mode: 0644]
srp/src/groups/6144.bin [new file with mode: 0644]
srp/src/groups/8192.bin [new file with mode: 0644]
srp/src/k_sha1_1024.bin [new file with mode: 0644]
srp/src/lib.rs [new file with mode: 0644]
srp/src/prime.bin [new file with mode: 0644]
srp/src/server.rs [new file with mode: 0644]
srp/src/tools.rs [new file with mode: 0644]
srp/src/types.rs [new file with mode: 0644]
srp/tests/mod.rs [new file with mode: 0644]
tests/mod.rs [deleted file]

index 7f3fa4076536b395c293666e6b4206ad0f15b8a9..88515a83530f85fc29c9e04ae10628473231214e 100644 (file)
@@ -6,4 +6,4 @@ rust:
 matrix:
   allow_failures:
     - rust: nightly
-script: cargo test --release --verbose
+script: cargo test --release --verbose --all
index 74a72aa82c9d24e54afe6d74616651a086f70ce6..2c131a4f5ca8659bdb467601429ea2013bc0cb9f 100644 (file)
@@ -1,24 +1,4 @@
-[package]
-name = "srp"
-version = "0.2.1"
-authors = ["RustCrypto Developers"]
-license = "MIT/Apache-2.0"
-description = "Secure Remote Password (SRP) protocol implementation"
-documentation = "https://docs.rs/srp"
-repository = "https://github.com/RustCrypto/SRP"
-keywords = ["crypto", "pake", "authentication"]
-categories = ["cryptography", "authentication"]
-
-[dependencies]
-num = "0.1"
-generic-array = "0.8"
-digest = "0.6"
-lazy_static = "0.2"
-
-[dev-dependencies]
-rand = "0.3"
-sha2 = "0.6"
-sha-1 = "0.4"
-
-[badges]
-travis-ci = { repository = "RustCrypto/SRP" }
+[workspace]
+members = [
+    "srp",
+]
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
deleted file mode 100644 (file)
index 78173fa..0000000
+++ /dev/null
@@ -1,201 +0,0 @@
-                              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.
diff --git a/LICENSE-MIT b/LICENSE-MIT
deleted file mode 100644 (file)
index 8dcb85b..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-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.
diff --git a/src/client.rs b/src/client.rs
deleted file mode 100644 (file)
index 4348f4f..0000000
+++ /dev/null
@@ -1,212 +0,0 @@
-//! SRP client implementation.
-//! 
-//! # Usage
-//! First create SRP client struct by passing to it SRP parameters (shared
-//! between client and server) and randomly generated `a`:
-//! 
-//! ```ignore
-//! use srp::groups::G_2048;
-//! use sha2::Sha256;
-//!
-//! let a = rng.gen_iter::<u8>().take(64).collect::<Vec<u8>>();
-//! let client = SrpClient::<Sha256>::new(&a, &G_2048);
-//! ```
-//! 
-//! 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 = srp_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 = client.get_password_verifier(&private_key);
-//! conn.send_registration_data(username, salt, pwd_verifier);
-//! ```
-
-//let buf = rng.gen_iter::<u8>().take(l).collect::<Vec<u8>>();
-use std::marker::PhantomData;
-
-use num::{BigUint, Zero};
-use digest::Digest;
-use generic_array::GenericArray;
-
-use tools::powm;
-use types::{SrpAuthError, SrpGroup};
-
-/// SRP client state before handshake with the server.
-pub struct SrpClient<'a, D: Digest> {
-    params: &'a SrpGroup,
-
-    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 RFC 5054. Consider using proper
-/// password hashing algorithm instead.
-pub fn srp_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(a: &[u8], params: &'a SrpGroup) -> Self {
-        let a = BigUint::from_bytes_be(a);
-        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_be(&private_key);
-        let v = self.params.powm(&x);
-        v.to_bytes_be()
-    }
-
-    fn calc_key(&self, b_pub: &BigUint, x: &BigUint, u: &BigUint)
-        -> GenericArray<u8, D::OutputSize>
-    {
-        let n = &self.params.n;
-        let k = self.params.compute_k::<D>();
-        let interm = (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_be())
-    }
-
-    /// 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_be());
-            d.input(b_pub);
-            BigUint::from_bytes_be(&d.result())
-        };
-
-        let b_pub = BigUint::from_bytes_be(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_be(&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_be());
-            d.input(&b_pub.to_bytes_be());
-            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_be());
-            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_be()
-    }
-}
-
-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)
-        }
-    }
-}
diff --git a/src/groups.rs b/src/groups.rs
deleted file mode 100644 (file)
index 246134e..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-//! Groups from [RFC 5054](https://tools.ietf.org/html/rfc5054)
-//! 
-//! It is strongly recommended to use them instead of custom generated
-//! groups. Additionally it is not recommended to use `G_1024` and `G_1536`,
-//! they are provided only for compatability with the legacy software.
-use types::SrpGroup;
-use num::BigUint;
-
-lazy_static! {
-    pub static ref G_1024: SrpGroup = SrpGroup {
-        n: BigUint::from_bytes_be(include_bytes!("groups/1024.bin")),
-        g: BigUint::from_bytes_be(&[2]),
-    };
-}
-
-lazy_static! {
-    pub static ref G_1536: SrpGroup = SrpGroup {
-        n: BigUint::from_bytes_be(include_bytes!("groups/1536.bin")),
-        g: BigUint::from_bytes_be(&[2]),
-    };
-}
-
-lazy_static! {
-    pub static ref G_2048: SrpGroup = SrpGroup {
-        n: BigUint::from_bytes_be(include_bytes!("groups/2048.bin")),
-        g: BigUint::from_bytes_be(&[2]),
-    };
-}
-
-lazy_static! {
-    pub static ref G_3072: SrpGroup = SrpGroup {
-        n: BigUint::from_bytes_be(include_bytes!("groups/3072.bin")),
-        g: BigUint::from_bytes_be(&[5]),
-    };
-}
-
-lazy_static! {
-    pub static ref G_4096: SrpGroup = SrpGroup {
-        n: BigUint::from_bytes_be(include_bytes!("groups/4096.bin")),
-        g: BigUint::from_bytes_be(&[5]),
-    };
-}
-
-lazy_static! {
-    pub static ref G_6144: SrpGroup = SrpGroup {
-        n: BigUint::from_bytes_be(include_bytes!("groups/6144.bin")),
-        g: BigUint::from_bytes_be(&[5]),
-    };
-}
-
-lazy_static! {
-    pub static ref G_8192: SrpGroup = SrpGroup {
-        n: BigUint::from_bytes_be(include_bytes!("groups/8192.bin")),
-        g: BigUint::from_bytes_be(&[19]),
-    };
-}
diff --git a/src/groups/1024.bin b/src/groups/1024.bin
deleted file mode 100644 (file)
index 7ce0aa3..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-î¯
-¹­³\8dÖ\9c
\8fÅè`ra\87uÿ<\v\9e¢1L\9c%evÖtßt\96ê\81Ó8;H\13Ö\92ÆààÕØâP¹\8bä\8eI\\1d`\89ÚÑ]Ç×´aTÖ¶Î\8eô­i±]I\82U\9b){Ï\18\85Å)õff\ eWìhí¼<\ 5rlÀ/ÔËô\97\9aýQ8þ\83vC[\9fÆ\1d/Àë\ 6ã
\ No newline at end of file
diff --git a/src/groups/1536.bin b/src/groups/1536.bin
deleted file mode 100644 (file)
index c3a5972..0000000
+++ /dev/null
@@ -1 +0,0 @@
-\9dï<¯¹9'z±ñ*\86\17¤{»Û¥\1dô\99¬L\80¾î©aK\19ÌM_O_Un'ËÞQÆ©Kä`z)\15X\90; ÐøC\80¶U»\9a"èÜß\ 2\8a|ìgðÐ\814±È¹y\89\14\9b`\9e\v㺶=GT\83\81ÛűüvN?KSÝ\9d¡\15\8bý>+\9c\8cõnß\ 1\9594\96'Û/Õ=$·Ä\86ew.C}l\7f\8cäBsJ÷Ì·®\83|&J㩾¸\7f\8a/鸵).Z\ 2\1fÿ^\91G\9e\8cç¢\8c$BÆó\15\18\ f\93I\9a#MÏvãþÑ5ù»
\ No newline at end of file
diff --git a/src/groups/2048.bin b/src/groups/2048.bin
deleted file mode 100644 (file)
index 23207c6..0000000
+++ /dev/null
@@ -1,2 +0,0 @@
-¬kÛA2J\9a\9bñfÞ^\13\89X/¯r¶e\19\87î\aü1\92\94=µ`P£s)Ë´ \99í\81\93àuwg¡=Õ#\12«K\ 31\rÍ\7fH©Ú\ 4ýPè\b9ií·g°Ï`\95\17\9a\16:³f\1a\ 5ûÕúªè)\18©\96/\v\93¸Uùy\93ì\97^ê¨\rt
-ÛôÿtsYÐAÕÃ>§\1d(\1eDk\14w;Ê\97´:#û\80\16v½ zCld\81ñÒ¹\a\87\17F\1a[\9d\88øwHTE#µ$°Õ}^§z'uÒìú\ 3,ûÛõ/³xa`'\90\ 4åzæ¯\87Ns\ 3ÎS)\9cÌ\ 4\1c\bØ*V\98ó¨ÐÃ\82q®5øéÛû¶\94µÈ\ 3Ø\9fzä5Þ#mR_Tu\9beãrüÖ\8eò\ f§\11\1f\9eJÿs
\ No newline at end of file
diff --git a/src/groups/3072.bin b/src/groups/3072.bin
deleted file mode 100644 (file)
index 7e1a84d..0000000
Binary files a/src/groups/3072.bin and /dev/null differ
diff --git a/src/groups/4096.bin b/src/groups/4096.bin
deleted file mode 100644 (file)
index 82463c0..0000000
Binary files a/src/groups/4096.bin and /dev/null differ
diff --git a/src/groups/6144.bin b/src/groups/6144.bin
deleted file mode 100644 (file)
index 83a559a..0000000
Binary files a/src/groups/6144.bin and /dev/null differ
diff --git a/src/groups/8192.bin b/src/groups/8192.bin
deleted file mode 100644 (file)
index b1f32ac..0000000
Binary files a/src/groups/8192.bin and /dev/null differ
diff --git a/src/k_sha1_1024.bin b/src/k_sha1_1024.bin
deleted file mode 100644 (file)
index 4408438..0000000
+++ /dev/null
@@ -1 +0,0 @@
-uVª\ 4Zï,Ý\a«¯\ ff\>\81\89\13\18o
\ No newline at end of file
diff --git a/src/lib.rs b/src/lib.rs
deleted file mode 100644 (file)
index df11ae9..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-//! [Secure Remote Password][1] (SRP) protocol implementation.
-//! 
-//! This implementation is generic over hash functions using
-//! [`Digest`](https://docs.rs/digest) trait, so you will need to choose a hash
-//! function, e.g. `Sha256` from [`sha2`](https://crates.io/crates/sha2) crate.
-//! Additionally this crate allows to use a specialized password hashing
-//! algorithm for private key computation instead of method described in the
-//! SRP literature.
-//! 
-//! Compatability with over implementations was not yet tested.
-//! 
-//! # Usage
-//! Add `srp` dependecy to your `Cargo.toml`:
-//! 
-//! ```toml
-//! [dependencies]
-//! rand = "0.3"
-//! ```
-//!
-//! and this to your crate root:
-//!
-//! ```rust
-//! extern crate srp;
-//! ```
-//!
-//! Next read documentation for [`client`](client/index.html) and
-//! [`server`](server/index.html) modules.
-//!
-//! # 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). Additionally `g` MUST be
-//! a generator modulo `N`. It's STRONGLY recommended to use SRP parameters
-//! provided by this crate in the [`groups`](groups/index.html) module.
-//! 
-//!        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
-//! - `PH` — password hashing algroithm, in the RFC 5054 described as
-//! `H(s || H(I || ":" || 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 (at least 256 bits in length)
-//! - `A`, `B` — Public ephemeral values
-//! - `u` — scrambling parameter
-//! - `k` — multiplier parameter (`k = H(N || g)` in SRP-6a)
-//!
-//! [1]: https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol
-//! [2]: https://tools.ietf.org/html/rfc5054
-extern crate num;
-extern crate digest;
-extern crate generic_array;
-#[macro_use]
-extern crate lazy_static;
-
-#[cfg(test)]
-extern crate sha_1;
-
-mod tools;
-pub mod client;
-pub mod server;
-pub mod types;
-pub mod groups;
diff --git a/src/prime.bin b/src/prime.bin
deleted file mode 100644 (file)
index d2109b7..0000000
+++ /dev/null
@@ -1 +0,0 @@
-ã_\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\98\88uÃ7À
\ No newline at end of file
diff --git a/src/server.rs b/src/server.rs
deleted file mode 100644 (file)
index 137d6b3..0000000
+++ /dev/null
@@ -1,136 +0,0 @@
-//! SRP server implementation
-//!
-//! # Usage
-//! First receive user's username and public value `a_pub`, retrieve from a
-//! database `UserRecord` for a given username, generate `b` (e.g. 512 bits
-//! long) and initialize SRP server instance:
-//! 
-//! ```ignore
-//! use srp::groups::G_2048;
-//!
-//! let (username, a_pub) = conn.receive_handshake();
-//! let user = db.retrieve_user_record(username);
-//! let b = rng.gen_iter::<u8>().take(64).collect::<Vec<u8>>();
-//! let server = SrpServer::<Sha256>::new(&user, &a_pub, &b, &G_2048)?;
-//! ```
-//! 
-//! 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 in the
-//! 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 num::{BigUint, Zero};
-use digest::Digest;
-use generic_array::GenericArray;
-
-use tools::powm;
-use types::{SrpAuthError, SrpGroup};
-
-/// 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.
-    pub fn new(user: &UserRecord, a_pub: &[u8], b: &[u8], params: &SrpGroup)
-        -> Result<Self, SrpAuthError>
-    {
-        let a_pub = BigUint::from_bytes_be(a_pub);
-        // Safeguard against malicious A
-        if &a_pub % &params.n == BigUint::zero() {
-            return Err(SrpAuthError { description: "Malicious a_pub value" })
-        }
-        let v = BigUint::from_bytes_be(user.verifier);
-        let b = BigUint::from_bytes_be(b)  % &params.n;
-        let k = params.compute_k::<D>();
-        // kv + g^b
-        let interm = (k * &v) % &params.n;
-        let b_pub = (interm + &params.powm(&b)) % &params.n;
-        // H(A || B)
-        let u = {
-            let mut d = D::new();
-            d.input(&a_pub.to_bytes_be());
-            d.input(&b_pub.to_bytes_be());
-            d.result()
-        };
-        let d = Default::default();
-        //(Av^u) ^ b
-        let key = {
-            let u =  BigUint::from_bytes_be(&u);
-            let t = (&a_pub * powm(&v, &u, &params.n)) % &params.n;
-            let s = powm(&t, &b, &params.n);
-            D::digest(&s.to_bytes_be())
-        };
-        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_be()
-    }
-
-    /// Get public `b_pub` value for sending to the user.
-    pub fn get_b_pub(&self) -> Vec<u8> {
-        self.b_pub.to_bytes_be()
-    }
-
-    /// 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_be());
-        d.input(&self.b_pub.to_bytes_be());
-        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_be());
-            d.input(user_proof);
-            d.input(&self.key);
-            Ok(d.result())
-        } else {
-            Err(SrpAuthError { description: "Incorrect user proof" })
-        }
-    }
-}
diff --git a/src/tools.rs b/src/tools.rs
deleted file mode 100644 (file)
index 8cb6910..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-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
-}
diff --git a/src/types.rs b/src/types.rs
deleted file mode 100644 (file)
index 810132c..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-//! Additional SRP types.
-use std::{fmt, error};
-use num::BigUint;
-use tools::powm;
-use digest::Digest;
-
-/// 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
-    }
-}
-
-/// Group used for SRP computations
-#[derive(Debug, Clone, Eq, PartialEq)]
-pub struct SrpGroup {
-    /// A large safe prime (N = 2q+1, where q is prime)
-    pub n: BigUint,
-    /// A generator modulo N
-    pub g: BigUint,
-}
-
-impl SrpGroup {
-    pub(crate) fn powm(&self, v: &BigUint) -> BigUint {
-        powm(&self.g, v, &self.n)
-    }
-
-    /// Compute `k` with given hash function and return SRP parameters
-    pub(crate) fn compute_k<D: Digest>(&self) -> BigUint {
-        let n = self.n.to_bytes_be();
-        let g_bytes = self.g.to_bytes_be();
-        let mut buf = vec![0u8; n.len()];
-        let l = n.len() - g_bytes.len();
-        buf[l..].copy_from_slice(&g_bytes);
-
-        let mut d = D::new();
-        d.input(&n);
-        d.input(&buf);
-        BigUint::from_bytes_be(&d.result())
-    }
-}
-
-#[cfg(test)]
-mod tests {
-    use ::groups::G_1024;
-    use sha_1::Sha1;
-
-    #[test]
-    fn test_k_1024_sha1() {
-        let k = G_1024.compute_k::<Sha1>().to_bytes_be();
-        assert_eq!(&k, include_bytes!("k_sha1_1024.bin"));
-    }
-}
diff --git a/srp/Cargo.toml b/srp/Cargo.toml
new file mode 100644 (file)
index 0000000..27c846d
--- /dev/null
@@ -0,0 +1,24 @@
+[package]
+name = "srp"
+version = "0.2.2"
+authors = ["RustCrypto Developers"]
+license = "MIT/Apache-2.0"
+description = "Secure Remote Password (SRP) protocol implementation"
+documentation = "https://docs.rs/srp"
+repository = "https://github.com/RustCrypto/PAKE"
+keywords = ["crypto", "pake", "authentication"]
+categories = ["cryptography", "authentication"]
+
+[dependencies]
+num = "0.1"
+generic-array = "0.8"
+digest = "0.6"
+lazy_static = "0.2"
+
+[dev-dependencies]
+rand = "0.3"
+sha2 = "0.6"
+sha-1 = "0.4"
+
+[badges]
+travis-ci = { repository = "RustCrypto/SRP" }
diff --git a/srp/LICENSE-APACHE b/srp/LICENSE-APACHE
new file mode 100644 (file)
index 0000000..78173fa
--- /dev/null
@@ -0,0 +1,201 @@
+                              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.
diff --git a/srp/LICENSE-MIT b/srp/LICENSE-MIT
new file mode 100644 (file)
index 0000000..8dcb85b
--- /dev/null
@@ -0,0 +1,25 @@
+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.
diff --git a/srp/src/client.rs b/srp/src/client.rs
new file mode 100644 (file)
index 0000000..4348f4f
--- /dev/null
@@ -0,0 +1,212 @@
+//! SRP client implementation.
+//! 
+//! # Usage
+//! First create SRP client struct by passing to it SRP parameters (shared
+//! between client and server) and randomly generated `a`:
+//! 
+//! ```ignore
+//! use srp::groups::G_2048;
+//! use sha2::Sha256;
+//!
+//! let a = rng.gen_iter::<u8>().take(64).collect::<Vec<u8>>();
+//! let client = SrpClient::<Sha256>::new(&a, &G_2048);
+//! ```
+//! 
+//! 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 = srp_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 = client.get_password_verifier(&private_key);
+//! conn.send_registration_data(username, salt, pwd_verifier);
+//! ```
+
+//let buf = rng.gen_iter::<u8>().take(l).collect::<Vec<u8>>();
+use std::marker::PhantomData;
+
+use num::{BigUint, Zero};
+use digest::Digest;
+use generic_array::GenericArray;
+
+use tools::powm;
+use types::{SrpAuthError, SrpGroup};
+
+/// SRP client state before handshake with the server.
+pub struct SrpClient<'a, D: Digest> {
+    params: &'a SrpGroup,
+
+    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 RFC 5054. Consider using proper
+/// password hashing algorithm instead.
+pub fn srp_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(a: &[u8], params: &'a SrpGroup) -> Self {
+        let a = BigUint::from_bytes_be(a);
+        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_be(&private_key);
+        let v = self.params.powm(&x);
+        v.to_bytes_be()
+    }
+
+    fn calc_key(&self, b_pub: &BigUint, x: &BigUint, u: &BigUint)
+        -> GenericArray<u8, D::OutputSize>
+    {
+        let n = &self.params.n;
+        let k = self.params.compute_k::<D>();
+        let interm = (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_be())
+    }
+
+    /// 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_be());
+            d.input(b_pub);
+            BigUint::from_bytes_be(&d.result())
+        };
+
+        let b_pub = BigUint::from_bytes_be(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_be(&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_be());
+            d.input(&b_pub.to_bytes_be());
+            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_be());
+            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_be()
+    }
+}
+
+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)
+        }
+    }
+}
diff --git a/srp/src/groups.rs b/srp/src/groups.rs
new file mode 100644 (file)
index 0000000..246134e
--- /dev/null
@@ -0,0 +1,56 @@
+//! Groups from [RFC 5054](https://tools.ietf.org/html/rfc5054)
+//! 
+//! It is strongly recommended to use them instead of custom generated
+//! groups. Additionally it is not recommended to use `G_1024` and `G_1536`,
+//! they are provided only for compatability with the legacy software.
+use types::SrpGroup;
+use num::BigUint;
+
+lazy_static! {
+    pub static ref G_1024: SrpGroup = SrpGroup {
+        n: BigUint::from_bytes_be(include_bytes!("groups/1024.bin")),
+        g: BigUint::from_bytes_be(&[2]),
+    };
+}
+
+lazy_static! {
+    pub static ref G_1536: SrpGroup = SrpGroup {
+        n: BigUint::from_bytes_be(include_bytes!("groups/1536.bin")),
+        g: BigUint::from_bytes_be(&[2]),
+    };
+}
+
+lazy_static! {
+    pub static ref G_2048: SrpGroup = SrpGroup {
+        n: BigUint::from_bytes_be(include_bytes!("groups/2048.bin")),
+        g: BigUint::from_bytes_be(&[2]),
+    };
+}
+
+lazy_static! {
+    pub static ref G_3072: SrpGroup = SrpGroup {
+        n: BigUint::from_bytes_be(include_bytes!("groups/3072.bin")),
+        g: BigUint::from_bytes_be(&[5]),
+    };
+}
+
+lazy_static! {
+    pub static ref G_4096: SrpGroup = SrpGroup {
+        n: BigUint::from_bytes_be(include_bytes!("groups/4096.bin")),
+        g: BigUint::from_bytes_be(&[5]),
+    };
+}
+
+lazy_static! {
+    pub static ref G_6144: SrpGroup = SrpGroup {
+        n: BigUint::from_bytes_be(include_bytes!("groups/6144.bin")),
+        g: BigUint::from_bytes_be(&[5]),
+    };
+}
+
+lazy_static! {
+    pub static ref G_8192: SrpGroup = SrpGroup {
+        n: BigUint::from_bytes_be(include_bytes!("groups/8192.bin")),
+        g: BigUint::from_bytes_be(&[19]),
+    };
+}
diff --git a/srp/src/groups/1024.bin b/srp/src/groups/1024.bin
new file mode 100644 (file)
index 0000000..7ce0aa3
--- /dev/null
@@ -0,0 +1,3 @@
+î¯
+¹­³\8dÖ\9c
\8fÅè`ra\87uÿ<\v\9e¢1L\9c%evÖtßt\96ê\81Ó8;H\13Ö\92ÆààÕØâP¹\8bä\8eI\\1d`\89ÚÑ]Ç×´aTÖ¶Î\8eô­i±]I\82U\9b){Ï\18\85Å)õff\ eWìhí¼<\ 5rlÀ/ÔËô\97\9aýQ8þ\83vC[\9fÆ\1d/Àë\ 6ã
\ No newline at end of file
diff --git a/srp/src/groups/1536.bin b/srp/src/groups/1536.bin
new file mode 100644 (file)
index 0000000..c3a5972
--- /dev/null
@@ -0,0 +1 @@
+\9dï<¯¹9'z±ñ*\86\17¤{»Û¥\1dô\99¬L\80¾î©aK\19ÌM_O_Un'ËÞQÆ©Kä`z)\15X\90; ÐøC\80¶U»\9a"èÜß\ 2\8a|ìgðÐ\814±È¹y\89\14\9b`\9e\v㺶=GT\83\81ÛűüvN?KSÝ\9d¡\15\8bý>+\9c\8cõnß\ 1\9594\96'Û/Õ=$·Ä\86ew.C}l\7f\8cäBsJ÷Ì·®\83|&J㩾¸\7f\8a/鸵).Z\ 2\1fÿ^\91G\9e\8cç¢\8c$BÆó\15\18\ f\93I\9a#MÏvãþÑ5ù»
\ No newline at end of file
diff --git a/srp/src/groups/2048.bin b/srp/src/groups/2048.bin
new file mode 100644 (file)
index 0000000..23207c6
--- /dev/null
@@ -0,0 +1,2 @@
+¬kÛA2J\9a\9bñfÞ^\13\89X/¯r¶e\19\87î\aü1\92\94=µ`P£s)Ë´ \99í\81\93àuwg¡=Õ#\12«K\ 31\rÍ\7fH©Ú\ 4ýPè\b9ií·g°Ï`\95\17\9a\16:³f\1a\ 5ûÕúªè)\18©\96/\v\93¸Uùy\93ì\97^ê¨\rt
+ÛôÿtsYÐAÕÃ>§\1d(\1eDk\14w;Ê\97´:#û\80\16v½ zCld\81ñÒ¹\a\87\17F\1a[\9d\88øwHTE#µ$°Õ}^§z'uÒìú\ 3,ûÛõ/³xa`'\90\ 4åzæ¯\87Ns\ 3ÎS)\9cÌ\ 4\1c\bØ*V\98ó¨ÐÃ\82q®5øéÛû¶\94µÈ\ 3Ø\9fzä5Þ#mR_Tu\9beãrüÖ\8eò\ f§\11\1f\9eJÿs
\ No newline at end of file
diff --git a/srp/src/groups/3072.bin b/srp/src/groups/3072.bin
new file mode 100644 (file)
index 0000000..7e1a84d
Binary files /dev/null and b/srp/src/groups/3072.bin differ
diff --git a/srp/src/groups/4096.bin b/srp/src/groups/4096.bin
new file mode 100644 (file)
index 0000000..82463c0
Binary files /dev/null and b/srp/src/groups/4096.bin differ
diff --git a/srp/src/groups/6144.bin b/srp/src/groups/6144.bin
new file mode 100644 (file)
index 0000000..83a559a
Binary files /dev/null and b/srp/src/groups/6144.bin differ
diff --git a/srp/src/groups/8192.bin b/srp/src/groups/8192.bin
new file mode 100644 (file)
index 0000000..b1f32ac
Binary files /dev/null and b/srp/src/groups/8192.bin differ
diff --git a/srp/src/k_sha1_1024.bin b/srp/src/k_sha1_1024.bin
new file mode 100644 (file)
index 0000000..4408438
--- /dev/null
@@ -0,0 +1 @@
+uVª\ 4Zï,Ý\a«¯\ ff\>\81\89\13\18o
\ No newline at end of file
diff --git a/srp/src/lib.rs b/srp/src/lib.rs
new file mode 100644 (file)
index 0000000..df11ae9
--- /dev/null
@@ -0,0 +1,79 @@
+//! [Secure Remote Password][1] (SRP) protocol implementation.
+//! 
+//! This implementation is generic over hash functions using
+//! [`Digest`](https://docs.rs/digest) trait, so you will need to choose a hash
+//! function, e.g. `Sha256` from [`sha2`](https://crates.io/crates/sha2) crate.
+//! Additionally this crate allows to use a specialized password hashing
+//! algorithm for private key computation instead of method described in the
+//! SRP literature.
+//! 
+//! Compatability with over implementations was not yet tested.
+//! 
+//! # Usage
+//! Add `srp` dependecy to your `Cargo.toml`:
+//! 
+//! ```toml
+//! [dependencies]
+//! rand = "0.3"
+//! ```
+//!
+//! and this to your crate root:
+//!
+//! ```rust
+//! extern crate srp;
+//! ```
+//!
+//! Next read documentation for [`client`](client/index.html) and
+//! [`server`](server/index.html) modules.
+//!
+//! # 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). Additionally `g` MUST be
+//! a generator modulo `N`. It's STRONGLY recommended to use SRP parameters
+//! provided by this crate in the [`groups`](groups/index.html) module.
+//! 
+//!        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
+//! - `PH` — password hashing algroithm, in the RFC 5054 described as
+//! `H(s || H(I || ":" || 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 (at least 256 bits in length)
+//! - `A`, `B` — Public ephemeral values
+//! - `u` — scrambling parameter
+//! - `k` — multiplier parameter (`k = H(N || g)` in SRP-6a)
+//!
+//! [1]: https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol
+//! [2]: https://tools.ietf.org/html/rfc5054
+extern crate num;
+extern crate digest;
+extern crate generic_array;
+#[macro_use]
+extern crate lazy_static;
+
+#[cfg(test)]
+extern crate sha_1;
+
+mod tools;
+pub mod client;
+pub mod server;
+pub mod types;
+pub mod groups;
diff --git a/srp/src/prime.bin b/srp/src/prime.bin
new file mode 100644 (file)
index 0000000..d2109b7
--- /dev/null
@@ -0,0 +1 @@
+ã_\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\98\88uÃ7À
\ No newline at end of file
diff --git a/srp/src/server.rs b/srp/src/server.rs
new file mode 100644 (file)
index 0000000..137d6b3
--- /dev/null
@@ -0,0 +1,136 @@
+//! SRP server implementation
+//!
+//! # Usage
+//! First receive user's username and public value `a_pub`, retrieve from a
+//! database `UserRecord` for a given username, generate `b` (e.g. 512 bits
+//! long) and initialize SRP server instance:
+//! 
+//! ```ignore
+//! use srp::groups::G_2048;
+//!
+//! let (username, a_pub) = conn.receive_handshake();
+//! let user = db.retrieve_user_record(username);
+//! let b = rng.gen_iter::<u8>().take(64).collect::<Vec<u8>>();
+//! let server = SrpServer::<Sha256>::new(&user, &a_pub, &b, &G_2048)?;
+//! ```
+//! 
+//! 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 in the
+//! 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 num::{BigUint, Zero};
+use digest::Digest;
+use generic_array::GenericArray;
+
+use tools::powm;
+use types::{SrpAuthError, SrpGroup};
+
+/// 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.
+    pub fn new(user: &UserRecord, a_pub: &[u8], b: &[u8], params: &SrpGroup)
+        -> Result<Self, SrpAuthError>
+    {
+        let a_pub = BigUint::from_bytes_be(a_pub);
+        // Safeguard against malicious A
+        if &a_pub % &params.n == BigUint::zero() {
+            return Err(SrpAuthError { description: "Malicious a_pub value" })
+        }
+        let v = BigUint::from_bytes_be(user.verifier);
+        let b = BigUint::from_bytes_be(b)  % &params.n;
+        let k = params.compute_k::<D>();
+        // kv + g^b
+        let interm = (k * &v) % &params.n;
+        let b_pub = (interm + &params.powm(&b)) % &params.n;
+        // H(A || B)
+        let u = {
+            let mut d = D::new();
+            d.input(&a_pub.to_bytes_be());
+            d.input(&b_pub.to_bytes_be());
+            d.result()
+        };
+        let d = Default::default();
+        //(Av^u) ^ b
+        let key = {
+            let u =  BigUint::from_bytes_be(&u);
+            let t = (&a_pub * powm(&v, &u, &params.n)) % &params.n;
+            let s = powm(&t, &b, &params.n);
+            D::digest(&s.to_bytes_be())
+        };
+        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_be()
+    }
+
+    /// Get public `b_pub` value for sending to the user.
+    pub fn get_b_pub(&self) -> Vec<u8> {
+        self.b_pub.to_bytes_be()
+    }
+
+    /// 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_be());
+        d.input(&self.b_pub.to_bytes_be());
+        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_be());
+            d.input(user_proof);
+            d.input(&self.key);
+            Ok(d.result())
+        } else {
+            Err(SrpAuthError { description: "Incorrect user proof" })
+        }
+    }
+}
diff --git a/srp/src/tools.rs b/srp/src/tools.rs
new file mode 100644 (file)
index 0000000..8cb6910
--- /dev/null
@@ -0,0 +1,19 @@
+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
+}
diff --git a/srp/src/types.rs b/srp/src/types.rs
new file mode 100644 (file)
index 0000000..810132c
--- /dev/null
@@ -0,0 +1,64 @@
+//! Additional SRP types.
+use std::{fmt, error};
+use num::BigUint;
+use tools::powm;
+use digest::Digest;
+
+/// 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
+    }
+}
+
+/// Group used for SRP computations
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct SrpGroup {
+    /// A large safe prime (N = 2q+1, where q is prime)
+    pub n: BigUint,
+    /// A generator modulo N
+    pub g: BigUint,
+}
+
+impl SrpGroup {
+    pub(crate) fn powm(&self, v: &BigUint) -> BigUint {
+        powm(&self.g, v, &self.n)
+    }
+
+    /// Compute `k` with given hash function and return SRP parameters
+    pub(crate) fn compute_k<D: Digest>(&self) -> BigUint {
+        let n = self.n.to_bytes_be();
+        let g_bytes = self.g.to_bytes_be();
+        let mut buf = vec![0u8; n.len()];
+        let l = n.len() - g_bytes.len();
+        buf[l..].copy_from_slice(&g_bytes);
+
+        let mut d = D::new();
+        d.input(&n);
+        d.input(&buf);
+        BigUint::from_bytes_be(&d.result())
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use ::groups::G_1024;
+    use sha_1::Sha1;
+
+    #[test]
+    fn test_k_1024_sha1() {
+        let k = G_1024.compute_k::<Sha1>().to_bytes_be();
+        assert_eq!(&k, include_bytes!("k_sha1_1024.bin"));
+    }
+}
diff --git a/srp/tests/mod.rs b/srp/tests/mod.rs
new file mode 100644 (file)
index 0000000..24d911d
--- /dev/null
@@ -0,0 +1,61 @@
+extern crate num;
+extern crate sha2;
+extern crate rand;
+extern crate srp;
+
+use sha2::Sha256;
+use rand::Rng;
+
+use srp::groups::G_2048;
+use srp::client::{SrpClient, srp_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 = "alice".as_bytes();
+
+    // Client instance creation
+    let a = rng.gen_iter::<u8>().take(64).collect::<Vec<u8>>();
+    let client = SrpClient::<Sha256>::new(&a, &G_2048);
+
+    // Registration
+    let salt: [u8; 16] = rng.gen();
+    let reg_priv_key = srp_private_key::<Sha256>(username, reg_pwd, &salt);
+    let verif = client.get_password_verifier(&reg_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 b = rng.gen_iter::<u8>().take(64).collect::<Vec<u8>>();
+    let server = SrpServer::<Sha256>::new(&user, &a_pub, &b, &G_2048)
+        .unwrap();
+    let (salt, b_pub) = (&user.salt, server.get_b_pub());
+
+    // Client processes handshake reply
+    let auth_priv_key = srp_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());
+}
diff --git a/tests/mod.rs b/tests/mod.rs
deleted file mode 100644 (file)
index 24d911d..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-extern crate num;
-extern crate sha2;
-extern crate rand;
-extern crate srp;
-
-use sha2::Sha256;
-use rand::Rng;
-
-use srp::groups::G_2048;
-use srp::client::{SrpClient, srp_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 = "alice".as_bytes();
-
-    // Client instance creation
-    let a = rng.gen_iter::<u8>().take(64).collect::<Vec<u8>>();
-    let client = SrpClient::<Sha256>::new(&a, &G_2048);
-
-    // Registration
-    let salt: [u8; 16] = rng.gen();
-    let reg_priv_key = srp_private_key::<Sha256>(username, reg_pwd, &salt);
-    let verif = client.get_password_verifier(&reg_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 b = rng.gen_iter::<u8>().take(64).collect::<Vec<u8>>();
-    let server = SrpServer::<Sha256>::new(&user, &a_pub, &b, &G_2048)
-        .unwrap();
-    let (salt, b_pub) = (&user.salt, server.get_b_pub());
-
-    // Client processes handshake reply
-    let auth_priv_key = srp_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());
-}