├── libhl-crypto ├── debian │ ├── compat │ ├── source │ │ └── format │ ├── rules │ ├── libindy-crypto.install │ ├── libindy-crypto-dev.install │ ├── copyright │ ├── changelog │ └── control ├── .gitignore ├── ci │ ├── .gitattributes │ ├── libindy_crypto-deb-build-and-upload.sh │ ├── libindy_crypto-win-zip-and-upload.sh │ └── ubuntu.dockerfile ├── src │ ├── encoding │ │ ├── mod.rs │ │ └── hex.rs │ ├── utils │ │ ├── logger.rs │ │ ├── mod.rs │ │ ├── commitment.rs │ │ ├── rsa.rs │ │ ├── ctypes.rs │ │ └── macros.rs │ ├── keys.rs │ ├── cl │ │ └── constants.rs │ ├── hash │ │ ├── mod.rs │ │ ├── blake2.rs │ │ └── sha2.rs │ ├── signatures │ │ └── mod.rs │ ├── ffi │ │ └── mod.rs │ ├── lib.rs │ └── errors │ │ └── mod.rs ├── amcl │ ├── Cargo.lock │ ├── src │ │ ├── rsa2048 │ │ │ ├── mod.rs │ │ │ └── dbig.rs │ │ ├── rsa3072 │ │ │ ├── mod.rs │ │ │ └── dbig.rs │ │ ├── rsa4096 │ │ │ └── mod.rs │ │ ├── secp256k1 │ │ │ ├── mod.rs │ │ │ └── rom.rs │ │ ├── c41417 │ │ │ ├── mod.rs │ │ │ ├── rom.rs │ │ │ └── dbig.rs │ │ ├── goldilocks │ │ │ ├── mod.rs │ │ │ └── rom.rs │ │ ├── nist256 │ │ │ ├── mod.rs │ │ │ ├── rom.rs │ │ │ └── dbig.rs │ │ ├── nist384 │ │ │ ├── mod.rs │ │ │ ├── rom.rs │ │ │ └── dbig.rs │ │ ├── nist521 │ │ │ ├── mod.rs │ │ │ ├── rom.rs │ │ │ └── dbig.rs │ │ ├── bls381 │ │ │ ├── mod.rs │ │ │ ├── rom.rs │ │ │ └── dbig.rs │ │ ├── bls461 │ │ │ ├── mod.rs │ │ │ ├── rom.rs │ │ │ └── dbig.rs │ │ ├── bn254 │ │ │ ├── mod.rs │ │ │ ├── rom.rs │ │ │ └── dbig.rs │ │ ├── lib.rs │ │ ├── arch.rs │ │ ├── rand.rs │ │ ├── hash256.rs │ │ ├── hash384.rs │ │ ├── hash512.rs │ │ └── sha3.rs │ └── Cargo.toml ├── docs │ └── AnonCred.pdf ├── include │ ├── indy_crypto.h │ ├── indy_crypto_bls.h │ ├── indy_crypto_cl.h │ └── indy_crypto_error.h ├── rustlibsecp256k1 │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── build.rs ├── bin │ ├── test_ed25519.rs │ └── test_secp256k1.rs └── Cargo.toml ├── Cargo.toml ├── .gitignore ├── CONTRIBUTING.md ├── docs ├── source │ ├── contents.rst │ ├── community │ │ ├── code_of_conduct.rst │ │ ├── join_the_discussion.rst │ │ ├── issue_tracking.rst │ │ └── contributing.rst │ ├── community.rst │ ├── introduction.rst │ └── conf.py └── Makefile ├── Jenkinsfile.ci └── README.md /libhl-crypto/debian/compat: -------------------------------------------------------------------------------- 1 | 9 2 | -------------------------------------------------------------------------------- /libhl-crypto/.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | -------------------------------------------------------------------------------- /libhl-crypto/ci/.gitattributes: -------------------------------------------------------------------------------- 1 | *.sh text eol=lf -------------------------------------------------------------------------------- /libhl-crypto/debian/source/format: -------------------------------------------------------------------------------- 1 | 3.0 (native) 2 | -------------------------------------------------------------------------------- /libhl-crypto/src/encoding/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod hex; 2 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "libhl-crypto", 4 | ] 5 | -------------------------------------------------------------------------------- /libhl-crypto/debian/rules: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | # 3 | 4 | %: 5 | dh $@ 6 | -------------------------------------------------------------------------------- /libhl-crypto/debian/libindy-crypto.install: -------------------------------------------------------------------------------- 1 | target/release/libindy_crypto.so usr/lib/ 2 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/Cargo.lock: -------------------------------------------------------------------------------- 1 | [[package]] 2 | name = "amcl" 3 | version = "0.1.0" 4 | 5 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/rsa2048/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod ff; 4 | pub mod rsa; 5 | 6 | 7 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/rsa3072/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod ff; 4 | pub mod rsa; 5 | 6 | 7 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/rsa4096/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod ff; 4 | pub mod rsa; 5 | 6 | 7 | -------------------------------------------------------------------------------- /libhl-crypto/docs/AnonCred.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyperledger-labs/crypto-lib/HEAD/libhl-crypto/docs/AnonCred.pdf -------------------------------------------------------------------------------- /libhl-crypto/debian/libindy-crypto-dev.install: -------------------------------------------------------------------------------- 1 | include/*.h usr/include/indy_crypto/ 2 | target/release/libindy_crypto.a usr/lib/ 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | cargo-registry 2 | target 3 | build 4 | .idea 5 | .venv 6 | .cache 7 | .DS_Store 8 | Cargo.lock 9 | Podfile.lock 10 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/secp256k1/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod fp; 4 | pub mod ecp; 5 | pub mod ecdh; 6 | pub mod rom; 7 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/c41417/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod fp; 4 | pub mod ecp; 5 | pub mod ecdh; 6 | pub mod rom; 7 | 8 | 9 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/goldilocks/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod fp; 4 | pub mod ecp; 5 | pub mod ecdh; 6 | pub mod rom; 7 | 8 | 9 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/nist256/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod fp; 4 | pub mod ecp; 5 | pub mod ecdh; 6 | pub mod rom; 7 | 8 | 9 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/nist384/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod fp; 4 | pub mod ecp; 5 | pub mod ecdh; 6 | pub mod rom; 7 | 8 | 9 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/nist521/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod fp; 4 | pub mod ecp; 5 | pub mod ecdh; 6 | pub mod rom; 7 | 8 | 9 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "amcl_3" 3 | version = "0.1.0" 4 | authors = ["Michael Lodder "] 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /libhl-crypto/debian/copyright: -------------------------------------------------------------------------------- 1 | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | 3 | Files: * 4 | Copyright: Copyright 2018 Hyperledger 5 | License: Apache 2.0 -------------------------------------------------------------------------------- /libhl-crypto/include/indy_crypto.h: -------------------------------------------------------------------------------- 1 | #ifndef __indy__crypto__included__ 2 | #define __indy__crypto__included__ 3 | 4 | #include "indy_crypto_error.h" 5 | #include "indy_crypto_bls.h" 6 | 7 | #endif 8 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/bls381/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod fp; 4 | pub mod ecp; 5 | pub mod ecp2; 6 | pub mod fp2; 7 | pub mod fp4; 8 | pub mod fp12; 9 | pub mod pair; 10 | pub mod mpin; 11 | pub mod rom; 12 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/bls461/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod fp; 4 | pub mod ecp; 5 | pub mod ecp2; 6 | pub mod fp2; 7 | pub mod fp4; 8 | pub mod fp12; 9 | pub mod pair; 10 | pub mod mpin; 11 | pub mod rom; 12 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/bn254/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod big; 2 | pub mod dbig; 3 | pub mod fp; 4 | pub mod ecp; 5 | pub mod ecp2; 6 | pub mod fp2; 7 | pub mod fp4; 8 | pub mod fp12; 9 | pub mod pair; 10 | pub mod mpin; 11 | pub mod rom; 12 | -------------------------------------------------------------------------------- /libhl-crypto/src/utils/logger.rs: -------------------------------------------------------------------------------- 1 | #[cfg(debug_assertions)] 2 | #[macro_export] 3 | macro_rules! secret { 4 | ($val:expr) => {{ $val }}; 5 | } 6 | 7 | #[cfg(not(debug_assertions))] 8 | #[macro_export] 9 | macro_rules! secret { 10 | ($val:expr) => {{ "_" }}; 11 | } -------------------------------------------------------------------------------- /libhl-crypto/rustlibsecp256k1/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rustlibsecp256k1" 3 | version = "0.1.0" 4 | authors = ["Michael Lodder "] 5 | description = "Solely exists to prevent a namespace collision with secp256k1" 6 | 7 | [dependencies] 8 | libsecp256k1 = "0.1.14" 9 | -------------------------------------------------------------------------------- /libhl-crypto/include/indy_crypto_bls.h: -------------------------------------------------------------------------------- 1 | #ifndef __indy__crypto__bls__included__ 2 | #define __indy__crypto__bls__included__ 3 | 4 | #ifdef __cplusplus 5 | extern "C" { 6 | #endif 7 | 8 | /// TODO: FIXME: Probide list of interfaces for ffi/bls.rs 9 | 10 | #ifdef __cplusplus 11 | } 12 | #endif 13 | 14 | #endif 15 | 16 | -------------------------------------------------------------------------------- /libhl-crypto/include/indy_crypto_cl.h: -------------------------------------------------------------------------------- 1 | #ifndef __indy__crypto__cl__included__ 2 | #define __indy__crypto__cl__included__ 3 | 4 | #ifdef __cplusplus 5 | extern "C" { 6 | #endif 7 | 8 | /// TODO: FIXME: Probide list of interfaces for ffi/cl/mod.rs 9 | 10 | #ifdef __cplusplus 11 | } 12 | #endif 13 | 14 | #endif 15 | 16 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Hyperledger Ursa 2 | 3 | Hyperledger Ursa is Apache 2.0 licensed and accepts contributions via 4 | [GitHub](https://github.com/hyperledger-labs/crypto-lib) pull requests. 5 | 6 | Please see 7 | [Contributing](docs/source/community/contributing.rst) 8 | in the Ursa documentation for information on how to contribute and the guidelines for contributions. 9 | 10 | -------------------------------------------------------------------------------- /docs/source/contents.rst: -------------------------------------------------------------------------------- 1 | 2 | Table of Contents 3 | ================= 4 | 5 | .. toctree:: 6 | 7 | introduction.rst 8 | community.rst 9 | 10 | Indices and tables 11 | ================== 12 | 13 | * :ref:`genindex` 14 | * :ref:`modindex` 15 | * :ref:`search` 16 | 17 | .. Licensed under Creative Commons Attribution 4.0 International License 18 | .. https://creativecommons.org/licenses/by/4.0/ 19 | 20 | 21 | -------------------------------------------------------------------------------- /docs/source/community/code_of_conduct.rst: -------------------------------------------------------------------------------- 1 | 2 | Code of Conduct 3 | =============== 4 | 5 | When participating, please be respectful and courteous. 6 | 7 | Hyperledger Ursa uses the `Hyperledger Project Code of Conduct 8 | `_. 9 | 10 | .. Licensed under Creative Commons Attribution 4.0 International License 11 | .. https://creativecommons.org/licenses/by/4.0/ 12 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod arch; 2 | pub mod aes; 3 | pub mod gcm; 4 | pub mod hash256; 5 | pub mod hash384; 6 | pub mod hash512; 7 | pub mod rand; 8 | pub mod sha3; 9 | pub mod nhs; 10 | 11 | pub mod nist256; 12 | pub mod goldilocks; 13 | pub mod nist384; 14 | pub mod c41417; 15 | pub mod nist521; 16 | pub mod secp256k1; 17 | pub mod bn254; 18 | pub mod bls381; 19 | pub mod bls461; 20 | pub mod rsa2048; 21 | pub mod rsa3072; 22 | pub mod rsa4096; 23 | -------------------------------------------------------------------------------- /docs/source/community.rst: -------------------------------------------------------------------------------- 1 | ********* 2 | Community 3 | ********* 4 | 5 | Welcome to the Ursa community! 6 | 7 | For help topics, see "Joining the Discussion" linked below. 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | 12 | community/join_the_discussion 13 | community/issue_tracking 14 | community/contributing 15 | community/code_of_conduct 16 | 17 | 18 | .. Licensed under Creative Commons Attribution 4.0 International License 19 | .. https://creativecommons.org/licenses/by/4.0/ 20 | -------------------------------------------------------------------------------- /libhl-crypto/src/keys.rs: -------------------------------------------------------------------------------- 1 | use encoding::hex::bin2hex; 2 | 3 | // A private key instance. 4 | /// The underlying content is dependent on implementation. 5 | pub struct PrivateKey(pub Vec); 6 | impl_bytearray!(PrivateKey); 7 | 8 | pub struct PublicKey(pub Vec); 9 | impl_bytearray!(PublicKey); 10 | 11 | pub struct SessionKey(pub Vec); 12 | impl_bytearray!(SessionKey); 13 | 14 | pub struct MacKey(pub Vec); 15 | impl_bytearray!(MacKey); 16 | 17 | pub enum KeyPairOption<'a> { 18 | UseSeed(Vec), 19 | FromSecretKey(&'a PrivateKey) 20 | } 21 | -------------------------------------------------------------------------------- /libhl-crypto/debian/changelog: -------------------------------------------------------------------------------- 1 | libindy-crypto (0.4.1) unstable; urgency=medium 2 | 3 | [ Indy Crypto ] 4 | * BLS: verification optimization 5 | * Rust API enhancements (add more Clone derives for structures) 6 | * CL: update link-secrets logic - allow to use multiply link-secrets as non-schema attributes 7 | Note: 8 | This version of Indy Crypto can process artifacts from previous one. 9 | But in reason of multiply link-secrets support older versions can't consume CL output of 0.4.2. 10 | 11 | -- Hyperledger Tue, 12 Sep 2017 19:19:00 +0300 12 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SOURCEDIR = source 8 | BUILDDIR = build 9 | 10 | # Put it first so that "make" without argument is like "make help". 11 | help: 12 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 13 | 14 | .PHONY: help Makefile 15 | 16 | # Catch-all target: route all unknown targets to Sphinx using the new 17 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 18 | %: Makefile 19 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /libhl-crypto/debian/control: -------------------------------------------------------------------------------- 1 | Source: libindy-crypto 2 | Section: devel 3 | Priority: optional 4 | Maintainer: Hyperledger 5 | Build-Depends: libssl1.0.0 6 | Standards-Version: 0.0.1 7 | Vcs-Git: https://github.com/hyperledger/indy-crypto/ 8 | Vcs-Browser: https://github.com/hyperledger/indy-crypto/ 9 | 10 | 11 | Package: libindy-crypto 12 | Architecture: amd64 13 | Depends: libssl1.0.0 14 | Suggests: build-essential 15 | Description: This is the shared crypto libirary for Hyperledger Indy components. 16 | 17 | Package: libindy-crypto-dev 18 | Architecture: amd64 19 | Depends: libindy-crypto 20 | Suggests: build-essential 21 | Description: This is the shared crypto libirary for Hyperledger Indy components. 22 | -------------------------------------------------------------------------------- /libhl-crypto/ci/libindy_crypto-deb-build-and-upload.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | 3 | if [ "$1" = "--help" ] ; then 4 | echo "Usage: " 5 | return 6 | fi 7 | 8 | version="$1" 9 | type="$2" 10 | suffix="$3" 11 | repo="$4" 12 | host="$5" 13 | key="$6" 14 | 15 | [ -z $version ] && exit 1 16 | [ -z $type ] && exit 2 17 | [ -z $suffix ] && exit 3 18 | [ -z $repo ] && exit 4 19 | [ -z $host ] && exit 5 20 | [ -z $key ] && exit 6 21 | 22 | sed -i -E -e 'H;1h;$!d;x' -e "s/libindy-crypto ([(,),0-9,.]+)/libindy-crypto ($version$suffix)/" debian/changelog 23 | 24 | dpkg-buildpackage -tc 25 | 26 | mkdir debs && mv ../*.deb ./debs/ 27 | 28 | ./sovrin-packaging/upload_debs.py ./debs $repo $type --host $host --ssh-key $key 29 | -------------------------------------------------------------------------------- /libhl-crypto/rustlibsecp256k1/src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate secp256k1 as libsecp256k1; 2 | 3 | pub fn sign(message: &[u8; 32], secret_key: &[u8; 32]) -> Result<[u8; 64], ()> { 4 | let msg = libsecp256k1::Message::parse(message); 5 | match libsecp256k1::SecretKey::parse(secret_key) { 6 | Ok(sk) => match libsecp256k1::sign(&msg, &sk) { 7 | Ok((sig, _)) => Ok(sig.serialize()), 8 | Err(_) => Err(()) 9 | }, 10 | Err(_) => Err(()) 11 | } 12 | } 13 | 14 | pub fn verify(message: &[u8; 32], signature: &[u8; 64], public_key: &[u8; 65]) -> Result { 15 | let msg = libsecp256k1::Message::parse(message); 16 | let sig = libsecp256k1::Signature::parse(signature); 17 | match libsecp256k1::PublicKey::parse(public_key) { 18 | Ok(pk) => Ok(libsecp256k1::verify(&msg, &sig, &pk)), 19 | Err(_) => Err(()) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /libhl-crypto/src/encoding/hex.rs: -------------------------------------------------------------------------------- 1 | use CryptoError; 2 | 3 | pub fn bin2hex(b: &[u8]) -> String { 4 | b.iter() 5 | .map(|b| format!("{:02x}", b)) 6 | .collect::>() 7 | .join("") 8 | } 9 | 10 | pub fn hex2bin(s: &str) -> Result, CryptoError> { 11 | if s.len() % 2 != 0 { 12 | return Err(CryptoError::ParseError("Invalid string".to_string())) 13 | } 14 | for (i, ch) in s.chars().enumerate() { 15 | if !ch.is_digit(16) { 16 | return Err(CryptoError::ParseError(format!("Invalid character position {}", i))); 17 | } 18 | } 19 | 20 | let input: Vec<_> = s.chars().collect(); 21 | 22 | let decoded: Vec = input.chunks(2).map(|chunk| { 23 | ((chunk[0].to_digit(16).unwrap() << 4) | 24 | (chunk[1].to_digit(16).unwrap())) as u8 25 | }).collect(); 26 | 27 | return Ok(decoded); 28 | } 29 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/arch.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | pub type Chunk=i64; 21 | pub type DChunk=i128; 22 | pub const CHUNK:usize=64; 23 | -------------------------------------------------------------------------------- /docs/source/community/join_the_discussion.rst: -------------------------------------------------------------------------------- 1 | ********************** 2 | Joining the Discussion 3 | ********************** 4 | 5 | Chat 6 | ==== 7 | 8 | Hyperledger's RocketChat server is the place to go for real-time chat about everything from quick 9 | help to involved discussions. Be mindful that chat can sometimes disclude participants who are not 10 | available at that time. Discussions with broad impact to the community should take place on the 11 | mail list. 12 | 13 | `#sawtooth `_ 14 | 15 | 16 | 17 | Mailing Lists 18 | ============= 19 | 20 | The Hyperledger Ursa mailing list is the prefered place for discussions about decisional matters 21 | for the project: 22 | 23 | `hyperledger-ursa Mailing List `_ 24 | 25 | 26 | .. Licensed under Creative Commons Attribution 4.0 International License 27 | .. https://creativecommons.org/licenses/by/4.0/ 28 | -------------------------------------------------------------------------------- /libhl-crypto/ci/libindy_crypto-win-zip-and-upload.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | 3 | if [ "$1" = "--help" ] ; then 4 | echo "Usage: " 5 | return 6 | fi 7 | 8 | version="$1" 9 | key="$2" 10 | type="$3" 11 | number="$4" 12 | 13 | [ -z $version ] && exit 1 14 | [ -z $key ] && exit 2 15 | [ -z $type ] && exit 3 16 | [ -z $number ] && exit 4 17 | 18 | mkdir libindy_crypto-zip 19 | mkdir libindy_crypto-zip/lib 20 | cp -r ./include ./libindy_crypto-zip 21 | cp ./target/release/*.dll ./libindy_crypto-zip/lib/ 22 | 23 | cd libindy_crypto-zip && zip -r libindy_crypto_${version}.zip ./* && mv libindy_crypto_${version}.zip .. && cd .. 24 | 25 | rm -rf libindy_crypto-zip 26 | 27 | cat < {}", &prebuilt_lib.join(f).display(), &dst.join(f).display()); 24 | } 25 | } 26 | return; 27 | } else if let Some(..) = target.find("darwin") { 28 | println!("entered"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /docs/source/introduction.rst: -------------------------------------------------------------------------------- 1 | ************ 2 | Introduction 3 | ************ 4 | 5 | Hyperledger Ursa is a cryptography library designed to support Hyperledger 6 | projects and experimentation. This project is just getting started and should 7 | not yet be considered stable or reviewed for production uses. 8 | 9 | Ursa is an open source project under the Hyperledger umbrella. For 10 | information on how to contribute, see `Join the Ursa Community`_. 11 | 12 | 13 | Get the Ursa Software 14 | ------------------------- 15 | 16 | The Ursa software is distributed as source code with an Apache 2.0 license. 17 | 18 | * `ursa `_: 19 | Contains the main interface and wrappers for the selected libraries. 20 | 21 | * `zmix `_: 22 | Contains interfaces for zero-knowledge proofs. 23 | 24 | 25 | Join the Ursa Community 26 | --------------------------- 27 | 28 | Ursa is an open source project under the Hyperledger umbrella. We welcome 29 | working with individuals and companies interested in advancing distributed 30 | ledger technology. Please see :doc:`/community` for ways to become a part of 31 | the Ursa community. 32 | 33 | 34 | .. Licensed under Creative Commons Attribution 4.0 International License 35 | .. https://creativecommons.org/licenses/by/4.0/ 36 | -------------------------------------------------------------------------------- /libhl-crypto/src/cl/constants.rs: -------------------------------------------------------------------------------- 1 | use bn::{BigNumber, BIGNUMBER_2}; 2 | 3 | pub const LARGE_MASTER_SECRET: usize = 256; 4 | pub const LARGE_E_START: usize = 596; 5 | pub const LARGE_E_END_RANGE: usize = 119; 6 | pub const LARGE_PRIME: usize = 1024; 7 | pub const LARGE_VPRIME: usize = 2128; 8 | pub const LARGE_VPRIME_PRIME: usize = 2724; 9 | pub const LARGE_MVECT: usize = 592; 10 | pub const LARGE_ETILDE: usize = 456; 11 | pub const LARGE_VTILDE: usize = 3060; 12 | pub const LARGE_UTILDE: usize = 592; 13 | pub const LARGE_MTILDE: usize = 593; 14 | pub const LARGE_VPRIME_TILDE: usize = 673; 15 | pub const LARGE_RTILDE: usize = 672; 16 | pub const ITERATION: usize = 4; 17 | /* 18 | LARGE_M1_TILDE: now it differs from the paper v0.3, but author of the paper, 19 | Dmitry Khovratovich, suggests to use same size as LARGE_MVECT 20 | FIXME sync the paper and remove this comment 21 | */ 22 | pub const LARGE_NONCE: usize = 80; 23 | pub const LARGE_ALPHATILDE: usize = 2787; 24 | 25 | // Constants that are used throughout the CL signatures code, so avoiding recomputation. 26 | lazy_static! { 27 | pub static ref LARGE_E_START_VALUE: BigNumber = BIGNUMBER_2.exp( 28 | &BigNumber::from_u32(LARGE_E_START).unwrap(), 29 | None).unwrap(); 30 | pub static ref LARGE_E_END_RANGE_VALUE: BigNumber = BIGNUMBER_2.exp( 31 | &BigNumber::from_u32(LARGE_E_END_RANGE).unwrap(), 32 | None).unwrap().add(&LARGE_E_START_VALUE).unwrap(); 33 | pub static ref LARGE_VPRIME_PRIME_VALUE: BigNumber = BIGNUMBER_2.exp( 34 | &BigNumber::from_u32(LARGE_VPRIME_PRIME - 1).unwrap(), None).unwrap(); 35 | } 36 | -------------------------------------------------------------------------------- /libhl-crypto/ci/ubuntu.dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:16.04 2 | 3 | ARG uid=1000 4 | 5 | RUN apt-get update && \ 6 | apt-get install -y \ 7 | pkg-config \ 8 | libssl-dev \ 9 | curl \ 10 | build-essential \ 11 | cmake \ 12 | git \ 13 | python3.5 \ 14 | python3-pip \ 15 | python-setuptools \ 16 | apt-transport-https \ 17 | ca-certificates \ 18 | debhelper \ 19 | wget \ 20 | devscripts 21 | 22 | 23 | RUN pip3 install -U \ 24 | pip \ 25 | setuptools \ 26 | virtualenv 27 | 28 | ENV RUST_ARCHIVE=rust-1.25.0-x86_64-unknown-linux-gnu.tar.gz 29 | ENV RUST_DOWNLOAD_URL=https://static.rust-lang.org/dist/$RUST_ARCHIVE 30 | 31 | RUN mkdir -p /rust 32 | WORKDIR /rust 33 | 34 | RUN curl -fsOSL $RUST_DOWNLOAD_URL \ 35 | && curl -s $RUST_DOWNLOAD_URL.sha256 | sha256sum -c - \ 36 | && tar -C /rust -xzf $RUST_ARCHIVE --strip-components=1 \ 37 | && rm $RUST_ARCHIVE \ 38 | && ./install.sh 39 | 40 | ENV PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.cargo/bin" 41 | 42 | RUN apt-get install -y zip 43 | 44 | RUN useradd -ms /bin/bash -u $uid indy 45 | USER indy 46 | 47 | RUN cargo install --git https://github.com/DSRCorporation/cargo-test-xunit 48 | 49 | WORKDIR /home/indy 50 | 51 | USER root 52 | RUN pip3 install \ 53 | twine 54 | 55 | USER indy 56 | RUN virtualenv -p python3.5 /home/indy/test 57 | USER root 58 | RUN ln -sf /home/indy/test/bin/python /usr/local/bin/python3 59 | RUN ln -sf /home/indy/test/bin/pip /usr/local/bin/pip3 60 | 61 | RUN pip3 install -U pip plumbum deb-pkg-tools 62 | RUN apt-get install -y ruby-dev 63 | RUN gem install fpm -------------------------------------------------------------------------------- /docs/source/community/issue_tracking.rst: -------------------------------------------------------------------------------- 1 | *************** 2 | Tracking Issues 3 | *************** 4 | 5 | A great way to contribute is by reporting issues. Before reporting an issue, 6 | please review the current open issues to see if someone has already reported 7 | the issue. 8 | 9 | .. _jira: 10 | 11 | Using JIRA 12 | ========== 13 | 14 | Hyperledger Ursa uses JIRA as our issue tracking system: 15 | 16 | https://jira.hyperledger.org/projects/ 17 | 18 | 19 | How to Report an Issue 20 | ====================== 21 | 22 | If you believe the issue impacts the security of a production release of a 23 | Hyperledger project please use the responsible reporting mechanism found here: 24 | https://wiki.hyperledger.org/security 25 | 26 | To report all other issues, log into `jira.hyperledger.org 27 | `_, which requires a 28 | `Linux Foundation Account `_. 29 | 30 | Create issues in JIRA under the Hyperledger Ursa project. 31 | 32 | When reporting an issue, please provide as much detail as possible about how 33 | to reproduce it. If possible, explain how to reproduce the issue. 34 | Details are very helpful. Please include the following information: 35 | 36 | * OS version 37 | * Ursa version 38 | * Environment details (virtual, physical, etc.) 39 | * Steps to reproduce the issue 40 | * Actual results 41 | * Expected results 42 | 43 | If you would like, you could also describe the issue on RocketChat 44 | (see :doc:`join_the_discussion`) 45 | for initial feedback before submitting the issue in JIRA. 46 | 47 | .. Licensed under Creative Commons Attribution 4.0 International License 48 | .. https://creativecommons.org/licenses/by/4.0/ 49 | -------------------------------------------------------------------------------- /libhl-crypto/src/hash/mod.rs: -------------------------------------------------------------------------------- 1 | use CryptoError; 2 | 3 | #[derive(Debug)] 4 | pub enum DigestAlgorithm { 5 | Sha2_256, 6 | Sha2_384, 7 | Sha2_512, 8 | Blake2b256, 9 | Blake2b384, 10 | Blake2b512 11 | } 12 | 13 | pub fn digest(algorithm: DigestAlgorithm, message: &[u8]) -> Result, CryptoError> { 14 | match algorithm { 15 | DigestAlgorithm::Sha2_256 => { 16 | let mut hash = sha2::Sha256::new(); 17 | hash.update(message); 18 | hash.finalize() 19 | }, 20 | DigestAlgorithm::Sha2_384 => { 21 | let mut hash = sha2::Sha384::new(); 22 | hash.update(message); 23 | hash.finalize() 24 | }, 25 | DigestAlgorithm::Sha2_512 => { 26 | let mut hash = sha2::Sha512::new(); 27 | hash.update(message); 28 | hash.finalize() 29 | } 30 | DigestAlgorithm::Blake2b256 => { 31 | let mut hash = blake2::Blake2b256::new(); 32 | hash.update(message); 33 | hash.finalize() 34 | } 35 | DigestAlgorithm::Blake2b384 => { 36 | let mut hash = blake2::Blake2b384::new(); 37 | hash.update(message); 38 | hash.finalize() 39 | }, 40 | DigestAlgorithm::Blake2b512 => { 41 | let mut hash = blake2::Blake2b512::new(); 42 | hash.update(message); 43 | hash.finalize() 44 | } 45 | } 46 | } 47 | 48 | pub trait Digest { 49 | fn new() -> Self where Self : Sized; 50 | fn reset(&mut self); 51 | fn update(&mut self, data: &[u8]); 52 | fn finalize(&mut self) -> Result, CryptoError>; 53 | } 54 | 55 | pub mod sha2; 56 | pub mod blake2; 57 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/secp256k1/rom.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | /* Fixed Data in ROM - Field and Curve parameters */ 21 | 22 | use secp256k1::big::NLEN; 23 | use arch::Chunk; 24 | 25 | // Base Bits= 56 26 | // secp256k1 modulus 27 | pub const MODULUS:[Chunk;NLEN]=[0xFFFFFEFFFFFC2F,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFF,0xFFFFFFFF]; 28 | pub const R2MODP:[Chunk;NLEN]=[0xA1000000000000,0x7A2000E90,0x1,0x0,0x0]; 29 | pub const MCONST:Chunk=0x38091DD2253531; 30 | 31 | // secp256k1 curve 32 | pub const CURVE_A:isize = 0; 33 | pub const CURVE_COF_I:isize = 1; 34 | pub const CURVE_COF:[Chunk;NLEN]=[0x1,0x0,0x0,0x0,0x0]; 35 | pub const CURVE_B_I:isize = 7; 36 | pub const CURVE_B:[Chunk;NLEN]=[0x7,0x0,0x0,0x0,0x0]; 37 | pub const CURVE_ORDER:[Chunk;NLEN]=[0xD25E8CD0364141,0xDCE6AF48A03BBF,0xFFFFFFFFFEBAAE,0xFFFFFFFFFFFFFF,0xFFFFFFFF]; 38 | pub const CURVE_GX:[Chunk;NLEN]=[0xF2815B16F81798,0xFCDB2DCE28D959,0x95CE870B07029B,0xF9DCBBAC55A062,0x79BE667E]; 39 | pub const CURVE_GY:[Chunk;NLEN]=[0x47D08FFB10D4B8,0xB448A68554199C,0xFC0E1108A8FD17,0x26A3C4655DA4FB,0x483ADA77]; 40 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/c41417/rom.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use c41417::big::NLEN; 21 | use arch::Chunk; 22 | 23 | // Base Bits= 60 24 | // c41417 Modulus 25 | pub const MODULUS:[Chunk;NLEN]=[0xFFFFFFFFFFFFFEF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0x3FFFFFFFFFFFFF]; 26 | pub const R2MODP:[Chunk;NLEN]=[0x121000,0x0,0x0,0x0,0x0,0x0,0x0]; 27 | pub const MCONST:Chunk=0x11; 28 | 29 | // c41417 Curve 30 | pub const CURVE_COF_I:isize = 8; 31 | pub const CURVE_A:isize = 1; 32 | pub const CURVE_B_I:isize = 3617; 33 | pub const CURVE_COF:[Chunk;NLEN]=[0x8,0x0,0x0,0x0,0x0,0x0,0x0]; 34 | pub const CURVE_B:[Chunk;NLEN]=[0xE21,0x0,0x0,0x0,0x0,0x0,0x0]; 35 | pub const CURVE_ORDER:[Chunk;NLEN]=[0xB0E71A5E106AF79,0x1C0338AD63CF181,0x414CF706022B36F,0xFFFFFFFFEB3CC92,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0x7FFFFFFFFFFFF]; 36 | pub const CURVE_GX:[Chunk;NLEN]=[0x4FD3812F3CBC595,0x1A73FAA8537C64C,0x4AB4D6D6BA11130,0x3EC7F57FF35498A,0xE5FCD46369F44C0,0x300218C0631C326,0x1A334905141443]; 37 | pub const CURVE_GY:[Chunk;NLEN]=[0x22,0x0,0x0,0x0,0x0,0x0,0x0]; 38 | 39 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/nist256/rom.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | /* Fixed Data in ROM - Field and Curve parameters */ 21 | 22 | use nist256::big::NLEN; 23 | use arch::Chunk; 24 | 25 | // Base Bits= 56 26 | // nist256 modulus 27 | pub const MODULUS:[Chunk;NLEN]=[0xFFFFFFFFFFFFFF,0xFFFFFFFFFF,0x0,0x1000000,0xFFFFFFFF]; 28 | pub const R2MODP:[Chunk;NLEN]=[0x3000000050000,0x0,0xFFFFFBFFFFFFFA,0xFFFAFFFFFFFEFF,0x2FFFF]; 29 | pub const MCONST:Chunk=0x1; 30 | 31 | // nist256 curve 32 | pub const CURVE_COF_I:isize = 1; 33 | pub const CURVE_A:isize = -3; 34 | pub const CURVE_B_I:isize = 0; 35 | pub const CURVE_COF:[Chunk;NLEN]=[0x1,0x0,0x0,0x0,0x0]; 36 | pub const CURVE_B:[Chunk;NLEN]=[0xCE3C3E27D2604B,0x6B0CC53B0F63B,0x55769886BC651D,0xAA3A93E7B3EBBD,0x5AC635D8]; 37 | pub const CURVE_ORDER:[Chunk;NLEN]=[0xB9CAC2FC632551,0xFAADA7179E84F3,0xFFFFFFFFFFBCE6,0xFFFFFF,0xFFFFFFFF]; 38 | pub const CURVE_GX:[Chunk;NLEN]=[0xA13945D898C296,0x7D812DEB33A0F4,0xE563A440F27703,0xE12C4247F8BCE6,0x6B17D1F2]; 39 | pub const CURVE_GY:[Chunk;NLEN]=[0xB6406837BF51F5,0x33576B315ECECB,0x4A7C0F9E162BCE,0xFE1A7F9B8EE7EB,0x4FE342E2]; 40 | 41 | -------------------------------------------------------------------------------- /libhl-crypto/bin/test_ed25519.rs: -------------------------------------------------------------------------------- 1 | extern crate hl_crypto; 2 | extern crate libsodium_ffi as ffi; 3 | 4 | use hl_crypto::signatures::ed25519::Ed25519Sha512; 5 | use hl_crypto::signatures::SignatureScheme; 6 | 7 | use std::io; 8 | use std::io::Write; 9 | use std::time::Instant; 10 | 11 | fn main() { 12 | let letters = b"abcdefghijklmnopqrstuvwxyz"; 13 | let trials = 200; 14 | println!("Running 3 tests for ed25519 signing of {} messages", trials); 15 | print!("This library - "); 16 | io::stdout().flush().unwrap(); 17 | let scheme = Ed25519Sha512::new(); 18 | let (p, s) = scheme.keypair(None).unwrap(); 19 | let mut now = Instant::now(); 20 | 21 | for _ in 0..trials { 22 | let signature = scheme.sign(&letters[..], &s).unwrap(); 23 | scheme.verify(&letters[..], &signature, &p).unwrap(); 24 | } 25 | let elapsed = now.elapsed(); 26 | println!("{}.{:03}", elapsed.as_secs(), elapsed.subsec_millis()); 27 | 28 | let mut signature = [0u8; 64]; 29 | print!("libsodium based ed25519 - "); 30 | io::stdout().flush().unwrap(); 31 | 32 | now = Instant::now(); 33 | for _ in 0..trials { 34 | unsafe { 35 | ffi::crypto_sign_ed25519_detached(signature.as_mut_ptr() as *mut u8, 36 | 0u64 as *mut u64, 37 | letters.as_ptr() as *const u8, 38 | letters.len() as u64, 39 | s.as_ptr() as *const u8); 40 | 41 | ffi::crypto_sign_ed25519_verify_detached(signature.as_ptr() as *const u8, 42 | letters.as_ptr() as *const u8, 43 | letters.len() as u64, 44 | p.as_ptr() as *const u8) 45 | }; 46 | } 47 | 48 | let elapsed = now.elapsed(); 49 | println!("{}.{:03}", elapsed.as_secs(), elapsed.subsec_millis()); 50 | } 51 | -------------------------------------------------------------------------------- /libhl-crypto/include/indy_crypto_error.h: -------------------------------------------------------------------------------- 1 | #ifndef __indy__crypto__error__included__ 2 | #define __indy__cryoto__error__included__ 3 | 4 | typedef enum 5 | { 6 | Success = 0, 7 | 8 | // Common errors 9 | 10 | // Caller passed invalid value as param 1 (null, invalid json and etc..) 11 | CommonInvalidParam1 = 100, 12 | 13 | // Caller passed invalid value as param 2 (null, invalid json and etc..) 14 | CommonInvalidParam2 = 101, 15 | 16 | // Caller passed invalid value as param 3 (null, invalid json and etc..) 17 | CommonInvalidParam3 = 102, 18 | 19 | // Caller passed invalid value as param 4 (null, invalid json and etc..) 20 | CommonInvalidParam4 = 103, 21 | 22 | // Caller passed invalid value as param 5 (null, invalid json and etc..) 23 | CommonInvalidParam5 = 104, 24 | 25 | // Caller passed invalid value as param 6 (null, invalid json and etc..) 26 | CommonInvalidParam6 = 105, 27 | 28 | // Caller passed invalid value as param 7 (null, invalid json and etc..) 29 | CommonInvalidParam7 = 106, 30 | 31 | // Caller passed invalid value as param 8 (null, invalid json and etc..) 32 | CommonInvalidParam8 = 107, 33 | 34 | // Caller passed invalid value as param 9 (null, invalid json and etc..) 35 | CommonInvalidParam9 = 108, 36 | 37 | // Caller passed invalid value as param 10 (null, invalid json and etc..) 38 | CommonInvalidParam10 = 109, 39 | 40 | // Caller passed invalid value as param 11 (null, invalid json and etc..) 41 | CommonInvalidParam11 = 110, 42 | 43 | // Caller passed invalid value as param 12 (null, invalid json and etc..) 44 | CommonInvalidParam12 = 111, 45 | 46 | // Invalid library state was detected in runtime. It signals library bug 47 | CommonInvalidState = 112, 48 | 49 | // Object (json, config, key, credential and etc...) passed by library caller has invalid structure 50 | CommonInvalidStructure = 113, 51 | 52 | // IO Error 53 | CommonIOError = 114, 54 | } indy_crypto_error_t; 55 | 56 | #endif 57 | 58 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/nist384/rom.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use nist384::big::NLEN; 21 | use arch::Chunk; 22 | 23 | // Base Bits= 56 24 | // nist384 Modulus 25 | pub const MODULUS:[Chunk;NLEN]=[0xFFFFFFFF,0xFFFF0000000000,0xFFFFFFFFFEFFFF,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFF]; 26 | pub const R2MODP:[Chunk;NLEN]=[0xFE000000010000,0xFFFFFF,0x2,0xFFFFFFFE00,0x1000000020000,0x0,0x0]; 27 | pub const MCONST:Chunk=0x100000001; 28 | 29 | // nist384 Curve 30 | pub const CURVE_COF_I:isize = 1; 31 | pub const CURVE_A:isize = -3; 32 | pub const CURVE_B_I:isize = 0; 33 | pub const CURVE_COF:[Chunk;NLEN]=[0x1,0x0,0x0,0x0,0x0,0x0,0x0]; 34 | pub const CURVE_B:[Chunk;NLEN]=[0x85C8EDD3EC2AEF,0x398D8A2ED19D2A,0x8F5013875AC656,0xFE814112031408,0xF82D19181D9C6E,0xE7E4988E056BE3,0xB3312FA7E23E]; 35 | pub const CURVE_ORDER:[Chunk;NLEN]=[0xEC196ACCC52973,0xDB248B0A77AEC,0x81F4372DDF581A,0xFFFFFFFFC7634D,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFF]; 36 | pub const CURVE_GX:[Chunk;NLEN]=[0x545E3872760AB7,0xF25DBF55296C3A,0xE082542A385502,0x8BA79B9859F741,0x20AD746E1D3B62,0x5378EB1C71EF3,0xAA87CA22BE8B]; 37 | pub const CURVE_GY:[Chunk;NLEN]=[0x431D7C90EA0E5F,0xB1CE1D7E819D7A,0x13B5F0B8C00A60,0x289A147CE9DA31,0x92DC29F8F41DBD,0x2C6F5D9E98BF92,0x3617DE4A9626]; 38 | 39 | -------------------------------------------------------------------------------- /libhl-crypto/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crypto_lib" 3 | version = "0.1.0" 4 | authors = ["Michael Lodder "] 5 | description = "This is the shared crypto library for Hyperledger components." 6 | license = "MIT/Apache-2.0" 7 | 8 | [lib] 9 | name = "hl_crypto" 10 | path = "src/lib.rs" 11 | crate-type = ["staticlib","rlib", "dylib"] 12 | 13 | [[bin]] 14 | name = "test_secp256k1" 15 | path = "bin/test_secp256k1.rs" 16 | required-features = ["benchmarksecp256k1"] 17 | 18 | [[bin]] 19 | name = "test_ed25519" 20 | path = "bin/test_ed25519.rs" 21 | required-features = ["benchmarked25519"] 22 | 23 | [features] 24 | default = ["bn_openssl", "pair_amcl", "serialization", "native"] 25 | portable = ["bn_openssl", "pair_amcl", "serialization", "arrayref", "rust-crypto", "rustlibsecp256k1"] 26 | native = ["secp256k1", "libsodium-ffi"] 27 | bn_openssl = ["openssl", "int_traits"] 28 | pair_amcl = ["amcl"] 29 | serialization = ["serde", "serde_json", "serde_derive"] 30 | benchmarksecp256k1 = ["secp256k1", "openssl"] 31 | benchmarked25519 = ["libsodium-ffi"] 32 | 33 | [dependencies] 34 | amcl = { version = "0.1.2", optional = true, default-features = false, features = ["BN254"]} 35 | amcl_3 = { path = "amcl" } 36 | int_traits = { version = "0.1.1", optional = true } 37 | arrayref = { version = "0.3.5", optional = true } 38 | libc = "0.2.33" 39 | log = "0.3.8" 40 | rand = "0.3" 41 | sha2 = "0.7.1" 42 | sha3 = "0.7.3" 43 | time = "0.1.36" 44 | env_logger = "0.4.3" 45 | blake2b_simd = "0.3.1" 46 | openssl = { version = "0.10.11", optional = true } 47 | serde = { version = "1.0", optional = true} 48 | serde_json = { version = "1.0", optional = true} 49 | serde_derive = { version = "1.0", optional = true} 50 | lazy_static = "1.0" 51 | secp256k1 = { version = "0.10.0", optional = true, features = ["rand", "serde"]} 52 | libsodium-ffi = { version = "0.1.12", optional = true } 53 | rust-crypto = { version = "0.2.36", optional = true } 54 | rustlibsecp256k1 = { path = "rustlibsecp256k1", optional = true } 55 | 56 | [dev-dependencies] 57 | secp256k1 = "0.10.0" 58 | libsodium-ffi = "0.1.12" 59 | rustlibsecp256k1 = { path = "rustlibsecp256k1" } 60 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/goldilocks/rom.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use goldilocks::big::NLEN; 21 | use arch::Chunk; 22 | 23 | // Base Bits= 58 24 | // Goldilocks modulus 25 | pub const MODULUS:[Chunk;NLEN]=[0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FBFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFF]; 26 | pub const R2MODP:[Chunk;NLEN]=[0x200000000,0x0,0x0,0x0,0x3000000,0x0,0x0,0x0]; 27 | pub const MCONST:Chunk=0x1; 28 | 29 | // Goldilocks curve 30 | pub const CURVE_COF_I:isize = 4; 31 | pub const CURVE_A:isize = 1; 32 | pub const CURVE_B_I:isize = -39081; 33 | pub const CURVE_COF:[Chunk;NLEN]=[0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x0]; 34 | pub const CURVE_B:[Chunk;NLEN]=[0x3FFFFFFFFFF6756,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FBFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFF]; 35 | pub const CURVE_ORDER:[Chunk;NLEN]=[0x378C292AB5844F3,0x3309CA37163D548,0x1B49AED63690216,0x3FDF3288FA7113B,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0xFFFFFFFFFF]; 36 | pub const CURVE_GX:[Chunk;NLEN]=[0x155555555555555,0x155555555555555,0x155555555555555,0x2A5555555555555,0x2AAAAAAAAAAAAAA,0x2AAAAAAAAAAAAAA,0x2AAAAAAAAAAAAAA,0x2AAAAAAAAAA]; 37 | pub const CURVE_GY:[Chunk;NLEN]=[0x2EAFBCDEA9386ED,0x32CAFB473681AF6,0x25833A2A3098BBB,0x1CA2B6312E03595,0x35884DD7B7E36D,0x21B0AC00DBB5E8,0x17048DB359D6205,0x2B817A58D2B]; 38 | 39 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/nist521/rom.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use nist521::big::NLEN; 21 | use arch::Chunk; 22 | 23 | // Base Bits= 60 24 | // nist521 Modulus 25 | pub const MODULUS:[Chunk;NLEN]=[0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0x1FFFFFFFFFF]; 26 | pub const R2MODP:[Chunk;NLEN]=[0x4000000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]; 27 | pub const MCONST:Chunk=0x1; 28 | 29 | // nist521 Curve 30 | pub const CURVE_COF_I:isize = 1; 31 | pub const CURVE_A:isize = -3; 32 | pub const CURVE_B_I:isize = 0; 33 | pub const CURVE_COF:[Chunk;NLEN]=[0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]; 34 | pub const CURVE_B:[Chunk;NLEN]=[0xF451FD46B503F00,0x73DF883D2C34F1E,0x2C0BD3BB1BF0735,0x3951EC7E937B165,0x9918EF109E15619,0x5B99B315F3B8B48,0xB68540EEA2DA72,0x8E1C9A1F929A21A,0x51953EB961]; 35 | pub const CURVE_ORDER:[Chunk;NLEN]=[0xB6FB71E91386409,0xB5C9B8899C47AEB,0xC0148F709A5D03B,0x8783BF2F966B7FC,0xFFFFFFFFFFA5186,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0x1FFFFFFFFFF]; 36 | pub const CURVE_GX:[Chunk;NLEN]=[0x97E7E31C2E5BD66,0x48B3C1856A429BF,0xDC127A2FFA8DE33,0x5E77EFE75928FE1,0xF606B4D3DBAA14B,0x39053FB521F828A,0x62395B4429C6481,0x404E9CD9E3ECB6,0xC6858E06B7]; 37 | pub const CURVE_GY:[Chunk;NLEN]=[0x8BE94769FD16650,0x3C7086A272C2408,0xB9013FAD076135,0x72995EF42640C55,0xD17273E662C97EE,0x49579B446817AFB,0x42C7D1BD998F544,0x9A3BC0045C8A5FB,0x11839296A78]; 38 | 39 | -------------------------------------------------------------------------------- /libhl-crypto/src/signatures/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod secp256k1; 2 | pub mod ed25519; 3 | 4 | use CryptoError; 5 | use keys::{PrivateKey, PublicKey, KeyPairOption}; 6 | 7 | pub trait SignatureScheme { 8 | fn new() -> Self; 9 | fn keypair(&self, options: Option) -> Result<(PublicKey, PrivateKey), CryptoError>; 10 | fn sign(&self, message: &[u8], sk: &PrivateKey) -> Result, CryptoError>; 11 | fn verify(&self, message: &[u8], signature: &[u8], pk: &PublicKey) -> Result; 12 | fn signature_size() -> usize; 13 | fn private_key_size() -> usize; 14 | fn public_key_size() -> usize; 15 | } 16 | 17 | pub struct Signer<'a, 'b, T: 'a + SignatureScheme> { 18 | scheme: &'a T, 19 | key: &'b PrivateKey 20 | } 21 | 22 | impl<'a, 'b, T: 'a + SignatureScheme> Signer<'a, 'b, T> { 23 | /// Constructs a new Signer 24 | /// 25 | /// # Arguments 26 | /// 27 | /// * `scheme` - a cryptographic signature scheme 28 | /// * `private_key` - private key 29 | pub fn new(scheme: &'a T, key: &'b PrivateKey) -> Self { 30 | Signer { scheme, key } 31 | } 32 | 33 | /// Signs the given message. 34 | /// 35 | /// # Arguments 36 | /// 37 | /// * `message` - the message bytes 38 | /// 39 | /// # Returns 40 | /// 41 | /// * `signature` - the signature bytes 42 | pub fn sign(&self, message: &[u8]) -> Result, CryptoError> { 43 | self.scheme.sign(message, self.key) 44 | } 45 | 46 | /// Return the public key for this Signer instance. 47 | /// 48 | /// # Returns 49 | /// 50 | /// * `public_key` - the public key instance 51 | pub fn get_public_key(&self) -> Result { 52 | let (pubk, _) = self.scheme.keypair(Some(KeyPairOption::FromSecretKey(self.key))).unwrap(); 53 | Ok(pubk) 54 | } 55 | } 56 | 57 | pub trait EcdsaPublicKeyHandler { 58 | /// Returns the compressed bytes 59 | fn serialize(&self, pk: &PublicKey) -> Vec; 60 | /// Returns the uncompressed bytes 61 | fn serialize_uncompressed(&self, pk: &PublicKey) -> Vec; 62 | /// Read raw bytes into key struct. Can be either compressed or uncompressed 63 | fn parse(&self, data: &[u8]) -> Result; 64 | fn public_key_uncompressed_size() -> usize; 65 | } 66 | 67 | fn get_u32(n: &[u8]) -> u32 { 68 | let mut res = 0u32; 69 | for i in 0..4 { 70 | res <<= 8; 71 | res |= n[i] as u32; 72 | } 73 | res 74 | } 75 | -------------------------------------------------------------------------------- /libhl-crypto/src/ffi/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod cl; 2 | pub mod bls; 3 | 4 | use env_logger; 5 | 6 | #[derive(Debug, PartialEq, Copy, Clone)] 7 | #[repr(usize)] 8 | pub enum ErrorCode 9 | { 10 | Success = 0, 11 | 12 | // Common errors 13 | 14 | // Caller passed invalid value as param 1 (null, invalid json and etc..) 15 | CommonInvalidParam1 = 100, 16 | 17 | // Caller passed invalid value as param 2 (null, invalid json and etc..) 18 | CommonInvalidParam2 = 101, 19 | 20 | // Caller passed invalid value as param 3 (null, invalid json and etc..) 21 | CommonInvalidParam3 = 102, 22 | 23 | // Caller passed invalid value as param 4 (null, invalid json and etc..) 24 | CommonInvalidParam4 = 103, 25 | 26 | // Caller passed invalid value as param 5 (null, invalid json and etc..) 27 | CommonInvalidParam5 = 104, 28 | 29 | // Caller passed invalid value as param 6 (null, invalid json and etc..) 30 | CommonInvalidParam6 = 105, 31 | 32 | // Caller passed invalid value as param 7 (null, invalid json and etc..) 33 | CommonInvalidParam7 = 106, 34 | 35 | // Caller passed invalid value as param 8 (null, invalid json and etc..) 36 | CommonInvalidParam8 = 107, 37 | 38 | // Caller passed invalid value as param 9 (null, invalid json and etc..) 39 | CommonInvalidParam9 = 108, 40 | 41 | // Caller passed invalid value as param 10 (null, invalid json and etc..) 42 | CommonInvalidParam10 = 109, 43 | 44 | // Caller passed invalid value as param 11 (null, invalid json and etc..) 45 | CommonInvalidParam11 = 110, 46 | 47 | // Caller passed invalid value as param 11 (null, invalid json and etc..) 48 | CommonInvalidParam12 = 111, 49 | 50 | // Invalid library state was detected in runtime. It signals library bug 51 | CommonInvalidState = 112, 52 | 53 | // Object (json, config, key, credential and etc...) passed by library caller has invalid structure 54 | CommonInvalidStructure = 113, 55 | 56 | // IO Error 57 | CommonIOError = 114, 58 | 59 | // Trying to issue non-revocation credential with full anoncreds revocation accumulator 60 | AnoncredsRevocationAccumulatorIsFull = 115, 61 | 62 | // Invalid revocation accumulator index 63 | AnoncredsInvalidRevocationAccumulatorIndex = 116, 64 | 65 | // Credential revoked 66 | AnoncredsCredentialRevoked = 117, 67 | 68 | // Proof rejected 69 | AnoncredsProofRejected = 118, 70 | } 71 | 72 | #[no_mangle] 73 | pub extern fn hl_crypto_init_logger() { 74 | env_logger::init().unwrap(); 75 | } 76 | -------------------------------------------------------------------------------- /libhl-crypto/src/utils/mod.rs: -------------------------------------------------------------------------------- 1 | #[macro_use] 2 | pub mod ctypes; 3 | pub mod commitment; 4 | pub mod rsa; 5 | #[macro_use] 6 | pub mod logger; 7 | #[macro_use] 8 | pub mod macros; 9 | 10 | use bn::BigNumber; 11 | use errors::HLCryptoError; 12 | 13 | pub fn get_hash_as_int(nums: &Vec>) -> Result { 14 | trace!("Helpers::get_hash_as_int: >>> nums: {:?}", nums); 15 | 16 | let hash = BigNumber::from_bytes(&BigNumber::hash_array(&nums)?); 17 | 18 | trace!("Helpers::get_hash_as_int: <<< hash: {:?}", hash); 19 | 20 | hash 21 | } 22 | 23 | pub fn clone_option_bignum(b: &Option) -> Result, HLCryptoError> { 24 | match *b { 25 | Some(ref bn) => Ok(Some(bn.clone()?)), 26 | None => Ok(None) 27 | } 28 | } 29 | 30 | macro_rules! hashset { 31 | ( $( $x:expr ),* ) => { 32 | { 33 | let mut set = ::std::collections::HashSet::new(); 34 | $( 35 | set.insert($x); 36 | )* 37 | set 38 | } 39 | } 40 | } 41 | 42 | macro_rules! hashmap { 43 | ($( $key: expr => $val: expr ),*) => { 44 | { 45 | let mut map = ::std::collections::HashMap::new(); 46 | $( 47 | map.insert($key, $val); 48 | )* 49 | map 50 | } 51 | } 52 | } 53 | 54 | macro_rules! btreeset { 55 | ( $( $x:expr ),* ) => { 56 | { 57 | let mut set = ::std::collections::BTreeSet::new(); 58 | $( 59 | set.insert($x); 60 | )* 61 | set 62 | } 63 | } 64 | } 65 | 66 | macro_rules! btreemap { 67 | ($( $key: expr => $val: expr ),*) => { 68 | { 69 | let mut map = ::std::collections::BTreeMap::new(); 70 | $( 71 | map.insert($key, $val); 72 | )* 73 | map 74 | } 75 | } 76 | } 77 | 78 | #[cfg(test)] 79 | mod tests { 80 | use super::*; 81 | 82 | #[test] 83 | fn get_hash_as_int_works() { 84 | let mut nums = vec![ 85 | BigNumber::from_hex("ff9d2eedfee9cffd9ef6dbffedff3fcbef4caecb9bffe79bfa94d3fdf6abfbff").unwrap().to_bytes().unwrap(), 86 | BigNumber::from_hex("ff9d2eedfee9cffd9ef6dbffedff3fcbef4caecb9bffe79bfa9168615ccbc546").unwrap().to_bytes().unwrap() 87 | ]; 88 | let res = get_hash_as_int(&mut nums); 89 | 90 | assert!(res.is_ok()); 91 | assert_eq!("2C2566C22E04AB3F18B3BA693823175002F10F400811363D26BBB33633AC8BAD", res.unwrap().to_hex().unwrap()); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /libhl-crypto/src/utils/commitment.rs: -------------------------------------------------------------------------------- 1 | use bn::{BigNumber, BigNumberContext}; 2 | use errors::HLCryptoError; 3 | 4 | 5 | /// Generate a pedersen commitment to a given number 6 | /// 7 | /// # Arguments 8 | /// * `gen_1` - first generator 9 | /// * `m` - exponent of the first generator 10 | /// * `gen_2` - second generator 11 | /// * `r` - exponent of the second generator 12 | /// * `modulus` - all computations are done this modulo 13 | /// * `ctx` - big number context 14 | /// 15 | /// # Result 16 | /// Return the pedersen commitment, i.e `(gen_1^m)*(gen_2^r)` 17 | pub fn get_pedersen_commitment(gen_1: &BigNumber, m: &BigNumber, 18 | gen_2: &BigNumber, r: &BigNumber, 19 | modulus: &BigNumber, ctx: &mut BigNumberContext) -> Result { 20 | let commitment = gen_1.mod_exp(m, modulus, Some(ctx))? 21 | .mod_mul(&gen_2.mod_exp(r, modulus, Some(ctx))?, 22 | modulus, Some(ctx))?; 23 | Ok(commitment) 24 | } 25 | 26 | 27 | /// Generate a pedersen commitment over `n` values 28 | /// 29 | /// # Arguments 30 | /// * `to_commit` - a list of 2-tuples where the first element of the tuple is a generator and 31 | /// the second is the value being committed to, like [(g_1, m_1), (g_2, m_2), (g_3, m_3), ... (g_i, m_i)] 32 | /// * `modulus` - all computations are done this modulo 33 | /// * `ctx` - big number context 34 | /// 35 | /// # Result 36 | /// Return the pedersen commitment, i.e `(g_1^m_1)*(g_2^m_2)*...(g_i^m_i)*(gen_2^r)` 37 | pub fn get_generalized_pedersen_commitment(to_commit: Vec<(&BigNumber, &BigNumber)>, 38 | modulus: &BigNumber, ctx: &mut BigNumberContext) -> Result { 39 | let accumulated = get_exponentiated_generators(to_commit, modulus, ctx)?; 40 | 41 | Ok(accumulated) 42 | } 43 | 44 | 45 | /// Exponentiate the given generators to corresponding exponents 46 | /// 47 | /// # Arguments 48 | /// * `to_exponentiate` - a list of 2-tuples where the first element of the tuple is a generator and 49 | /// the second is the exponent, like [(g_1, e_1), (g_2, e_2), (g_3, e_3), ... (g_i, e_i)] 50 | /// * `modulus` - all computations are done this modulo 51 | /// * `ctx` - big number context 52 | /// 53 | /// # Result 54 | /// Return the exponentiation, i.e `(g_1^e_1)*(g_2^e_2)*...(g_i^e_i)` 55 | pub fn get_exponentiated_generators(to_exponentiate: Vec<(&BigNumber, &BigNumber)>, 56 | modulus: &BigNumber, ctx: &mut BigNumberContext) -> Result { 57 | let accumulated = to_exponentiate.iter() 58 | .fold(BigNumber::from_u32(1), 59 | |acc, &(g, m)| acc?.mod_mul(&g.mod_exp(m, modulus, Some(ctx))?, modulus, Some(ctx)))?; 60 | Ok(accumulated) 61 | } 62 | -------------------------------------------------------------------------------- /libhl-crypto/bin/test_secp256k1.rs: -------------------------------------------------------------------------------- 1 | extern crate hl_crypto; 2 | extern crate secp256k1; 3 | extern crate openssl; 4 | 5 | use hl_crypto::signatures::secp256k1::EcdsaSecp256k1Sha256; 6 | use hl_crypto::signatures::{PublicKey, PrivateKey, SignatureScheme, EcdsaPublicKeyHandler, sha256}; 7 | use openssl::ecdsa::EcdsaSig; 8 | use openssl::ec::{EcGroup, EcPoint, EcKey}; 9 | use openssl::nid::Nid; 10 | use openssl::bn::{BigNum, BigNumContext}; 11 | 12 | use std::io; 13 | use std::io::Write; 14 | use std::time::Instant; 15 | 16 | fn main() { 17 | let letters = b"abcdefghijklmnopqrstuvwxyz"; 18 | let trials = 200; 19 | println!("Running 3 tests for secp256k1 signing of {} messages", trials); 20 | print!("This library - "); 21 | io::stdout().flush().unwrap(); 22 | let scheme = EcdsaSecp256k1Sha256::new(); 23 | let (p, s) = scheme.keypair(None).unwrap(); 24 | let mut now = Instant::now(); 25 | 26 | for _ in 0..trials { 27 | let signature = scheme.sign(&letters[..], &s).unwrap(); 28 | scheme.verify(&letters[..], &signature, &p).unwrap(); 29 | } 30 | let elapsed = now.elapsed(); 31 | println!("{}.{:03}", elapsed.as_secs(), elapsed.subsec_millis()); 32 | 33 | print!("C based secp256k1 - "); 34 | io::stdout().flush().unwrap(); 35 | let context = secp256k1::Secp256k1::new(); 36 | let sk = secp256k1::key::SecretKey::from_slice(&context, &s[..]).unwrap(); 37 | let pk = secp256k1::key::PublicKey::from_slice(&context, &p[..]).unwrap(); 38 | 39 | now = Instant::now(); 40 | for _ in 0..trials { 41 | let hash = sha256(&letters[..]); 42 | let msg = secp256k1::Message::from_slice(&hash[..]).unwrap(); 43 | let sig_1 = context.sign(&msg, &sk); 44 | context.verify(&msg, &sig_1, &pk).unwrap(); 45 | } 46 | 47 | let elapsed = now.elapsed(); 48 | println!("{}.{:03}", elapsed.as_secs(), elapsed.subsec_millis()); 49 | 50 | print!("Openssl based secp256k1 - "); 51 | io::stdout().flush().unwrap(); 52 | let openssl_group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap(); 53 | let mut ctx = BigNumContext::new().unwrap(); 54 | let openssl_point = EcPoint::from_bytes(&openssl_group, &scheme.serialize_uncompressed(&p)[..], &mut ctx).unwrap(); 55 | let openssl_pkey = EcKey::from_public_key(&openssl_group, &openssl_point).unwrap(); 56 | let openssl_skey = EcKey::from_private_components(&openssl_group, &BigNum::from_slice(&s[..]).unwrap(), &openssl_point).unwrap(); 57 | 58 | now = Instant::now(); 59 | for _ in 0..trials { 60 | let hash = sha256(&letters[..]); 61 | let openssl_sig = EcdsaSig::sign(&hash, &openssl_skey).unwrap(); 62 | openssl_sig.verify(&hash, &openssl_pkey).unwrap(); 63 | } 64 | 65 | let elapsed = now.elapsed(); 66 | println!("{}.{:03}", elapsed.as_secs(), elapsed.subsec_millis()); 67 | } 68 | -------------------------------------------------------------------------------- /libhl-crypto/src/utils/rsa.rs: -------------------------------------------------------------------------------- 1 | use bn::{BigNumber, BigNumberContext}; 2 | use errors::HLCryptoError; 3 | 4 | /// Generate an RSA modulus of a given size 5 | /// 6 | /// # Arguments 7 | /// * `size` - size in bits of the the RSA modulus 8 | /// * `ctx` - big number context 9 | /// 10 | /// # Result 11 | /// Return the RSA modulus and the factors 12 | pub fn generate_rsa_modulus(size: usize, 13 | ctx: &mut BigNumberContext) -> Result<(BigNumber, BigNumber, BigNumber), HLCryptoError> { 14 | if size % 2 != 0 { 15 | return Err(HLCryptoError::InvalidParam1( 16 | format!("Need an even number of bits, found {}", size)) 17 | ); 18 | } 19 | 20 | let factor_size = size / 2; 21 | let p = BigNumber::generate_safe_prime(factor_size)?; 22 | let q = BigNumber::generate_safe_prime(factor_size)?; 23 | let n = p.mul(&q, Some(ctx))?; 24 | Ok((n, p, q)) 25 | } 26 | 27 | 28 | /// Generate the witness from the initial witness and subsequent exponents 29 | /// 30 | /// # Arguments 31 | /// * `initial_witness` - size in bits of the the RSA modulus 32 | /// * `exponents` - new exponents 33 | /// * `modulus` - exponentiations are done this modulo 34 | /// * `ctx` - big number context 35 | /// 36 | /// # Result 37 | /// Return the new witness 38 | pub fn generate_witness(initial_witness: &BigNumber, exponents: &Vec, 39 | modulus: &BigNumber, ctx: &mut BigNumberContext) -> Result { 40 | let mut updated_witness = initial_witness.clone()?; 41 | for ref e in exponents.iter() { 42 | updated_witness = updated_witness.mod_exp(&e, modulus, Some(ctx))?; 43 | } 44 | Ok(updated_witness) 45 | } 46 | 47 | 48 | #[cfg(test)] 49 | mod tests { 50 | use super::*; 51 | 52 | #[test] 53 | fn test_generate_rsa_modulus_basic() { 54 | // check modulus is the product of 2 primes 55 | let mut ctx = BigNumber::new_context().unwrap(); 56 | let (n, p, q) = generate_rsa_modulus(2048, &mut ctx).unwrap(); 57 | assert!(BigNumber::is_prime(&p,Some(&mut ctx)).unwrap()); 58 | assert!(BigNumber::is_prime(&q,Some(&mut ctx)).unwrap()); 59 | assert_eq!(n, p.mul(&q, Some(&mut ctx)).unwrap()); 60 | } 61 | 62 | #[test] 63 | fn test_generate_witness() { 64 | // check modulus is the product of 2 primes 65 | let mut ctx = BigNumber::new_context().unwrap(); 66 | let initial_witness = BigNumber::from_dec("5").unwrap(); 67 | let e1 = BigNumber::from_u32(3).unwrap(); 68 | let e2 = BigNumber::from_u32(5).unwrap(); 69 | let e3 = BigNumber::from_u32(7).unwrap(); 70 | let e4 = BigNumber::from_u32(11).unwrap(); 71 | let e5 = BigNumber::from_u32(13).unwrap(); 72 | let exps = vec![e1, e2, e3, e4, e5]; 73 | let n = BigNumber::from_u32(17).unwrap(); 74 | assert_eq!(BigNumber::from_u32(10).unwrap(), generate_witness(&initial_witness, 75 | &exps, &n, &mut ctx).unwrap()) 76 | } 77 | 78 | } 79 | -------------------------------------------------------------------------------- /Jenkinsfile.ci: -------------------------------------------------------------------------------- 1 | #!groovy 2 | 3 | testing() 4 | 5 | def testing() { 6 | stage('Testing') { 7 | parallel([ 8 | 'ubuntu-test' : { ubuntuTesting() }, 9 | 'windows-test': { windowsTesting() } 10 | ]) 11 | } 12 | } 13 | 14 | def ubuntuTesting() { 15 | node('ubuntu') { 16 | stage('Ubuntu Test') { 17 | linuxTesting("ci/ubuntu.dockerfile ci", "Ubuntu") 18 | } 19 | } 20 | } 21 | 22 | def windowsTesting() { 23 | node('win2016') { 24 | stage('Windows Test') { 25 | def ws_path = "workspace/${env.JOB_NAME}".replace(' ', '_') 26 | ws(ws_path) { 27 | try { 28 | echo "Windows Test: Checkout scm" 29 | checkout scm 30 | 31 | setupRust() 32 | 33 | dir('libindy-crypto') { 34 | echo "Windows Test: Download prebuilt dependencies" 35 | bat 'wget -O prebuilt.zip "https://repo.sovrin.org/windows/libindy_crypto/deps/indy-crypto-deps.zip"' 36 | bat 'unzip prebuilt.zip -d prebuilt' 37 | 38 | echo "Windows Test: Build" 39 | withEnv([ 40 | "OPENSSL_DIR=$WORKSPACE\\libindy-crypto\\prebuilt", 41 | "INDY_CRYPTO_PREBUILT_DEPS_DIR=$WORKSPACE\\libindy-crypto\\prebuilt", 42 | "RUST_BACKTRACE=1" 43 | ]) { 44 | bat "cargo test --no-run" 45 | 46 | echo "Windows Test: Run tests" 47 | withEnv(["RUST_LOG=trace"]) { 48 | bat "cargo test" 49 | } 50 | } 51 | } 52 | 53 | //TODO wrappers testing 54 | } finally { 55 | cleanWs() 56 | } 57 | } 58 | cleanWs() 59 | } 60 | } 61 | } 62 | 63 | def linuxTesting(file, env_name) { 64 | try { 65 | echo "${env_name} Test: Checkout csm" 66 | checkout scm 67 | 68 | def testEnv 69 | 70 | dir('libindy-crypto') { 71 | echo "${env_name} Test: Build docker image" 72 | 73 | testEnv = docker.build("libindy-crypto-test", "--build-arg uid=${getUserUid()} -f $file") 74 | testEnv.inside { 75 | echo "${env_name} Test: Test" 76 | 77 | echo "${env_name} Test: Build" 78 | sh "RUST_BACKTRACE=1 cargo test --no-run" 79 | 80 | echo "${env_name} Test: Run tests" 81 | sh "RUST_BACKTRACE=1 RUST_LOG=trace cargo test" 82 | } 83 | } 84 | 85 | sh "cp libindy-crypto/target/debug/libindy_crypto.so wrappers/python" 86 | dir('wrappers/python') { 87 | testEnv.inside { 88 | echo "${env_name} Test: Test python wrapper" 89 | 90 | sh ''' 91 | python3.5 -m pip install --user -e . 92 | LD_LIBRARY_PATH=./ RUST_LOG=trace python3.5 -m pytest 93 | ''' 94 | } 95 | } 96 | } 97 | finally { 98 | step([$class: 'WsCleanup']) 99 | } 100 | } 101 | 102 | def getUserUid() { 103 | return sh(returnStdout: true, script: 'id -u').trim() 104 | } 105 | 106 | def setupRust() { 107 | sh "rustup default 1.25.0" 108 | } 109 | -------------------------------------------------------------------------------- /libhl-crypto/src/utils/ctypes.rs: -------------------------------------------------------------------------------- 1 | use libc::c_char; 2 | 3 | use std::ffi::CStr; 4 | use std::str::Utf8Error; 5 | use std::ffi::CString; 6 | 7 | pub struct CTypesUtils {} 8 | 9 | impl CTypesUtils { 10 | pub fn c_str_to_string(cstr: *const c_char) -> Result, Utf8Error> { 11 | if cstr.is_null() { 12 | return Ok(None); 13 | } 14 | 15 | unsafe { 16 | match CStr::from_ptr(cstr).to_str() { 17 | Ok(str) => Ok(Some(str.to_string())), 18 | Err(err) => Err(err) 19 | } 20 | } 21 | } 22 | 23 | pub fn string_to_cstring(s: String) -> CString { 24 | CString::new(s).unwrap() 25 | } 26 | } 27 | 28 | macro_rules! check_useful_c_byte_array { 29 | ($ptr:ident, $len:expr, $err1:expr, $err2:expr) => { 30 | if $ptr.is_null() { 31 | return $err1 32 | } 33 | 34 | if $len <= 0 { 35 | return $err2 36 | } 37 | 38 | let $ptr = unsafe { slice::from_raw_parts($ptr, $len) }; 39 | } 40 | } 41 | 42 | macro_rules! check_useful_opt_c_byte_array { 43 | ($ptr:ident, $len:expr, $err1:expr, $err2:expr) => { 44 | if !$ptr.is_null() && $len <= 0 { 45 | return $err2 46 | } 47 | 48 | let $ptr = if $ptr.is_null() { 49 | None 50 | } else { 51 | unsafe { Some(slice::from_raw_parts($ptr, $len)) } 52 | }; 53 | } 54 | } 55 | 56 | macro_rules! check_useful_c_reference { 57 | ($ptr:ident, $type:ty, $err:expr) => { 58 | if $ptr.is_null() { 59 | return $err 60 | } 61 | 62 | let $ptr: &$type = unsafe { &*($ptr as *const $type) };; 63 | } 64 | } 65 | 66 | macro_rules! check_useful_mut_c_reference { 67 | ($ptr:ident, $type:ty, $err:expr) => { 68 | if $ptr.is_null() { 69 | return $err 70 | } 71 | 72 | let $ptr: &mut $type = unsafe { &mut *($ptr as *mut $type) };; 73 | } 74 | } 75 | 76 | macro_rules! check_useful_opt_c_reference { 77 | ($ptr:ident, $type:ty) => { 78 | let $ptr: Option<&$type> = if $ptr.is_null() { 79 | None 80 | } else { 81 | Some(unsafe { & *($ptr as *const $type) }) 82 | }; 83 | } 84 | } 85 | 86 | macro_rules! check_useful_c_reference_array { 87 | ($ptrs:ident, $ptrs_len:ident, $type:ty, $err1:expr, $err2:expr) => { 88 | if $ptrs.is_null() { 89 | return $err1 90 | } 91 | 92 | if $ptrs_len <= 0 { 93 | return $err2 94 | } 95 | 96 | let $ptrs: Vec<&$type> = 97 | unsafe { slice::from_raw_parts($ptrs, $ptrs_len) } 98 | .iter() 99 | .map(|ptr| unsafe { &*(*ptr as *const $type) }) 100 | .collect(); 101 | } 102 | } 103 | 104 | macro_rules! check_useful_hashset { 105 | ($ptr:ident, $len:expr, $err1:expr, $err2:expr) => { 106 | if $ptr.is_null() { 107 | return $err1 108 | } 109 | 110 | let $ptr = HashSet::from_iter( unsafe { slice::from_raw_parts($ptr, $len) }.iter().cloned()); 111 | } 112 | } 113 | 114 | macro_rules! check_useful_c_ptr { 115 | ($ptr:ident, $err1:expr) => { 116 | if $ptr.is_null() { 117 | return $err1 118 | } 119 | } 120 | } 121 | 122 | macro_rules! check_useful_c_str { 123 | ($x:ident, $e:expr) => { 124 | let $x = match CTypesUtils::c_str_to_string($x) { 125 | Ok(Some(val)) => val, 126 | _ => return $e, 127 | }; 128 | 129 | if $x.is_empty() { 130 | return $e 131 | } 132 | } 133 | } -------------------------------------------------------------------------------- /libhl-crypto/src/utils/macros.rs: -------------------------------------------------------------------------------- 1 | macro_rules! array_copy { 2 | ($src:expr, $dst:expr) => { 3 | for i in 0..$dst.len() { 4 | $dst[i] = $src[i]; 5 | } 6 | }; 7 | ($src:expr, $dst:expr, $offset:expr, $length:expr) => { 8 | for i in 0..$length { 9 | $dst[i + $offset] = $src[i] 10 | } 11 | }; 12 | ($src:expr, $src_offset:expr, $dst:expr, $dst_offset:expr, $length:expr) => { 13 | for i in 0..$length { 14 | $dst[i + $dst_offset] = $src[i + $src_offset] 15 | } 16 | } 17 | } 18 | 19 | macro_rules! impl_bytearray { 20 | ($thing:ident) => { 21 | impl $thing { 22 | #[inline] 23 | /// Converts the object to a raw pointer for FFI interfacing 24 | pub fn as_ptr(&self) -> *const u8 { 25 | self.0.as_slice().as_ptr() 26 | } 27 | 28 | #[inline] 29 | /// Converts the object to a mutable raw pointer for FFI interfacing 30 | pub fn as_mut_ptr(&mut self) -> *mut u8 { 31 | self.0.as_mut_slice().as_mut_ptr() 32 | } 33 | 34 | #[inline] 35 | /// Returns the length of the object as an array 36 | pub fn len(&self) -> usize { self.0.len() } 37 | } 38 | 39 | impl PartialEq for $thing { 40 | #[inline] 41 | fn eq(&self, other: &$thing) -> bool { 42 | self.0 == other.0 43 | } 44 | } 45 | 46 | impl Eq for $thing {} 47 | 48 | impl Clone for $thing { 49 | #[inline] 50 | fn clone(&self) -> $thing { 51 | $thing(self.0.clone()) 52 | } 53 | } 54 | 55 | impl ::std::ops::Index for $thing { 56 | type Output = u8; 57 | 58 | #[inline] 59 | fn index(&self, index: usize) -> &u8 { 60 | &self.0[index] 61 | } 62 | } 63 | 64 | impl ::std::ops::Index<::std::ops::Range> for $thing { 65 | type Output = [u8]; 66 | 67 | #[inline] 68 | fn index(&self, index: ::std::ops::Range) -> &[u8] { 69 | &self.0[index] 70 | } 71 | } 72 | 73 | impl ::std::ops::Index<::std::ops::RangeTo> for $thing { 74 | type Output = [u8]; 75 | 76 | #[inline] 77 | fn index(&self, index: ::std::ops::RangeTo) -> &[u8] { 78 | &self.0[index] 79 | } 80 | } 81 | 82 | impl ::std::ops::Index<::std::ops::RangeFrom> for $thing { 83 | type Output = [u8]; 84 | 85 | #[inline] 86 | fn index(&self, index: ::std::ops::RangeFrom) -> &[u8] { 87 | &self.0[index] 88 | } 89 | } 90 | 91 | impl ::std::ops::Index<::std::ops::RangeFull> for $thing { 92 | type Output = [u8]; 93 | 94 | #[inline] 95 | fn index(&self, _: ::std::ops::RangeFull) -> &[u8] { 96 | self.0.as_slice() 97 | } 98 | } 99 | impl ::std::fmt::Display for $thing { 100 | fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 101 | write!(formatter, "{} {{ {} }}", stringify!($thing), bin2hex(&self.0[..])) 102 | } 103 | } 104 | 105 | impl ::std::fmt::Debug for $thing { 106 | fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 107 | write!(formatter, "{} {{ {} }}", stringify!($thing), bin2hex(&self.0[..])) 108 | } 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /libhl-crypto/src/lib.rs: -------------------------------------------------------------------------------- 1 | /// Portable try to solely use Rust and no external C libraries. 2 | /// This is considered less secure only because the Rust code may not have had a 3 | /// security audited yet. 4 | /// 5 | /// Native uses external C libraries that have had a security audit performed 6 | 7 | extern crate amcl; 8 | extern crate amcl_3; 9 | #[cfg(feature = "portable")] 10 | #[macro_use] 11 | extern crate arrayref; 12 | extern crate env_logger; 13 | #[macro_use] 14 | extern crate log; 15 | extern crate rand; 16 | extern crate sha2; 17 | extern crate sha3; 18 | #[cfg(any(test, all(feature = "native", not(feature = "portable"))))] 19 | extern crate libsodium_ffi; 20 | #[cfg(all(feature = "portable", not(feature = "native")))] 21 | extern crate crypto as rcrypto; 22 | #[cfg(any(test, all(feature = "native", not(feature = "portable"))))] 23 | extern crate secp256k1 as libsecp256k1; 24 | #[cfg(all(feature = "portable", not(feature = "native")))] 25 | extern crate rustlibsecp256k1; 26 | 27 | // To use macros from util inside of other modules it must me loaded first. 28 | #[macro_use] 29 | pub mod utils; 30 | 31 | #[cfg(feature = "serialization")] 32 | extern crate serde; 33 | 34 | #[cfg(feature = "serialization")] 35 | #[allow(unused_imports)] // Remove false positive warning. See https://github.com/rust-lang/rust/issues/44342 36 | #[macro_use] 37 | extern crate serde_derive; 38 | 39 | #[cfg(not(test))] 40 | #[cfg(feature = "serialization")] 41 | extern crate serde_json; 42 | 43 | #[cfg(test)] 44 | #[cfg(feature = "serialization")] 45 | #[macro_use] 46 | extern crate serde_json; 47 | 48 | #[cfg(feature = "bn_openssl")] 49 | extern crate openssl; 50 | 51 | #[cfg(feature = "bn_openssl")] 52 | extern crate int_traits; 53 | 54 | extern crate libc; 55 | 56 | extern crate time; 57 | 58 | extern crate blake2b_simd; 59 | 60 | pub mod cl; 61 | pub mod bls; 62 | 63 | #[cfg(feature = "bn_openssl")] 64 | #[path = "bn/openssl.rs"] 65 | pub mod bn; 66 | 67 | pub mod errors; 68 | pub mod ffi; 69 | 70 | #[cfg(feature = "pair_amcl")] 71 | #[path = "pair/amcl.rs"] 72 | pub mod pair; 73 | 74 | #[macro_use] 75 | extern crate lazy_static; 76 | 77 | pub mod hash; 78 | pub mod keys; 79 | pub mod signatures; 80 | pub mod encoding; 81 | #[derive(Debug)] 82 | pub enum CryptoError { 83 | /// Returned when trying to create an algorithm which does not exist. 84 | NoSuchAlgorithm(String), 85 | /// Returned when an error occurs during deserialization of a Private or 86 | /// Public key from various formats. 87 | ParseError(String), 88 | /// Returned when an error occurs during the signing process. 89 | SigningError(String), 90 | /// Returned when an error occurs during key generation 91 | KeyGenError(String), 92 | /// Returned when an error occurs during digest generation 93 | DigestGenError(String) 94 | } 95 | 96 | #[cfg(feature = "native")] 97 | impl From for CryptoError { 98 | fn from(error: libsecp256k1::Error) -> CryptoError { 99 | match error { 100 | libsecp256k1::Error::IncorrectSignature => CryptoError::ParseError("Incorrect Signature".to_string()), 101 | libsecp256k1::Error::InvalidMessage => CryptoError::ParseError("Invalid Message".to_string()), 102 | libsecp256k1::Error::InvalidPublicKey => CryptoError::ParseError("Invalid Public Key".to_string()), 103 | libsecp256k1::Error::InvalidSignature => CryptoError::ParseError("Invalid Signature".to_string()), 104 | libsecp256k1::Error::InvalidSecretKey => CryptoError::ParseError("Invalid Secret Key".to_string()), 105 | libsecp256k1::Error::InvalidRecoveryId => CryptoError::ParseError("Invalid Recovery Id".to_string()) 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/bn254/rom.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use bn254::big::NLEN; 21 | use arch::Chunk; 22 | 23 | // BN254 Modulus 24 | // Base Bits= 56 25 | pub const MODULUS:[Chunk;NLEN]=[0x13,0x13A7,0x80000000086121,0x40000001BA344D,0x25236482]; 26 | pub const R2MODP:[Chunk;NLEN]=[0x2F2A96FF5E7E39,0x64E8642B96F13C,0x9926F7B00C7146,0x8321E7B4DACD24,0x1D127A2E]; 27 | pub const MCONST:Chunk=0x435E50D79435E5; 28 | pub const FRA:[Chunk;NLEN]=[0x7DE6C06F2A6DE9,0x74924D3F77C2E1,0x50A846953F8509,0x212E7C8CB6499B,0x1B377619]; 29 | pub const FRB:[Chunk;NLEN]=[0x82193F90D5922A,0x8B6DB2C08850C5,0x2F57B96AC8DC17,0x1ED1837503EAB2,0x9EBEE69]; 30 | 31 | pub const CURVE_COF_I:isize = 1; 32 | pub const CURVE_A:isize = 0; 33 | pub const CURVE_B_I:isize = 2; 34 | pub const CURVE_B:[Chunk;NLEN]=[0x2,0x0,0x0,0x0,0x0]; 35 | pub const CURVE_ORDER:[Chunk;NLEN]=[0xD,0x800000000010A1,0x8000000007FF9F,0x40000001BA344D,0x25236482]; 36 | pub const CURVE_GX:[Chunk;NLEN]=[0x12,0x13A7,0x80000000086121,0x40000001BA344D,0x25236482]; 37 | pub const CURVE_GY:[Chunk;NLEN]=[0x1,0x0,0x0,0x0,0x0]; 38 | pub const CURVE_BNX:[Chunk;NLEN]=[0x80000000000001,0x40,0x0,0x0,0x0]; 39 | pub const CURVE_COF:[Chunk;NLEN]=[0x1,0x0,0x0,0x0,0x0]; 40 | pub const CURVE_CRU:[Chunk;NLEN]=[0x80000000000007,0x6CD,0x40000000024909,0x49B362,0x0]; 41 | pub const CURVE_PXA:[Chunk;NLEN]=[0xEE4224C803FB2B,0x8BBB4898BF0D91,0x7E8C61EDB6A464,0x519EB62FEB8D8C,0x61A10BB]; 42 | pub const CURVE_PXB:[Chunk;NLEN]=[0x8C34C1E7D54CF3,0x746BAE3784B70D,0x8C5982AA5B1F4D,0xBA737833310AA7,0x516AAF9]; 43 | pub const CURVE_PYA:[Chunk;NLEN]=[0xF0E07891CD2B9A,0xAE6BDBE09BD19,0x96698C822329BD,0x6BAF93439A90E0,0x21897A0]; 44 | pub const CURVE_PYB:[Chunk;NLEN]=[0x2D1AEC6B3ACE9B,0x6FFD739C9578A,0x56F5F38D37B090,0x7C8B15268F6D44,0xEBB2B0E]; 45 | pub const CURVE_W:[[Chunk;NLEN];2]=[[0x3,0x80000000000204,0x6181,0x0,0x0],[0x1,0x81,0x0,0x0,0x0]]; 46 | pub const CURVE_SB:[[[Chunk;NLEN];2];2]=[[[0x4,0x80000000000285,0x6181,0x0,0x0],[0x1,0x81,0x0,0x0,0x0]],[[0x1,0x81,0x0,0x0,0x0],[0xA,0xE9D,0x80000000079E1E,0x40000001BA344D,0x25236482]]]; 47 | pub const CURVE_WB:[[Chunk;NLEN];4]=[[0x80000000000000,0x80000000000040,0x2080,0x0,0x0],[0x80000000000005,0x54A,0x8000000001C707,0x312241,0x0],[0x80000000000003,0x800000000002C5,0xC000000000E383,0x189120,0x0],[0x80000000000001,0x800000000000C1,0x2080,0x0,0x0]]; 48 | pub const CURVE_BB:[[[Chunk;NLEN];4];4]=[[[0x8000000000000D,0x80000000001060,0x8000000007FF9F,0x40000001BA344D,0x25236482],[0x8000000000000C,0x80000000001060,0x8000000007FF9F,0x40000001BA344D,0x25236482],[0x8000000000000C,0x80000000001060,0x8000000007FF9F,0x40000001BA344D,0x25236482],[0x2,0x81,0x0,0x0,0x0]],[[0x1,0x81,0x0,0x0,0x0],[0x8000000000000C,0x80000000001060,0x8000000007FF9F,0x40000001BA344D,0x25236482],[0x8000000000000D,0x80000000001060,0x8000000007FF9F,0x40000001BA344D,0x25236482],[0x8000000000000C,0x80000000001060,0x8000000007FF9F,0x40000001BA344D,0x25236482]],[[0x2,0x81,0x0,0x0,0x0],[0x1,0x81,0x0,0x0,0x0],[0x1,0x81,0x0,0x0,0x0],[0x1,0x81,0x0,0x0,0x0]],[[0x80000000000002,0x40,0x0,0x0,0x0],[0x2,0x102,0x0,0x0,0x0],[0xA,0x80000000001020,0x8000000007FF9F,0x40000001BA344D,0x25236482],[0x80000000000002,0x40,0x0,0x0,0x0]]]; 49 | 50 | pub const USE_GLV:bool = true; 51 | pub const USE_GS_G2:bool = true; 52 | pub const USE_GS_GT:bool = true; 53 | pub const GT_STRONG:bool = false; 54 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/bls381/rom.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use bls381::big::NLEN; 21 | use arch::Chunk; 22 | 23 | // Base Bits= 58 24 | // bls381 Modulus 25 | 26 | pub const MODULUS:[Chunk;NLEN]=[0x1FEFFFFFFFFAAAB,0x2FFFFAC54FFFFEE,0x12A0F6B0F6241EA,0x213CE144AFD9CC3,0x2434BACD764774B,0x25FF9A692C6E9ED,0x1A0111EA3]; 27 | pub const R2MODP:[Chunk;NLEN]=[0x20639A1D5BEF7AE,0x1244C6462DD93E8,0x22D09B54E6E2CD2,0x111C4B63170E5DB,0x38A6DE8FB366399,0x4F16CFED1F9CBC,0x19EA66A2B]; 28 | pub const MCONST:Chunk=0x1F3FFFCFFFCFFFD; 29 | pub const FRA:[Chunk;NLEN]=[0x10775ED92235FB8,0x3A94F58F9E04F63,0x3D784BAB9C4F67,0x3F4F2F57D3DEC91,0x202C0D1F0FD603,0xAEC199F08C6FAD,0x1904D3BF0]; 30 | pub const FRB:[Chunk;NLEN]=[0xF78A126DDC4AF3,0x356B0535B1FB08B,0xEC971F63C5F282,0x21EDB1ECDBFB032,0x2231F9FB854A147,0x1B1380CA23A7A40,0xFC3E2B3]; 31 | 32 | pub const CURVE_COF_I:isize = 0; 33 | pub const CURVE_A:isize = 0; 34 | pub const CURVE_B_I:isize = 4; 35 | pub const CURVE_B:[Chunk;NLEN]=[0x4,0x0,0x0,0x0,0x0,0x0,0x0]; 36 | pub const CURVE_ORDER:[Chunk;NLEN]=[0x3FFFFFF00000001,0x36900BFFF96FFBF,0x180809A1D80553B,0x14CA675F520CCE7,0x73EDA7,0x0,0x0]; 37 | pub const CURVE_GX:[Chunk;NLEN]=[0x33AF00ADB22C6BB,0x17A0FFE5E86BBFE,0x3A3F171BAC586C5,0x13E5DD2E4168538,0x4FA9AC0FC3688C,0x65F5E509A558E3,0x17F1D3A73]; 38 | pub const CURVE_GY:[Chunk;NLEN]=[0xAA232946C5E7E1,0x331D128A222B903,0x18CB2C04B3EDD03,0x25757402BD8036C,0x1741D8AE4FCF5E0,0xEAA83C68278C3B,0x8B3F481E]; 39 | 40 | pub const CURVE_BNX:[Chunk;NLEN]=[0x201000000010000,0x34,0x0,0x0,0x0,0x0,0x0]; 41 | pub const CURVE_COF:[Chunk;NLEN]=[0xAAAB0000AAAB,0x3230015557855A3,0x396,0x0,0x0,0x0,0x0]; 42 | pub const CURVE_CRU:[Chunk;NLEN]=[0x201FFFFFFFEFFFE,0x1F604D88280008B,0x293BE6F89688DE1,0x1DA83DDFAB76CE,0x3DF76CE51BA69C6,0x17C659CB,0x0]; 43 | 44 | pub const CURVE_PXA:[Chunk;NLEN]=[0x8056C8C121BDB8,0x300C9AA016EFBF5,0xB647AE3D1770BA,0x353E900EC0AD144,0x32DC51051C6E47A,0x23C2A449820149,0x24AA2B2F]; 45 | pub const CURVE_PXB:[Chunk;NLEN]=[0x1AC7D055D042B7E,0x33C4484E51755F9,0x21BBDC7F5049334,0x3426482D86AD769,0x88274F65596BD0,0x9C67D81F6B34E8,0x13E02B605]; 46 | pub const CURVE_PYA:[Chunk;NLEN]=[0x193548608B82801,0x2B2730EEB28A278,0x1A695160D12C923,0x2AA32F74E9DB50A,0x2DA2E351AADFD9B,0x9F5B8463327371,0xCE5D5277]; 47 | pub const CURVE_PYB:[Chunk;NLEN]=[0x2A9075FF05F79BE,0x1C349D73B07686A,0x12AB572E99AB3F3,0x1FA169D8EBC99D2,0x2BC28B99CB3E28,0x3A9CD330CAB34AC,0x606C4A02]; 48 | pub const CURVE_W:[[Chunk;NLEN];2]=[[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0]]; 49 | pub const CURVE_SB:[[[Chunk;NLEN];2];2]=[[[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0]],[[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0]]]; 50 | pub const CURVE_WB:[[Chunk;NLEN];4]=[[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0]]; 51 | pub const CURVE_BB:[[[Chunk;NLEN];4];4]=[[[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0]],[[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0]],[[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0]],[[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0]]]; 52 | 53 | pub const USE_GLV:bool = true; 54 | pub const USE_GS_G2:bool = true; 55 | pub const USE_GS_GT:bool = true; 56 | pub const GT_STRONG:bool = false; 57 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/rand.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | //mod hash256; 21 | 22 | use hash256::HASH256; 23 | 24 | const RAND_NK: usize=21; 25 | const RAND_NJ: usize=6; 26 | const RAND_NV: usize=8; 27 | 28 | pub struct RAND { 29 | ira: [u32;RAND_NK], /* random number... */ 30 | rndptr: usize, 31 | borrow: u32, 32 | pool_ptr: usize, 33 | pool: [u8;32] 34 | } 35 | 36 | impl RAND { 37 | 38 | pub fn new() -> RAND { 39 | RAND { 40 | ira: [0;RAND_NK], 41 | rndptr:0, 42 | borrow: 0, 43 | pool_ptr:0, 44 | pool:[0;32] 45 | } 46 | } 47 | 48 | pub fn clean(&mut self) { 49 | self.pool_ptr=0; self.rndptr=0; 50 | for i in 0..32 {self.pool[i]=0} 51 | for i in 0..RAND_NK {self.ira[i]=0} 52 | self.borrow=0; 53 | } 54 | 55 | fn sbrand(&mut self) -> u32 { /* Marsaglia & Zaman random number generator */ 56 | self.rndptr+=1; 57 | if self.rndptrt {self.borrow=1} 66 | self.ira[i]=pdiff; 67 | k+=1; 68 | } 69 | return self.ira[0]; 70 | } 71 | 72 | fn sirand(&mut self,seed: u32) { 73 | let mut m: u32=1; 74 | let mut sd=seed; 75 | self.borrow=0; 76 | self.rndptr=0; 77 | self.ira[0]^=sd; 78 | for i in 1..RAND_NK { /* fill initialisation vector */ 79 | let inn=(RAND_NV*i)%RAND_NK; 80 | self.ira[inn]^=m; /* note XOR */ 81 | let t=m; 82 | m=sd.wrapping_sub(m); 83 | sd=t; 84 | } 85 | for _ in 0..10000 {self.sbrand();} /* "warm-up" & stir the generator */ 86 | } 87 | 88 | fn fill_pool(&mut self) { 89 | let mut sh=HASH256::new(); 90 | for _ in 0..128 {sh.process((self.sbrand()&0xff) as u8)} 91 | let w=sh.hash(); 92 | for i in 0..32 {self.pool[i]=w[i]} 93 | self.pool_ptr=0; 94 | } 95 | 96 | fn pack(b: [u8;4]) -> u32 { /* pack 4 bytes into a 32-bit Word */ 97 | return ((((b[3] as u32))&0xff)<<24)|(((b[2] as u32)&0xff)<<16)|(((b[1] as u32)&0xff)<<8)|((b[0] as u32)&0xff); 98 | } 99 | 100 | /* Initialize RNG with some real entropy from some external source */ 101 | pub fn seed(&mut self,rawlen: usize,raw: &[u8]) { /* initialise from at least 128 byte string of raw random entropy */ 102 | let mut b: [u8;4]=[0;4]; 103 | let mut sh=HASH256::new(); 104 | self.pool_ptr=0; 105 | 106 | for i in 0..RAND_NK {self.ira[i]=0} 107 | if rawlen>0 { 108 | for i in 0..rawlen { 109 | sh.process(raw[i]); 110 | } 111 | let digest=sh.hash(); 112 | 113 | /* initialise PRNG from distilled randomness */ 114 | 115 | for i in 0..8 { 116 | b[0]=digest[4*i]; b[1]=digest[4*i+1]; b[2]=digest[4*i+2]; b[3]=digest[4*i+3]; 117 | self.sirand(RAND::pack(b)); 118 | } 119 | } 120 | self.fill_pool(); 121 | } 122 | 123 | /* get random byte */ 124 | pub fn getbyte(&mut self) -> u8 { 125 | let r=self.pool[self.pool_ptr]; 126 | self.pool_ptr+=1; 127 | if self.pool_ptr>=32 {self.fill_pool()} 128 | return (r&0xff) as u8; 129 | } 130 | } 131 | 132 | /* test main program */ 133 | /* 134 | fn main() { 135 | let mut raw : [u8;100]=[0;100]; 136 | let mut rng=RAND::new(); 137 | 138 | rng.clean(); 139 | for i in 0..100 {raw[i]=i as u8} 140 | 141 | rng.seed(100,&raw); 142 | 143 | for _ in 0..1000 { 144 | print!("{:03} ",rng.getbyte()); 145 | } 146 | } 147 | */ 148 | -------------------------------------------------------------------------------- /docs/source/community/contributing.rst: -------------------------------------------------------------------------------- 1 | ------------ 2 | Contributing 3 | ------------ 4 | 5 | ========================================== 6 | Ways to Contribute to Hyperledger Ursa 7 | ========================================== 8 | 9 | Contributions from the development community help improve the capabilities of 10 | Hyperledger Ursa. These contributions are the most effective way to 11 | make a positive impact on the project. 12 | 13 | Ways you can contribute: 14 | 15 | * Bugs or issues: Report problems or defects found when working with Ursa 16 | * Core features and enhancements: Provide expanded capabilities or optimizations 17 | * Documentation: Improve existing documentation or create new information 18 | * Tests: Add functional, performance, or scalability tests 19 | 20 | Hyperledger Ursa issues can be found in :ref:`jira`. Any unassigned items 21 | are probably still open. When in doubt, ask on RocketChat about 22 | a specific JIRA issue (see :doc:`join_the_discussion`). 23 | 24 | ================== 25 | The Commit Process 26 | ================== 27 | 28 | Hyperledger Ursa is Apache 2.0 licensed and accepts contributions 29 | via `GitHub `_ 30 | pull requests. When contributing code, please follow these guidelines: 31 | 32 | * Fork the repository and make your changes in a feature branch 33 | * Include unit and integration tests for any new features and updates 34 | to existing tests 35 | * Ensure that the unit and integration tests run successfully. 36 | 37 | **Pull Request Guidelines** 38 | 39 | A pull request can contain a single commit or multiple commits. The most 40 | important guideline is that a single commit should map to a single fix or 41 | enhancement. Here are some example scenarios: 42 | 43 | * If a pull request adds a feature but also fixes two bugs, the pull 44 | request should have three commits: one commit for the feature change and 45 | two commits for the bug fixes. 46 | * If a PR is opened with five commits that contain changes to fix a single 47 | issue, the PR should be rebased to a single commit. 48 | * If a PR is opened with several commits, where the first commit fixes one issue 49 | and the rest fix a separate issue, the PR should be rebased to two 50 | commits (one for each issue). 51 | 52 | **Important:** 53 | Your pull request should be rebased against the current master branch. Do 54 | not merge the current master branch in with your topic branch. Do not use the 55 | Update Branch button provided by GitHub on the pull request page. 56 | 57 | **Commit Messages** 58 | 59 | Commit messages should follow common Git conventions, such as using the 60 | imperative mood, separate subject lines, and a line length of 72 characters. 61 | These rules are well documented in `Chris Beam's blog post 62 | `_. 63 | 64 | **Signed-off-by** 65 | 66 | Each commit must include a "Signed-off-by" line in the commit message 67 | (``git commit -s``). This sign-off indicates that you agree the commit satisfies 68 | the `Developer Certificate of Origin (DCO) `_. 69 | 70 | **Commit Email Address** 71 | 72 | Your commit email address must match your GitHub email address. For more 73 | information, see 74 | https://help.github.com/articles/setting-your-commit-email-address-in-git/ 75 | 76 | **Important GitHub Requirements** 77 | 78 | A pull request cannot merged until it has passed these status checks: 79 | 80 | * The build must pass on Jenkins 81 | * The PR must be approved by at least two maintainers without any 82 | outstanding requests for changes 83 | * Any non-black-box use of an algorithm must include a theoretical maintainer 84 | as one of the two reviewers. 85 | 86 | **Integrating GitHub Commits with JIRA** 87 | 88 | You can link JIRA issues to your commits, which will integrate 89 | developer activity with the associated issue. JIRA uses the issue key to 90 | associate the commit with the issue, so that the commit can be summarized in the 91 | development panel for the JIRA issue. 92 | 93 | When you make a commit, add the JIRA issue key to the end of the commit message 94 | or to the branch name. Either method should integrate your commit with the JIRA 95 | issue that it references. 96 | 97 | .. Licensed under Creative Commons Attribution 4.0 International License 98 | .. https://creativecommons.org/licenses/by/4.0/ 99 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/bls461/rom.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use bls461::big::NLEN; 21 | use arch::Chunk; 22 | 23 | // Base Bits= 60 24 | // bls461 Modulus 25 | 26 | pub const MODULUS:[Chunk;NLEN]=[0xAAC0000AAAAAAAB,0x20000555554AAAA,0x6AA91557F004000,0xA8DFFA5C1CC00F2,0xACCA47B14848B42,0x935FBD6F1E32D8B,0xD5A555A55D69414,0x15555545554]; 27 | pub const R2MODP:[Chunk;NLEN]=[0x96D08774614DDA8,0xCD45F539225D5BD,0xD712EB760C95AB1,0xB3B687155F30B55,0xC4E62A05C3F5B81,0xBA1151676CA3CD0,0x7EDD8A958F442BE,0x12B89DD3F91]; 28 | pub const MCONST:Chunk=0xC0005FFFFFFFD; 29 | pub const FRA:[Chunk;NLEN]=[0xF7117BF9B812A3A,0xA1C6308A599C400,0x5A6510E07505BF8,0xB31ACE4858D45FA,0xFC61EBC2CB04770,0x366190D073588E2,0x69E55E24DFEFA84,0x12E40504B7F]; 30 | pub const FRB:[Chunk;NLEN]=[0xB3AE8410F298071,0x7E39D4CAFBAE6A9,0x104404777AFE407,0xF5C52C13C3EBAF8,0xB0685BEE7D443D1,0x5CFE2C9EAADA4A8,0x6BBFF7807D79990,0x27150409D5]; 31 | 32 | // bls461 Curve 33 | pub const CURVE_COF_I:isize = 0; 34 | pub const CURVE_A:isize = 0; 35 | pub const CURVE_B_I:isize = 9; 36 | pub const CURVE_B:[Chunk;NLEN]=[0x9,0x0,0x0,0x0,0x0,0x0,0x0,0x0]; 37 | pub const CURVE_ORDER:[Chunk;NLEN]=[0x1,0x7FEFFFEFFFFC0,0xC017FFC80001100,0x7FE05FD000E801F,0xFFFF7FFFC018001,0xFF,0x0,0x0]; 38 | pub const CURVE_GX:[Chunk;NLEN]=[0x14D026A8ADEE93D,0xF2D9C00EE74B741,0x229C3981B531AC7,0x6650D3564DC9218,0x436166F7C292A09,0x2CF668BE922B197,0x463B73A0C813271,0xAD0E74E99B]; 39 | pub const CURVE_GY:[Chunk;NLEN]=[0xF763157AD1D465,0x5D17884C8C4FF47,0x9D0A819E66B8D21,0x910AE5C3245F495,0x96EECB8BFA40B84,0x277ACC8BF9F8CBE,0x5F68C95F1C3F2F,0x77BCDB14B3]; 40 | 41 | pub const CURVE_BNX:[Chunk;NLEN]=[0xFFBFFFE00000000,0x1FFFF,0x0,0x0,0x0,0x0,0x0,0x0]; 42 | pub const CURVE_COF:[Chunk;NLEN]=[0xAA7FFFEAAAAAAAB,0xFFD55AAAB01556A,0x1555554FF,0x0,0x0,0x0,0x0,0x0]; 43 | pub const CURVE_CRU:[Chunk;NLEN]=[0x40001FFFFFFFE,0x6FFFE7FFFFE0000,0x6047200C47F0FFF,0x777115796DB7BCC,0x3F0E89875433CF4,0xBFFF60500050261,0x1FFFFFE,0x0]; 44 | pub const CURVE_PXA:[Chunk;NLEN]=[0x65B503186D0A37C,0xA9C2E492E75DCC4,0x564E01F919D6878,0x3F086DB74FF92F,0xED78D46D581A668,0x270C892F97C2907,0x6A50A9AF679453C,0x10CC54138A0]; 45 | pub const CURVE_PXB:[Chunk;NLEN]=[0x9F85CA8C2C1C0AD,0x96CD66C425CADE,0x1AC612951A2896,0xB17D529ABEBEE24,0xC5AF5BA09D33F65,0x6A672E4D4371ED4,0xACEA37CA279D224,0x95C1FB4FE5]; 46 | pub const CURVE_PYA:[Chunk;NLEN]=[0x7CCD0C1B02FB006,0x953D194A4A12A33,0x68B4960CFCC92C8,0xBA0F3A9B00F39FC,0xCDFD8A7DBBC5ED1,0xE73ED227CC2F7A9,0xEBA7E676070F4F4,0x226AC848E7]; 47 | pub const CURVE_PYB:[Chunk;NLEN]=[0x8A506ADFDF1457C,0xB4D6A31DC04C20A,0x668EA9A8F136E3F,0x12973C3BE4492F5,0xA20BE74BEABA67A,0x5157F04C42E3856,0xBB402EA2AB1D004,0xE38101B4FA]; 48 | pub const CURVE_W:[[Chunk;NLEN];2]=[[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]]; 49 | pub const CURVE_SB:[[[Chunk;NLEN];2];2]=[[[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]],[[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]]]; 50 | pub const CURVE_WB:[[Chunk;NLEN];4]=[[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]]; 51 | pub const CURVE_BB:[[[Chunk;NLEN];4];4]=[[[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]],[[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]],[[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]],[[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0],[0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]]]; 52 | 53 | pub const USE_GLV:bool = true; 54 | pub const USE_GS_G2:bool = true; 55 | pub const USE_GS_GT:bool = true; 56 | pub const GT_STRONG:bool = false; 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Lab Name 2 | crypto-lib 3 | 4 | # Short Description 5 | A lab for experimentation on creating shared cryptography modules for cross-project collaboration 6 | 7 | # Scope of Lab 8 | The purpose of this lab is to serve as an initial launching point for what will hopefully become a shared Hyperledger cryptography library. We aim to use this lab to set up a code base and experiment with integrating cryptographic protocols between projects. 9 | 10 | See: https://docs.google.com/document/d/1JtFT5L-82egj6shgGXzTsNAg6_UHuMheKfsst6NS_Xo/edit?usp=sharing 11 | for more details. 12 | 13 | # Initial Committers 14 | - hartm 15 | - mikelodder7 16 | - lovesh 17 | - vaporos 18 | 19 | # Sponsor 20 | Hart Montgomery 21 | 22 | 23 | ## Before you Continue 24 | 25 | If you haven't done so already, please visit the main resource for all things "Indy" to get acquainted with the code base, helpful resources, and up-to-date information: [Hyperledger Wiki-Indy](https://wiki.hyperledger.org/projects/indy). 26 | 27 | # Crypto Lib 28 | 29 | This is the shared crypto library for [Hyperledger](https://www.hyperledger.org/projects) components. 30 | 31 | [Hyperledger](https://www.hyperledger.org/projects) provides a distributed-ledger-based foundation for [self-sovereign identity](https://sovrin.org). 32 | 33 | The major artifacts of the Crypto Lib are: 34 | * С-callable library interface 35 | * Rust сrate 36 | 37 | All bugs, stories, and backlog for this project are managed through [Hyperledger's Jira](https://jira.hyperledger.org) 38 | in project IS (note that regular Indy tickets are in the INDY project instead...). Also, join 39 | us on [Jira's Rocket.Chat](chat.hyperledger.org) at #indy-sdk to discuss. 40 | 41 | ## Building Crypto-Lib 42 | 43 | 1. Install xcode command line tools 44 | ``` 45 | xcode-select --install 46 | ``` 47 | 1. Install Rust and rustup (https://www.rust-lang.org/install.html). 48 | 1. Install Libsodium 49 | - For Mac OS X 50 | ``` 51 | brew install libsodium 52 | 53 | or to build it from scratch 54 | 55 | brew install autoconf 56 | brew install automake 57 | git clone git@github.com:jedisct1/libsodium.git 58 | cd libsodium 59 | ./autoconf 60 | ./configure 61 | make 62 | sudo make install 63 | ``` 64 | 1. Checkout and build the library: 65 | 66 | ``` 67 | git clone https://github.com/hyperledger-labs/crypto-lib.git 68 | cd ./crypto-lib/libhl-crypto 69 | cargo build 70 | cd .. 71 | ``` 72 | 1. Run tests 73 | ``` 74 | cd libhl-crypto 75 | cargo test 76 | ``` 77 | **Note:** 78 | By default `cargo build` produce debug artifacts with a large amount of run-time checks. 79 | It's good for development, but this build can be in 100+ times slower for some math calculation. 80 | If you would like to analyse CPU performance of libindy-crypto for your use case, you have to use release artifacts (`cargo build --release`). 81 | 82 | ### Windows build dependency 83 | System OpenSSL library is required. 84 | - Download the prebuilt dependencies [here](https://repo.sovrin.org/windows/libindy_crypto/deps/) 85 | - Extract them into the folder _C:\BIN\x64_ 86 | > It really doesn't matter where you put these as long as you remember where so you can set 87 | > the environment variables to this path 88 | - Point path to this directory using environment variables: 89 | - set INDY_CRYPTO_PREBUILT_DEPS_DIR=C:\BIN\x64 90 | - set OPENSSL_DIR=C:\BIN\x64 91 | 92 | ## Documentation 93 | Project documentation is available via sphinx. 94 | Install sphinx: 95 | ``` 96 | pip install -U Sphinx 97 | ``` 98 | Build the project docs: 99 | ``` 100 | cd docs/ 101 | make html 102 | ``` 103 | 104 | API documentation is now available as rust doc in code. See: 105 | * C API 106 | - [BLS](libhl-crypto/src/ffi/bls.rs) 107 | - [CL](libhl-crypto/src/ffi/cl) 108 | * Rust API 109 | - [BLS](libhl-crypto/src/bls/mod.rs) 110 | - [CL](libhl-crypto/src/cl) 111 | 112 | ## Binaries 113 | 114 | Note: Binaries creation is in progress now!!! 115 | 116 | Builded binaries can be downloaded from https://repo.sovrin.org: 117 | * sdk/lib/apt/xenial/{master,stable,rc} - Ubuntu deb packages 118 | * windows/libindy_crypto/{master,stable,rc} - Windows zip-archive with all required DLLs (include libindy itself) and headers 119 | * ios/libindy_crypto/stable/ - Pods for iOS 120 | * rhel/libindy_crypto/{master,stable,rc} - RHEL rpms 121 | 122 | Also Ubuntu deb packages can be installed from APT repository: 123 | ``` 124 | apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 68DB5E88 125 | sudo add-apt-repository "deb https://repo.sovrin.org/sdk/deb xenial stable" 126 | sudo apt-get update 127 | sudo apt-get install -y libindy-crypto 128 | ``` 129 | 130 | -------------------------------------------------------------------------------- /libhl-crypto/src/hash/blake2.rs: -------------------------------------------------------------------------------- 1 | use super::Digest; 2 | use CryptoError; 3 | use blake2b_simd::{Params, State}; 4 | 5 | macro_rules! impl_hasher { 6 | ($thing:ident,$size:tt) => { 7 | impl Digest for $thing { 8 | #[inline] 9 | fn new() -> $thing { 10 | $thing(Params::new() 11 | .hash_length($size) 12 | .to_state()) 13 | } 14 | #[inline] 15 | fn reset(&mut self) { 16 | self.0 = Params::new() 17 | .hash_length($size) 18 | .to_state(); 19 | } 20 | #[inline] 21 | fn update(&mut self, data: &[u8]) { 22 | self.0.update(data); 23 | } 24 | #[inline] 25 | fn finalize(&mut self) -> Result, CryptoError> { 26 | Ok(self.0.finalize().as_bytes().to_vec()) 27 | } 28 | } 29 | }; 30 | } 31 | 32 | pub struct Blake2b256(State); 33 | impl_hasher!(Blake2b256, 32); 34 | 35 | pub struct Blake2b384(State); 36 | impl_hasher!(Blake2b384, 48); 37 | 38 | pub struct Blake2b512(State); 39 | impl_hasher!(Blake2b512, 64); 40 | 41 | #[cfg(test)] 42 | mod tests { 43 | // See https://raw.githubusercontent.com/BLAKE2/BLAKE2/master/testvectors/blake2b-kat.txt 44 | use super::*; 45 | use encoding::hex::hex2bin; 46 | 47 | #[test] 48 | fn blake2b_256() { 49 | let mut hasher = Blake2b256::new(); 50 | let message = b""; 51 | let expected = hex2bin("0e5751c026e543b2e8ab2eb06099daa1d1e5df47778f7787faab45cdf12fe3a8").unwrap(); 52 | 53 | hasher.update(&message[..]); 54 | let result = hasher.finalize().unwrap(); 55 | assert_eq!(expected.to_vec(), result); 56 | 57 | let mut hasher = Blake2b256::new(); 58 | let message = b"00"; 59 | let expected = hex2bin("cbc63dc2acb86bd8967453ef98fd4f2be2f26d7337a0937958211c128a18b442").unwrap(); 60 | 61 | hasher.update(&message[..]); 62 | let result = hasher.finalize().unwrap(); 63 | assert_eq!(expected.to_vec(), result); 64 | 65 | let mut hasher = Blake2b256::new(); 66 | let message = b"0001"; 67 | let expected = hex2bin("e6a2a7281707b12d5c44315845a63651602dc8e387693161103326263ef64cb2").unwrap(); 68 | 69 | hasher.update(&message[..]); 70 | let result = hasher.finalize().unwrap(); 71 | assert_eq!(expected.to_vec(), result); 72 | } 73 | 74 | #[test] 75 | fn blake2b_384() { 76 | let mut hasher = Blake2b384::new(); 77 | let message = b""; 78 | let expected = hex2bin("b32811423377f52d7862286ee1a72ee540524380fda1724a6f25d7978c6fd3244a6caf0498812673c5e05ef583825100").unwrap(); 79 | 80 | hasher.update(&message[..]); 81 | let result = hasher.finalize().unwrap(); 82 | assert_eq!(expected.to_vec(), result); 83 | 84 | let mut hasher = Blake2b384::new(); 85 | let message = b"00"; 86 | let expected = hex2bin("0604ba2f245f0e2896aace5b03ddfe41beab2e7966929ecf387edc1c85d666233ef280e3caf85b910792851307a7309e").unwrap(); 87 | 88 | hasher.update(&message[..]); 89 | let result = hasher.finalize().unwrap(); 90 | assert_eq!(expected.to_vec(), result); 91 | 92 | let mut hasher = Blake2b384::new(); 93 | let message = b"0001"; 94 | let expected = hex2bin("723f6fe6589ccc1bb9504d280499426d2c448e0765b9ebfe28194e12dad66718109b8176f733625df925194c7e00e594").unwrap(); 95 | 96 | hasher.update(&message[..]); 97 | let result = hasher.finalize().unwrap(); 98 | assert_eq!(expected.to_vec(), result); 99 | } 100 | 101 | #[test] 102 | fn blake2b_512() { 103 | let mut hasher = Blake2b512::new(); 104 | let message = b""; 105 | let expected = hex2bin("786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce").unwrap(); 106 | 107 | hasher.update(&message[..]); 108 | let result = hasher.finalize().unwrap(); 109 | assert_eq!(expected.to_vec(), result); 110 | 111 | let mut hasher = Blake2b512::new(); 112 | let message = b"00"; 113 | let expected = hex2bin("7a4754f2de4589268c2a2d11914f71a1cf170c3f245e9b0593c27ab27f8d19a962da68e8d7e2d229e52510481ef285a0031ad3ac88f35a586ab6347b1716db02").unwrap(); 114 | 115 | hasher.update(&message[..]); 116 | let result = hasher.finalize().unwrap(); 117 | assert_eq!(expected.to_vec(), result); 118 | 119 | let mut hasher = Blake2b512::new(); 120 | let message = b"0001"; 121 | let expected = hex2bin("b0e209d7640593ad8b8a0260ade998d72dc5a57aaa48a21388f0f54f0472d4d9f7acc936a95d19bbb7f8066c57cd1409cbd43b82a5faa4084017cb83a0dc5313").unwrap(); 122 | 123 | hasher.update(&message[..]); 124 | let result = hasher.finalize().unwrap(); 125 | assert_eq!(expected.to_vec(), result); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /libhl-crypto/src/hash/sha2.rs: -------------------------------------------------------------------------------- 1 | use super::Digest; 2 | use CryptoError; 3 | 4 | use amcl_3::hash256::HASH256; 5 | use amcl_3::hash384::HASH384; 6 | use amcl_3::hash512::HASH512; 7 | 8 | macro_rules! impl_hasher { 9 | ($thing:ident,$wrapped:ident) => { 10 | impl Digest for $thing { 11 | #[inline] 12 | fn new() -> $thing { 13 | $thing($wrapped::new()) 14 | } 15 | #[inline] 16 | fn reset(&mut self) { 17 | self.0.init() 18 | } 19 | #[inline] 20 | fn update(&mut self, data: &[u8]) { 21 | self.0.process_array(data) 22 | } 23 | #[inline] 24 | fn finalize(&mut self) -> Result, CryptoError> { 25 | Ok(self.0.hash().to_vec()) 26 | } 27 | } 28 | }; 29 | } 30 | 31 | pub struct Sha256(HASH256); 32 | impl_hasher!(Sha256, HASH256); 33 | 34 | pub struct Sha384(HASH384); 35 | impl_hasher!(Sha384, HASH384); 36 | 37 | pub struct Sha512(HASH512); 38 | impl_hasher!(Sha512, HASH512); 39 | 40 | #[cfg(test)] 41 | mod tests { 42 | use super::*; 43 | use encoding::hex::hex2bin; 44 | 45 | #[test] 46 | fn sha2_256() { 47 | let mut hasher = Sha256::new(); 48 | // Taken from https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2withchangenotice.pdf 49 | let message = b"abc"; 50 | let expected = hex2bin("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD").unwrap(); 51 | 52 | hasher.update(&message[..]); 53 | let result = hasher.finalize().unwrap(); 54 | assert_eq!(expected.to_vec(), result); 55 | 56 | let message = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"; 57 | let expected = hex2bin("248D6A61D20638B8E5C026930C3E6039A33CE45964FF2167F6ECEDD419DB06C1").unwrap(); 58 | 59 | hasher.update(&message[..]); 60 | let result = hasher.finalize().unwrap(); 61 | assert_eq!(expected.to_vec(), result); 62 | 63 | let expected = hex2bin("CDC76E5C9914FB9281A1C7E284D73E67F1809A48A497200E046D39CCC7112CD0").unwrap(); 64 | for _ in 0..1000000 { 65 | hasher.update(b"a"); 66 | } 67 | let result = hasher.finalize().unwrap(); 68 | assert_eq!(expected.to_vec(), result); 69 | } 70 | 71 | #[test] 72 | fn sha2_384() { 73 | let mut hasher = Sha384::new(); 74 | // Taken from https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2withchangenotice.pdf 75 | let message = b"abc"; 76 | let expected = hex2bin("cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7").unwrap(); 77 | 78 | hasher.update(&message[..]); 79 | let result = hasher.finalize().unwrap(); 80 | assert_eq!(expected.to_vec(), result); 81 | 82 | let message = b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"; 83 | let expected = hex2bin("09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039").unwrap(); 84 | 85 | hasher.update(&message[..]); 86 | let result = hasher.finalize().unwrap(); 87 | assert_eq!(expected.to_vec(), result); 88 | 89 | let expected = hex2bin("9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985").unwrap(); 90 | for _ in 0..1000000 { 91 | hasher.update(b"a"); 92 | } 93 | let result = hasher.finalize().unwrap(); 94 | assert_eq!(expected.to_vec(), result); 95 | } 96 | 97 | #[test] 98 | fn sha2_512() { 99 | let mut hasher = Sha512::new(); 100 | // Taken from https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2withchangenotice.pdf 101 | let message = b"abc"; 102 | 103 | let expected = hex2bin("ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f").unwrap(); 104 | 105 | hasher.update(&message[..]); 106 | let result = hasher.finalize().unwrap(); 107 | assert_eq!(expected.to_vec(), result); 108 | 109 | let message = b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"; 110 | let expected = hex2bin("8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909").unwrap(); 111 | 112 | hasher.update(&message[..]); 113 | let result = hasher.finalize().unwrap(); 114 | assert_eq!(expected.to_vec(), result); 115 | 116 | let expected = hex2bin("e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b").unwrap(); 117 | for _ in 0..1000000 { 118 | hasher.update(b"a"); 119 | } 120 | let result = hasher.finalize().unwrap(); 121 | assert_eq!(expected.to_vec(), result); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/master/config 8 | 9 | # -- Path setup -------------------------------------------------------------- 10 | 11 | # If extensions (or modules to document with autodoc) are in another directory, 12 | # add these directories to sys.path here. If the directory is relative to the 13 | # documentation root, use os.path.abspath to make it absolute, like shown here. 14 | # 15 | # import os 16 | # import sys 17 | # sys.path.insert(0, os.path.abspath('.')) 18 | 19 | 20 | # -- Project information ----------------------------------------------------- 21 | 22 | project = 'Hyperledger Ursa' 23 | copyright = '2018, Ursa Contributors' 24 | author = 'Ursa Contributors' 25 | 26 | # The short X.Y version 27 | version = '' 28 | # The full version, including alpha/beta/rc tags 29 | release = 'pre-release' 30 | 31 | 32 | # -- General configuration --------------------------------------------------- 33 | 34 | # If your documentation needs a minimal Sphinx version, state it here. 35 | # 36 | # needs_sphinx = '1.0' 37 | 38 | # Add any Sphinx extension module names here, as strings. They can be 39 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 40 | # ones. 41 | extensions = [ 42 | 'sphinx.ext.mathjax', 43 | 'sphinx.ext.githubpages', 44 | ] 45 | 46 | # Add any paths that contain templates here, relative to this directory. 47 | templates_path = ['_templates'] 48 | 49 | # The suffix(es) of source filenames. 50 | # You can specify multiple suffix as a list of string: 51 | # 52 | # source_suffix = ['.rst', '.md'] 53 | source_suffix = '.rst' 54 | 55 | # The master toctree document. 56 | master_doc = 'contents' 57 | 58 | # The language for content autogenerated by Sphinx. Refer to documentation 59 | # for a list of supported languages. 60 | # 61 | # This is also used if you do content translation via gettext catalogs. 62 | # Usually you set "language" from the command line for these cases. 63 | language = None 64 | 65 | # List of patterns, relative to source directory, that match files and 66 | # directories to ignore when looking for source files. 67 | # This pattern also affects html_static_path and html_extra_path. 68 | exclude_patterns = [] 69 | 70 | # The name of the Pygments (syntax highlighting) style to use. 71 | pygments_style = None 72 | 73 | 74 | # -- Options for HTML output ------------------------------------------------- 75 | 76 | # The theme to use for HTML and HTML Help pages. See the documentation for 77 | # a list of builtin themes. 78 | # 79 | html_theme = 'alabaster' 80 | 81 | # Theme options are theme-specific and customize the look and feel of a theme 82 | # further. For a list of options available for each theme, see the 83 | # documentation. 84 | # 85 | # html_theme_options = {} 86 | 87 | # Add any paths that contain custom static files (such as style sheets) here, 88 | # relative to this directory. They are copied after the builtin static files, 89 | # so a file named "default.css" will overwrite the builtin "default.css". 90 | html_static_path = ['_static'] 91 | 92 | # Custom sidebar templates, must be a dictionary that maps document names 93 | # to template names. 94 | # 95 | # The default sidebars (for documents that don't match any pattern) are 96 | # defined by theme itself. Builtin themes are using these templates by 97 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 98 | # 'searchbox.html']``. 99 | # 100 | # html_sidebars = {} 101 | 102 | 103 | # -- Options for HTMLHelp output --------------------------------------------- 104 | 105 | # Output file base name for HTML help builder. 106 | htmlhelp_basename = 'HyperledgerUrsadoc' 107 | 108 | 109 | # -- Options for LaTeX output ------------------------------------------------ 110 | 111 | latex_elements = { 112 | # The paper size ('letterpaper' or 'a4paper'). 113 | # 114 | # 'papersize': 'letterpaper', 115 | 116 | # The font size ('10pt', '11pt' or '12pt'). 117 | # 118 | # 'pointsize': '10pt', 119 | 120 | # Additional stuff for the LaTeX preamble. 121 | # 122 | # 'preamble': '', 123 | 124 | # Latex figure (float) alignment 125 | # 126 | # 'figure_align': 'htbp', 127 | } 128 | 129 | # Grouping the document tree into LaTeX files. List of tuples 130 | # (source start file, target name, title, 131 | # author, documentclass [howto, manual, or own class]). 132 | latex_documents = [ 133 | (master_doc, 'HyperledgerUrsa.tex', 'Hyperledger Ursa Documentation', 134 | 'Ursa Contributors', 'manual'), 135 | ] 136 | 137 | 138 | # -- Options for manual page output ------------------------------------------ 139 | 140 | # One entry per manual page. List of tuples 141 | # (source start file, name, description, authors, manual section). 142 | man_pages = [ 143 | (master_doc, 'hyperledgerursa', 'Hyperledger Ursa Documentation', 144 | [author], 1) 145 | ] 146 | 147 | 148 | # -- Options for Texinfo output ---------------------------------------------- 149 | 150 | # Grouping the document tree into Texinfo files. List of tuples 151 | # (source start file, target name, title, author, 152 | # dir menu entry, description, category) 153 | texinfo_documents = [ 154 | (master_doc, 'HyperledgerUrsa', 'Hyperledger Ursa Documentation', 155 | author, 'HyperledgerUrsa', 'One line description of project.', 156 | 'Miscellaneous'), 157 | ] 158 | 159 | 160 | # -- Options for Epub output ------------------------------------------------- 161 | 162 | # Bibliographic Dublin Core info. 163 | epub_title = project 164 | 165 | # The unique identifier of the text. This can be a ISBN number 166 | # or the project homepage. 167 | # 168 | # epub_identifier = '' 169 | 170 | # A unique identification for the text. 171 | # 172 | # epub_uid = '' 173 | 174 | # A list of files that should not be packed into the epub file. 175 | epub_exclude_files = ['search.html'] 176 | 177 | 178 | # -- Extension configuration ------------------------------------------------- 179 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/hash256.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | const HASH256_H0: u32=0x6A09E667; 21 | const HASH256_H1: u32=0xBB67AE85; 22 | const HASH256_H2: u32=0x3C6EF372; 23 | const HASH256_H3: u32=0xA54FF53A; 24 | const HASH256_H4: u32=0x510E527F; 25 | const HASH256_H5: u32=0x9B05688C; 26 | const HASH256_H6: u32=0x1F83D9AB; 27 | const HASH256_H7: u32=0x5BE0CD19; 28 | 29 | const HASH256_K : [u32;64]=[ 30 | 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 31 | 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, 32 | 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, 33 | 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, 34 | 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, 35 | 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, 36 | 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, 37 | 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]; 38 | 39 | 40 | pub struct HASH256 { 41 | length: [u32;2], 42 | h: [u32;8], 43 | w: [u32;64] 44 | } 45 | 46 | impl HASH256 { 47 | fn s(n: u32,x: u32) -> u32 { 48 | return ((x)>>n) | ((x)<<(32-n)); 49 | } 50 | fn r(n: u32,x: u32) -> u32 { 51 | return (x)>>n; 52 | } 53 | 54 | fn ch(x: u32,y: u32,z: u32) -> u32 { 55 | return (x&y)^(!(x)&z); 56 | } 57 | 58 | fn maj(x: u32,y: u32,z: u32) -> u32 { 59 | return (x&y)^(x&z)^(y&z); 60 | } 61 | fn sig0(x: u32) -> u32 { 62 | return HASH256::s(2,x)^HASH256::s(13,x)^HASH256::s(22,x); 63 | } 64 | 65 | fn sig1(x: u32) -> u32 { 66 | return HASH256::s(6,x)^HASH256::s(11,x)^HASH256::s(25,x); 67 | } 68 | 69 | fn theta0(x: u32) -> u32 { 70 | return HASH256::s(7,x)^HASH256::s(18,x)^HASH256::r(3,x); 71 | } 72 | 73 | fn theta1(x: u32) -> u32 { 74 | return HASH256::s(17,x)^HASH256::s(19,x)^HASH256::r(10,x); 75 | } 76 | 77 | fn transform(&mut self) { /* basic transformation step */ 78 | for j in 16..64 { 79 | self.w[j]=HASH256::theta1(self.w[j-2]).wrapping_add(self.w[j-7]).wrapping_add(HASH256::theta0(self.w[j-15])).wrapping_add(self.w[j-16]); 80 | } 81 | let mut a=self.h[0]; let mut b=self.h[1]; let mut c=self.h[2]; let mut d=self.h[3]; 82 | let mut e=self.h[4]; let mut f=self.h[5]; let mut g=self.h[6]; let mut hh=self.h[7]; 83 | for j in 0..64 { /* 64 times - mush it up */ 84 | let t1=hh.wrapping_add(HASH256::sig1(e)).wrapping_add(HASH256::ch(e,f,g)).wrapping_add(HASH256_K[j]).wrapping_add(self.w[j]); 85 | let t2=HASH256::sig0(a).wrapping_add(HASH256::maj(a,b,c)); 86 | hh=g; g=f; f=e; 87 | e=d.wrapping_add(t1); 88 | d=c; 89 | c=b; 90 | b=a; 91 | a=t1.wrapping_add(t2) ; 92 | } 93 | self.h[0]=self.h[0].wrapping_add(a); self.h[1]=self.h[1].wrapping_add(b); self.h[2]=self.h[2].wrapping_add(c); self.h[3]=self.h[3].wrapping_add(d); 94 | self.h[4]=self.h[4].wrapping_add(e); self.h[5]=self.h[5].wrapping_add(f); self.h[6]=self.h[6].wrapping_add(g); self.h[7]=self.h[7].wrapping_add(hh); 95 | 96 | } 97 | 98 | /* Initialise Hash function */ 99 | pub fn init(&mut self) { /* initialise */ 100 | for i in 0..64 {self.w[i]=0} 101 | self.length[0]=0; self.length[1]=0; 102 | self.h[0]=HASH256_H0; 103 | self.h[1]=HASH256_H1; 104 | self.h[2]=HASH256_H2; 105 | self.h[3]=HASH256_H3; 106 | self.h[4]=HASH256_H4; 107 | self.h[5]=HASH256_H5; 108 | self.h[6]=HASH256_H6; 109 | self.h[7]=HASH256_H7; 110 | } 111 | 112 | pub fn new() -> HASH256 { 113 | let mut nh=HASH256 { 114 | length: [0;2], 115 | h: [0;8], 116 | w: [0;64] 117 | }; 118 | nh.init(); 119 | return nh; 120 | } 121 | 122 | /* process a single byte */ 123 | pub fn process(&mut self,byt: u8) { /* process the next message byte */ 124 | let cnt=((self.length[0]/32)%16) as usize; 125 | self.w[cnt]<<=8; 126 | self.w[cnt]|=(byt&0xFF) as u32; 127 | self.length[0]+=8; 128 | if self.length[0]==0 {self.length[1]+=1; self.length[0]=0} 129 | if (self.length[0]%512)==0 {self.transform()} 130 | } 131 | 132 | /* process an array of bytes */ 133 | pub fn process_array(&mut self,b: &[u8]) { 134 | for i in 0..b.len() {self.process(b[i])} 135 | } 136 | 137 | /* process a 32-bit integer */ 138 | pub fn process_num(&mut self,n: i32) { 139 | self.process(((n>>24)&0xff) as u8); 140 | self.process(((n>>16)&0xff) as u8); 141 | self.process(((n>>8)&0xff) as u8); 142 | self.process((n&0xff) as u8); 143 | } 144 | 145 | /* Generate 32-byte Hash */ 146 | pub fn hash(&mut self) -> [u8;32] { /* pad message and finish - supply digest */ 147 | let mut digest:[u8;32]=[0;32]; 148 | let len0=self.length[0]; 149 | let len1=self.length[1]; 150 | self.process(0x80); 151 | while (self.length[0]%512)!=448 {self.process(0)} 152 | self.w[14]=len1; 153 | self.w[15]=len0; 154 | self.transform(); 155 | for i in 0..32 { /* convert to bytes */ 156 | digest[i]=((self.h[i/4]>>(8*(3-i%4))) & 0xff) as u8; 157 | } 158 | self.init(); 159 | return digest; 160 | } 161 | } 162 | 163 | //248d6a61 d20638b8 e5c02693 0c3e6039 a33ce459 64ff2167 f6ecedd4 19db06c1 164 | /* 165 | fn main() { 166 | let s = String::from("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); 167 | let test = s.into_bytes(); 168 | let mut sh=HASH256::new(); 169 | 170 | for i in 0..test.len(){ 171 | sh.process(test[i]); 172 | } 173 | 174 | let digest=sh.hash(); 175 | for i in 0..32 {print!("{:02x}",digest[i])} 176 | } 177 | */ 178 | -------------------------------------------------------------------------------- /libhl-crypto/src/errors/mod.rs: -------------------------------------------------------------------------------- 1 | extern crate serde_json; 2 | 3 | use ffi::ErrorCode; 4 | 5 | use std::error::Error; 6 | use std::{fmt, io}; 7 | 8 | pub trait ToErrorCode { 9 | fn to_error_code(&self) -> ErrorCode; 10 | } 11 | 12 | #[derive(Debug)] 13 | pub enum HLCryptoError { 14 | InvalidParam1(String), 15 | InvalidParam2(String), 16 | InvalidParam3(String), 17 | InvalidParam4(String), 18 | InvalidParam5(String), 19 | InvalidParam6(String), 20 | InvalidParam7(String), 21 | InvalidParam8(String), 22 | InvalidParam9(String), 23 | InvalidState(String), 24 | InvalidStructure(String), 25 | IOError(io::Error), 26 | AnoncredsRevocationAccumulatorIsFull(String), 27 | AnoncredsInvalidRevocationAccumulatorIndex(String), 28 | AnoncredsCredentialRevoked(String), 29 | AnoncredsProofRejected(String), 30 | } 31 | 32 | impl fmt::Display for HLCryptoError { 33 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 34 | match *self { 35 | HLCryptoError::InvalidParam1(ref description) => write!(f, "Invalid param 1: {}", description), 36 | HLCryptoError::InvalidParam2(ref description) => write!(f, "Invalid param 2: {}", description), 37 | HLCryptoError::InvalidParam3(ref description) => write!(f, "Invalid param 3: {}", description), 38 | HLCryptoError::InvalidParam4(ref description) => write!(f, "Invalid param 4: {}", description), 39 | HLCryptoError::InvalidParam5(ref description) => write!(f, "Invalid param 4: {}", description), 40 | HLCryptoError::InvalidParam6(ref description) => write!(f, "Invalid param 4: {}", description), 41 | HLCryptoError::InvalidParam7(ref description) => write!(f, "Invalid param 4: {}", description), 42 | HLCryptoError::InvalidParam8(ref description) => write!(f, "Invalid param 4: {}", description), 43 | HLCryptoError::InvalidParam9(ref description) => write!(f, "Invalid param 4: {}", description), 44 | HLCryptoError::InvalidState(ref description) => write!(f, "Invalid library state: {}", description), 45 | HLCryptoError::InvalidStructure(ref description) => write!(f, "Invalid structure: {}", description), 46 | HLCryptoError::IOError(ref err) => err.fmt(f), 47 | HLCryptoError::AnoncredsRevocationAccumulatorIsFull(ref description) => write!(f, "Revocation accumulator is full: {}", description), 48 | HLCryptoError::AnoncredsInvalidRevocationAccumulatorIndex(ref description) => write!(f, "Invalid revocation accumulator index: {}", description), 49 | HLCryptoError::AnoncredsCredentialRevoked(ref description) => write!(f, "Credential revoked: {}", description), 50 | HLCryptoError::AnoncredsProofRejected(ref description) => write!(f, "Proof rejected: {}", description), 51 | } 52 | } 53 | } 54 | 55 | impl Error for HLCryptoError { 56 | fn description(&self) -> &str { 57 | match *self { 58 | HLCryptoError::InvalidParam1(ref description) => description, 59 | HLCryptoError::InvalidParam2(ref description) => description, 60 | HLCryptoError::InvalidParam3(ref description) => description, 61 | HLCryptoError::InvalidParam4(ref description) => description, 62 | HLCryptoError::InvalidParam5(ref description) => description, 63 | HLCryptoError::InvalidParam6(ref description) => description, 64 | HLCryptoError::InvalidParam7(ref description) => description, 65 | HLCryptoError::InvalidParam8(ref description) => description, 66 | HLCryptoError::InvalidParam9(ref description) => description, 67 | HLCryptoError::InvalidState(ref description) => description, 68 | HLCryptoError::InvalidStructure(ref description) => description, 69 | HLCryptoError::IOError(ref err) => err.description(), 70 | HLCryptoError::AnoncredsRevocationAccumulatorIsFull(ref description) => description, 71 | HLCryptoError::AnoncredsInvalidRevocationAccumulatorIndex(ref description) => description, 72 | HLCryptoError::AnoncredsCredentialRevoked(ref description) => description, 73 | HLCryptoError::AnoncredsProofRejected(ref description) => description, 74 | } 75 | } 76 | 77 | fn cause(&self) -> Option<&Error> { 78 | match *self { 79 | HLCryptoError::InvalidParam1(_) | 80 | HLCryptoError::InvalidParam2(_) | 81 | HLCryptoError::InvalidParam3(_) | 82 | HLCryptoError::InvalidParam4(_) | 83 | HLCryptoError::InvalidParam5(_) | 84 | HLCryptoError::InvalidParam6(_) | 85 | HLCryptoError::InvalidParam7(_) | 86 | HLCryptoError::InvalidParam8(_) | 87 | HLCryptoError::InvalidParam9(_) | 88 | HLCryptoError::InvalidState(_) | 89 | HLCryptoError::InvalidStructure(_) => None, 90 | HLCryptoError::IOError(ref err) => Some(err), 91 | HLCryptoError::AnoncredsRevocationAccumulatorIsFull(_) => None, 92 | HLCryptoError::AnoncredsInvalidRevocationAccumulatorIndex(_) => None, 93 | HLCryptoError::AnoncredsCredentialRevoked(_) => None, 94 | HLCryptoError::AnoncredsProofRejected(_) => None, 95 | } 96 | } 97 | } 98 | 99 | impl ToErrorCode for HLCryptoError { 100 | fn to_error_code(&self) -> ErrorCode { 101 | match *self { 102 | HLCryptoError::InvalidParam1(_) => ErrorCode::CommonInvalidParam1, 103 | HLCryptoError::InvalidParam2(_) => ErrorCode::CommonInvalidParam2, 104 | HLCryptoError::InvalidParam3(_) => ErrorCode::CommonInvalidParam3, 105 | HLCryptoError::InvalidParam4(_) => ErrorCode::CommonInvalidParam4, 106 | HLCryptoError::InvalidParam5(_) => ErrorCode::CommonInvalidParam5, 107 | HLCryptoError::InvalidParam6(_) => ErrorCode::CommonInvalidParam6, 108 | HLCryptoError::InvalidParam7(_) => ErrorCode::CommonInvalidParam7, 109 | HLCryptoError::InvalidParam8(_) => ErrorCode::CommonInvalidParam8, 110 | HLCryptoError::InvalidParam9(_) => ErrorCode::CommonInvalidParam9, 111 | HLCryptoError::InvalidState(_) => ErrorCode::CommonInvalidState, 112 | HLCryptoError::InvalidStructure(_) => ErrorCode::CommonInvalidStructure, 113 | HLCryptoError::IOError(_) => ErrorCode::CommonIOError, 114 | HLCryptoError::AnoncredsRevocationAccumulatorIsFull(_) => ErrorCode::AnoncredsRevocationAccumulatorIsFull, 115 | HLCryptoError::AnoncredsInvalidRevocationAccumulatorIndex(_) => ErrorCode::AnoncredsInvalidRevocationAccumulatorIndex, 116 | HLCryptoError::AnoncredsCredentialRevoked(_) => ErrorCode::AnoncredsCredentialRevoked, 117 | HLCryptoError::AnoncredsProofRejected(_) => ErrorCode::AnoncredsProofRejected, 118 | } 119 | } 120 | } 121 | 122 | impl From for HLCryptoError { 123 | fn from(err: serde_json::Error) -> HLCryptoError { 124 | HLCryptoError::InvalidStructure(err.to_string()) 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/hash384.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | const HASH384_H0: u64=0xcbbb9d5dc1059ed8; 21 | const HASH384_H1: u64=0x629a292a367cd507; 22 | const HASH384_H2: u64=0x9159015a3070dd17; 23 | const HASH384_H3: u64=0x152fecd8f70e5939; 24 | const HASH384_H4: u64=0x67332667ffc00b31; 25 | const HASH384_H5: u64=0x8eb44a8768581511; 26 | const HASH384_H6: u64=0xdb0c2e0d64f98fa7; 27 | const HASH384_H7: u64=0x47b5481dbefa4fa4; 28 | 29 | const HASH384_K : [u64;80]=[ 30 | 0x428a2f98d728ae22,0x7137449123ef65cd,0xb5c0fbcfec4d3b2f,0xe9b5dba58189dbbc, 31 | 0x3956c25bf348b538,0x59f111f1b605d019,0x923f82a4af194f9b,0xab1c5ed5da6d8118, 32 | 0xd807aa98a3030242,0x12835b0145706fbe,0x243185be4ee4b28c,0x550c7dc3d5ffb4e2, 33 | 0x72be5d74f27b896f,0x80deb1fe3b1696b1,0x9bdc06a725c71235,0xc19bf174cf692694, 34 | 0xe49b69c19ef14ad2,0xefbe4786384f25e3,0x0fc19dc68b8cd5b5,0x240ca1cc77ac9c65, 35 | 0x2de92c6f592b0275,0x4a7484aa6ea6e483,0x5cb0a9dcbd41fbd4,0x76f988da831153b5, 36 | 0x983e5152ee66dfab,0xa831c66d2db43210,0xb00327c898fb213f,0xbf597fc7beef0ee4, 37 | 0xc6e00bf33da88fc2,0xd5a79147930aa725,0x06ca6351e003826f,0x142929670a0e6e70, 38 | 0x27b70a8546d22ffc,0x2e1b21385c26c926,0x4d2c6dfc5ac42aed,0x53380d139d95b3df, 39 | 0x650a73548baf63de,0x766a0abb3c77b2a8,0x81c2c92e47edaee6,0x92722c851482353b, 40 | 0xa2bfe8a14cf10364,0xa81a664bbc423001,0xc24b8b70d0f89791,0xc76c51a30654be30, 41 | 0xd192e819d6ef5218,0xd69906245565a910,0xf40e35855771202a,0x106aa07032bbd1b8, 42 | 0x19a4c116b8d2d0c8,0x1e376c085141ab53,0x2748774cdf8eeb99,0x34b0bcb5e19b48a8, 43 | 0x391c0cb3c5c95a63,0x4ed8aa4ae3418acb,0x5b9cca4f7763e373,0x682e6ff3d6b2b8a3, 44 | 0x748f82ee5defb2fc,0x78a5636f43172f60,0x84c87814a1f0ab72,0x8cc702081a6439ec, 45 | 0x90befffa23631e28,0xa4506cebde82bde9,0xbef9a3f7b2c67915,0xc67178f2e372532b, 46 | 0xca273eceea26619c,0xd186b8c721c0c207,0xeada7dd6cde0eb1e,0xf57d4f7fee6ed178, 47 | 0x06f067aa72176fba,0x0a637dc5a2c898a6,0x113f9804bef90dae,0x1b710b35131c471b, 48 | 0x28db77f523047d84,0x32caab7b40c72493,0x3c9ebe0a15c9bebc,0x431d67c49c100d4c, 49 | 0x4cc5d4becb3e42b6,0x597f299cfc657e2a,0x5fcb6fab3ad6faec,0x6c44198c4a475817]; 50 | 51 | 52 | pub struct HASH384 { 53 | length: [u64;2], 54 | h: [u64;8], 55 | w: [u64;80] 56 | } 57 | 58 | impl HASH384 { 59 | fn s(n: u64,x: u64) -> u64 { 60 | return ((x)>>n) | ((x)<<(64-n)); 61 | } 62 | fn r(n: u64,x: u64) -> u64 { 63 | return (x)>>n; 64 | } 65 | 66 | fn ch(x: u64,y: u64,z: u64) -> u64 { 67 | return (x&y)^(!(x)&z); 68 | } 69 | 70 | fn maj(x: u64,y: u64,z: u64) -> u64 { 71 | return (x&y)^(x&z)^(y&z); 72 | } 73 | 74 | fn sig0(x: u64) -> u64 { 75 | return HASH384::s(28,x)^HASH384::s(34,x)^HASH384::s(39,x); 76 | } 77 | 78 | fn sig1(x: u64) -> u64 { 79 | return HASH384::s(14,x)^HASH384::s(18,x)^HASH384::s(41,x); 80 | } 81 | 82 | fn theta0(x: u64) -> u64 { 83 | return HASH384::s(1,x)^HASH384::s(8,x)^HASH384::r(7,x); 84 | } 85 | 86 | fn theta1(x: u64) -> u64 { 87 | return HASH384::s(19,x)^HASH384::s(61,x)^HASH384::r(6,x); 88 | } 89 | 90 | fn transform(&mut self) { /* basic transformation step */ 91 | for j in 16..80 { 92 | self.w[j]=HASH384::theta1(self.w[j-2]).wrapping_add(self.w[j-7]).wrapping_add(HASH384::theta0(self.w[j-15])).wrapping_add(self.w[j-16]); 93 | } 94 | let mut a=self.h[0]; let mut b=self.h[1]; let mut c=self.h[2]; let mut d=self.h[3]; 95 | let mut e=self.h[4]; let mut f=self.h[5]; let mut g=self.h[6]; let mut hh=self.h[7]; 96 | for j in 0..80 { /* 64 times - mush it up */ 97 | let t1=hh.wrapping_add(HASH384::sig1(e)).wrapping_add(HASH384::ch(e,f,g)).wrapping_add(HASH384_K[j]).wrapping_add(self.w[j]); 98 | let t2=HASH384::sig0(a).wrapping_add(HASH384::maj(a,b,c)); 99 | hh=g; g=f; f=e; 100 | e=d.wrapping_add(t1); 101 | d=c; 102 | c=b; 103 | b=a; 104 | a=t1.wrapping_add(t2) ; 105 | } 106 | self.h[0]=self.h[0].wrapping_add(a); self.h[1]=self.h[1].wrapping_add(b); self.h[2]=self.h[2].wrapping_add(c); self.h[3]=self.h[3].wrapping_add(d); 107 | self.h[4]=self.h[4].wrapping_add(e); self.h[5]=self.h[5].wrapping_add(f); self.h[6]=self.h[6].wrapping_add(g); self.h[7]=self.h[7].wrapping_add(hh); 108 | 109 | } 110 | 111 | /* Initialise Hash function */ 112 | pub fn init(&mut self) { /* initialise */ 113 | for i in 0..64 {self.w[i]=0} 114 | self.length[0]=0; self.length[1]=0; 115 | self.h[0]=HASH384_H0; 116 | self.h[1]=HASH384_H1; 117 | self.h[2]=HASH384_H2; 118 | self.h[3]=HASH384_H3; 119 | self.h[4]=HASH384_H4; 120 | self.h[5]=HASH384_H5; 121 | self.h[6]=HASH384_H6; 122 | self.h[7]=HASH384_H7; 123 | } 124 | 125 | pub fn new() -> HASH384 { 126 | let mut nh=HASH384 { 127 | length: [0;2], 128 | h: [0;8], 129 | w: [0;80] 130 | }; 131 | nh.init(); 132 | return nh; 133 | } 134 | 135 | /* process a single byte */ 136 | pub fn process(&mut self,byt: u8) { /* process the next message byte */ 137 | let cnt=((self.length[0]/64)%16) as usize; 138 | self.w[cnt]<<=8; 139 | self.w[cnt]|=(byt&0xFF) as u64; 140 | self.length[0]+=8; 141 | if self.length[0]==0 {self.length[1]+=1; self.length[0]=0} 142 | if (self.length[0]%1024)==0 {self.transform()} 143 | } 144 | 145 | /* process an array of bytes */ 146 | pub fn process_array(&mut self,b: &[u8]) { 147 | for i in 0..b.len() {self.process(b[i])} 148 | } 149 | 150 | /* process a 32-bit integer */ 151 | pub fn process_num(&mut self,n: i32) { 152 | self.process(((n>>24)&0xff) as u8); 153 | self.process(((n>>16)&0xff) as u8); 154 | self.process(((n>>8)&0xff) as u8); 155 | self.process((n&0xff) as u8); 156 | } 157 | 158 | /* Generate 32-byte Hash */ 159 | pub fn hash(&mut self) -> [u8;48] { /* pad message and finish - supply digest */ 160 | let mut digest:[u8;48]=[0;48]; 161 | let len0=self.length[0]; 162 | let len1=self.length[1]; 163 | self.process(0x80); 164 | while (self.length[0]%1024)!=896 {self.process(0)} 165 | self.w[14]=len1; 166 | self.w[15]=len0; 167 | self.transform(); 168 | for i in 0..48 { /* convert to bytes */ 169 | digest[i]=((self.h[i/8]>>(8*(7-i%8))) & 0xff) as u8; 170 | } 171 | self.init(); 172 | return digest; 173 | } 174 | } 175 | 176 | //09330c33f71147e8 3d192fc782cd1b47 53111b173b3b05d2 2fa08086e3b0f712 fcc7c71a557e2db9 66c3e9fa91746039 177 | /* 178 | fn main() { 179 | let s = String::from("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); 180 | let test = s.into_bytes(); 181 | let mut sh=HASH384::new(); 182 | 183 | for i in 0..test.len(){ 184 | sh.process(test[i]); 185 | } 186 | 187 | let digest=sh.hash(); 188 | for i in 0..48 {print!("{:02x}",digest[i])} 189 | } */ 190 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/hash512.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | 21 | const HASH512_H0: u64=0x6a09e667f3bcc908; 22 | const HASH512_H1: u64=0xbb67ae8584caa73b; 23 | const HASH512_H2: u64=0x3c6ef372fe94f82b; 24 | const HASH512_H3: u64=0xa54ff53a5f1d36f1; 25 | const HASH512_H4: u64=0x510e527fade682d1; 26 | const HASH512_H5: u64=0x9b05688c2b3e6c1f; 27 | const HASH512_H6: u64=0x1f83d9abfb41bd6b; 28 | const HASH512_H7: u64=0x5be0cd19137e2179; 29 | 30 | const HASH512_K : [u64;80]=[ 31 | 0x428a2f98d728ae22,0x7137449123ef65cd,0xb5c0fbcfec4d3b2f,0xe9b5dba58189dbbc, 32 | 0x3956c25bf348b538,0x59f111f1b605d019,0x923f82a4af194f9b,0xab1c5ed5da6d8118, 33 | 0xd807aa98a3030242,0x12835b0145706fbe,0x243185be4ee4b28c,0x550c7dc3d5ffb4e2, 34 | 0x72be5d74f27b896f,0x80deb1fe3b1696b1,0x9bdc06a725c71235,0xc19bf174cf692694, 35 | 0xe49b69c19ef14ad2,0xefbe4786384f25e3,0x0fc19dc68b8cd5b5,0x240ca1cc77ac9c65, 36 | 0x2de92c6f592b0275,0x4a7484aa6ea6e483,0x5cb0a9dcbd41fbd4,0x76f988da831153b5, 37 | 0x983e5152ee66dfab,0xa831c66d2db43210,0xb00327c898fb213f,0xbf597fc7beef0ee4, 38 | 0xc6e00bf33da88fc2,0xd5a79147930aa725,0x06ca6351e003826f,0x142929670a0e6e70, 39 | 0x27b70a8546d22ffc,0x2e1b21385c26c926,0x4d2c6dfc5ac42aed,0x53380d139d95b3df, 40 | 0x650a73548baf63de,0x766a0abb3c77b2a8,0x81c2c92e47edaee6,0x92722c851482353b, 41 | 0xa2bfe8a14cf10364,0xa81a664bbc423001,0xc24b8b70d0f89791,0xc76c51a30654be30, 42 | 0xd192e819d6ef5218,0xd69906245565a910,0xf40e35855771202a,0x106aa07032bbd1b8, 43 | 0x19a4c116b8d2d0c8,0x1e376c085141ab53,0x2748774cdf8eeb99,0x34b0bcb5e19b48a8, 44 | 0x391c0cb3c5c95a63,0x4ed8aa4ae3418acb,0x5b9cca4f7763e373,0x682e6ff3d6b2b8a3, 45 | 0x748f82ee5defb2fc,0x78a5636f43172f60,0x84c87814a1f0ab72,0x8cc702081a6439ec, 46 | 0x90befffa23631e28,0xa4506cebde82bde9,0xbef9a3f7b2c67915,0xc67178f2e372532b, 47 | 0xca273eceea26619c,0xd186b8c721c0c207,0xeada7dd6cde0eb1e,0xf57d4f7fee6ed178, 48 | 0x06f067aa72176fba,0x0a637dc5a2c898a6,0x113f9804bef90dae,0x1b710b35131c471b, 49 | 0x28db77f523047d84,0x32caab7b40c72493,0x3c9ebe0a15c9bebc,0x431d67c49c100d4c, 50 | 0x4cc5d4becb3e42b6,0x597f299cfc657e2a,0x5fcb6fab3ad6faec,0x6c44198c4a475817]; 51 | 52 | 53 | pub struct HASH512 { 54 | length: [u64;2], 55 | h: [u64;8], 56 | w: [u64;80] 57 | } 58 | 59 | impl HASH512 { 60 | fn s(n: u64,x: u64) -> u64 { 61 | return ((x)>>n) | ((x)<<(64-n)); 62 | } 63 | fn r(n: u64,x: u64) -> u64 { 64 | return (x)>>n; 65 | } 66 | 67 | fn ch(x: u64,y: u64,z: u64) -> u64 { 68 | return (x&y)^(!(x)&z); 69 | } 70 | 71 | fn maj(x: u64,y: u64,z: u64) -> u64 { 72 | return (x&y)^(x&z)^(y&z); 73 | } 74 | 75 | fn sig0(x: u64) -> u64 { 76 | return HASH512::s(28,x)^HASH512::s(34,x)^HASH512::s(39,x); 77 | } 78 | 79 | fn sig1(x: u64) -> u64 { 80 | return HASH512::s(14,x)^HASH512::s(18,x)^HASH512::s(41,x); 81 | } 82 | 83 | fn theta0(x: u64) -> u64 { 84 | return HASH512::s(1,x)^HASH512::s(8,x)^HASH512::r(7,x); 85 | } 86 | 87 | fn theta1(x: u64) -> u64 { 88 | return HASH512::s(19,x)^HASH512::s(61,x)^HASH512::r(6,x); 89 | } 90 | 91 | fn transform(&mut self) { /* basic transformation step */ 92 | for j in 16..80 { 93 | self.w[j]=HASH512::theta1(self.w[j-2]).wrapping_add(self.w[j-7]).wrapping_add(HASH512::theta0(self.w[j-15])).wrapping_add(self.w[j-16]); 94 | } 95 | let mut a=self.h[0]; let mut b=self.h[1]; let mut c=self.h[2]; let mut d=self.h[3]; 96 | let mut e=self.h[4]; let mut f=self.h[5]; let mut g=self.h[6]; let mut hh=self.h[7]; 97 | for j in 0..80 { /* 64 times - mush it up */ 98 | let t1=hh.wrapping_add(HASH512::sig1(e)).wrapping_add(HASH512::ch(e,f,g)).wrapping_add(HASH512_K[j]).wrapping_add(self.w[j]); 99 | let t2=HASH512::sig0(a).wrapping_add(HASH512::maj(a,b,c)); 100 | hh=g; g=f; f=e; 101 | e=d.wrapping_add(t1); 102 | d=c; 103 | c=b; 104 | b=a; 105 | a=t1.wrapping_add(t2) ; 106 | } 107 | self.h[0]=self.h[0].wrapping_add(a); self.h[1]=self.h[1].wrapping_add(b); self.h[2]=self.h[2].wrapping_add(c); self.h[3]=self.h[3].wrapping_add(d); 108 | self.h[4]=self.h[4].wrapping_add(e); self.h[5]=self.h[5].wrapping_add(f); self.h[6]=self.h[6].wrapping_add(g); self.h[7]=self.h[7].wrapping_add(hh); 109 | 110 | } 111 | 112 | /* Initialise Hash function */ 113 | pub fn init(&mut self) { /* initialise */ 114 | for i in 0..64 {self.w[i]=0} 115 | self.length[0]=0; self.length[1]=0; 116 | self.h[0]=HASH512_H0; 117 | self.h[1]=HASH512_H1; 118 | self.h[2]=HASH512_H2; 119 | self.h[3]=HASH512_H3; 120 | self.h[4]=HASH512_H4; 121 | self.h[5]=HASH512_H5; 122 | self.h[6]=HASH512_H6; 123 | self.h[7]=HASH512_H7; 124 | } 125 | 126 | pub fn new() -> HASH512 { 127 | let mut nh=HASH512 { 128 | length: [0;2], 129 | h: [0;8], 130 | w: [0;80] 131 | }; 132 | nh.init(); 133 | return nh; 134 | } 135 | 136 | /* process a single byte */ 137 | pub fn process(&mut self,byt: u8) { /* process the next message byte */ 138 | let cnt=((self.length[0]/64)%16) as usize; 139 | self.w[cnt]<<=8; 140 | self.w[cnt]|=(byt&0xFF) as u64; 141 | self.length[0]+=8; 142 | if self.length[0]==0 {self.length[1]+=1; self.length[0]=0} 143 | if (self.length[0]%1024)==0 {self.transform()} 144 | } 145 | 146 | /* process an array of bytes */ 147 | pub fn process_array(&mut self,b: &[u8]) { 148 | for i in 0..b.len() {self.process(b[i])} 149 | } 150 | 151 | /* process a 32-bit integer */ 152 | pub fn process_num(&mut self,n: i32) { 153 | self.process(((n>>24)&0xff) as u8); 154 | self.process(((n>>16)&0xff) as u8); 155 | self.process(((n>>8)&0xff) as u8); 156 | self.process((n&0xff) as u8); 157 | } 158 | 159 | /* Generate 32-byte Hash */ 160 | pub fn hash(&mut self) -> [u8;64] { /* pad message and finish - supply digest */ 161 | let mut digest:[u8;64]=[0;64]; 162 | let len0=self.length[0]; 163 | let len1=self.length[1]; 164 | self.process(0x80); 165 | while (self.length[0]%1024)!=896 {self.process(0)} 166 | self.w[14]=len1; 167 | self.w[15]=len0; 168 | self.transform(); 169 | for i in 0..64 { /* convert to bytes */ 170 | digest[i]=((self.h[i/8]>>(8*(7-i%8))) & 0xff) as u8; 171 | } 172 | self.init(); 173 | return digest; 174 | } 175 | } 176 | 177 | //8e959b75dae313da 8cf4f72814fc143f 8f7779c6eb9f7fa1 7299aeadb6889018 501d289e4900f7e4 331b99dec4b5433a c7d329eeb6dd2654 5e96e55b874be909 178 | /* 179 | fn main() { 180 | let s = String::from("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); 181 | let test = s.into_bytes(); 182 | let mut sh=HASH512::new(); 183 | 184 | for i in 0..test.len(){ 185 | sh.process(test[i]); 186 | } 187 | 188 | let digest=sh.hash(); 189 | for i in 0..64 {print!("{:02x}",digest[i])} 190 | } */ 191 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/sha3.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | 21 | pub const HASH224: usize=28; 22 | pub const HASH256: usize=32; 23 | pub const HASH384: usize=48; 24 | pub const HASH512: usize=64; 25 | pub const SHAKE128: usize=16; 26 | pub const SHAKE256: usize=32; 27 | 28 | const ROUNDS: usize=24; 29 | 30 | const RC : [u64;24] = [ 31 | 0x0000000000000001,0x0000000000008082,0x800000000000808A,0x8000000080008000, 32 | 0x000000000000808B,0x0000000080000001,0x8000000080008081,0x8000000000008009, 33 | 0x000000000000008A,0x0000000000000088,0x0000000080008009,0x000000008000000A, 34 | 0x000000008000808B,0x800000000000008B,0x8000000000008089,0x8000000000008003, 35 | 0x8000000000008002,0x8000000000000080,0x000000000000800A,0x800000008000000A, 36 | 0x8000000080008081,0x8000000000008080,0x0000000080000001,0x8000000080008008]; 37 | 38 | 39 | 40 | pub struct SHA3 { 41 | length: u64, 42 | rate: usize, 43 | len: usize, 44 | s: [[u64;5];5] 45 | } 46 | 47 | impl SHA3 { 48 | fn rotl(x: u64,n: u64) -> u64 { 49 | return ((x)<>(64-n)); 50 | } 51 | 52 | fn transform(&mut self) { /* basic transformation step */ 53 | let mut c: [u64; 5] = [0; 5]; 54 | let mut d: [u64; 5] = [0; 5]; 55 | let mut b: [[u64;5];5]=[[0;5];5]; 56 | 57 | for k in 0..ROUNDS { 58 | c[0]=self.s[0][0]^self.s[0][1]^self.s[0][2]^self.s[0][3]^self.s[0][4]; 59 | c[1]=self.s[1][0]^self.s[1][1]^self.s[1][2]^self.s[1][3]^self.s[1][4]; 60 | c[2]=self.s[2][0]^self.s[2][1]^self.s[2][2]^self.s[2][3]^self.s[2][4]; 61 | c[3]=self.s[3][0]^self.s[3][1]^self.s[3][2]^self.s[3][3]^self.s[3][4]; 62 | c[4]=self.s[4][0]^self.s[4][1]^self.s[4][2]^self.s[4][3]^self.s[4][4]; 63 | 64 | d[0]=c[4]^SHA3::rotl(c[1],1); 65 | d[1]=c[0]^SHA3::rotl(c[2],1); 66 | d[2]=c[1]^SHA3::rotl(c[3],1); 67 | d[3]=c[2]^SHA3::rotl(c[4],1); 68 | d[4]=c[3]^SHA3::rotl(c[0],1); 69 | 70 | for i in 0..5 { 71 | for j in 0..5 { 72 | self.s[i][j]^=d[i]; 73 | } 74 | } 75 | 76 | b[0][0]=self.s[0][0]; 77 | b[1][3]=SHA3::rotl(self.s[0][1],36); 78 | b[2][1]=SHA3::rotl(self.s[0][2],3); 79 | b[3][4]=SHA3::rotl(self.s[0][3],41); 80 | b[4][2]=SHA3::rotl(self.s[0][4],18); 81 | 82 | b[0][2]=SHA3::rotl(self.s[1][0],1); 83 | b[1][0]=SHA3::rotl(self.s[1][1],44); 84 | b[2][3]=SHA3::rotl(self.s[1][2],10); 85 | b[3][1]=SHA3::rotl(self.s[1][3],45); 86 | b[4][4]=SHA3::rotl(self.s[1][4],2); 87 | 88 | b[0][4]=SHA3::rotl(self.s[2][0],62); 89 | b[1][2]=SHA3::rotl(self.s[2][1],6); 90 | b[2][0]=SHA3::rotl(self.s[2][2],43); 91 | b[3][3]=SHA3::rotl(self.s[2][3],15); 92 | b[4][1]=SHA3::rotl(self.s[2][4],61); 93 | 94 | b[0][1]=SHA3::rotl(self.s[3][0],28); 95 | b[1][4]=SHA3::rotl(self.s[3][1],55); 96 | b[2][2]=SHA3::rotl(self.s[3][2],25); 97 | b[3][0]=SHA3::rotl(self.s[3][3],21); 98 | b[4][3]=SHA3::rotl(self.s[3][4],56); 99 | 100 | b[0][3]=SHA3::rotl(self.s[4][0],27); 101 | b[1][1]=SHA3::rotl(self.s[4][1],20); 102 | b[2][4]=SHA3::rotl(self.s[4][2],39); 103 | b[3][2]=SHA3::rotl(self.s[4][3],8); 104 | b[4][0]=SHA3::rotl(self.s[4][4],14); 105 | 106 | for i in 0..5 { 107 | for j in 0..5 { 108 | self.s[i][j]=b[i][j]^(!b[(i+1)%5][j]&b[(i+2)%5][j]); 109 | } 110 | } 111 | 112 | self.s[0][0]^=RC[k]; 113 | } 114 | } 115 | 116 | /* Initialise Hash function */ 117 | pub fn init(&mut self,olen: usize) { /* initialise */ 118 | for i in 0..5 { 119 | for j in 0..5 { 120 | self.s[i][j]=0; 121 | } 122 | } 123 | self.length=0; 124 | self.len=olen; 125 | self.rate=200-2*olen; 126 | } 127 | 128 | pub fn new(olen: usize) -> SHA3 { 129 | let mut nh=SHA3 { 130 | length: 0, 131 | rate: 0, 132 | len: 0, 133 | s: [[0;5];5] 134 | }; 135 | nh.init(olen); 136 | return nh; 137 | } 138 | 139 | /* process a single byte */ 140 | pub fn process(&mut self,byt: u8) { /* process the next message byte */ 141 | let cnt=(self.length%(self.rate as u64)) as usize; 142 | let b=cnt%8; 143 | let ind=cnt/8; 144 | let i=ind%5; 145 | let j=ind/5; 146 | self.s[i][j]^=((byt&0xff) as u64) << (8*b); 147 | self.length+=1; 148 | if cnt+1 == self.rate { 149 | self.transform(); 150 | } 151 | } 152 | 153 | pub fn squeeze(&mut self,buff: &mut [u8],olen: usize) { 154 | //let olen=buff.len(); 155 | let mut done=false; 156 | let mut m=0; 157 | loop { 158 | for j in 0..5 { 159 | for i in 0..5 { 160 | let mut el=self.s[i][j]; 161 | for _ in 0..8 { 162 | buff[m]=(el&0xff) as u8; 163 | m+=1; 164 | if m>=olen || (m%self.rate)==0 { 165 | done=true; 166 | break; 167 | } 168 | el>>=8; 169 | } 170 | if done {break} 171 | } 172 | if done {break} 173 | } 174 | if m>=olen {break} 175 | done=false; 176 | self.transform(); 177 | } 178 | 179 | } 180 | 181 | /* Generate 32-byte Hash */ 182 | pub fn hash(&mut self,digest: &mut [u8]) { /* pad message and finish - supply digest */ 183 | let q=self.rate-(self.length%(self.rate as u64)) as usize; 184 | if q==1 { 185 | self.process(0x86); 186 | } else { 187 | self.process(0x06); 188 | while (self.length%(self.rate as u64)) as usize != self.rate-1 {self.process(0x00)} 189 | self.process(0x80); 190 | } 191 | let hlen=self.len as usize; 192 | self.squeeze(digest,hlen); 193 | } 194 | 195 | pub fn shake(&mut self,digest: &mut[u8],olen: usize) { 196 | let q=self.rate-(self.length%(self.rate as u64)) as usize; 197 | if q==1 { 198 | self.process(0x9f); 199 | } else { 200 | self.process(0x1f); 201 | while (self.length%(self.rate as u64)) as usize != self.rate-1 {self.process(0x00)} 202 | self.process(0x80); 203 | } 204 | self.squeeze(digest,olen); 205 | } 206 | 207 | } 208 | 209 | //916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18 210 | //afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185 211 | //98be04516c04cc73593fef3ed0352ea9f6443942d6950e29a372a681c3deaf4535423709b02843948684e029010badcc0acd8303fc85fdad3eabf4f78cae165635f57afd28810fc2 212 | /* 213 | fn main() { 214 | let s = String::from("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); 215 | let mut digest: [u8;100]=[0;100]; 216 | let test = s.into_bytes(); 217 | 218 | let mut sh=SHA3::new(HASH256); 219 | for i in 0..test.len(){ 220 | sh.process(test[i]); 221 | } 222 | sh.hash(&mut digest); 223 | for i in 0..32 {print!("{:02x}",digest[i])} 224 | println!(""); 225 | 226 | sh=SHA3::new(HASH512); 227 | for i in 0..test.len(){ 228 | sh.process(test[i]); 229 | } 230 | sh.hash(&mut digest); 231 | for i in 0..64 {print!("{:02x}",digest[i])} 232 | println!(""); 233 | 234 | sh=SHA3::new(SHAKE256); 235 | for i in 0..test.len(){ 236 | sh.process(test[i]); 237 | } 238 | sh.shake(&mut digest,72); 239 | for i in 0..72 {print!("{:02x}",digest[i])} 240 | println!(""); 241 | 242 | } */ 243 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/bn254/dbig.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use arch; 21 | use bn254::big; 22 | use bn254::big::BIG; 23 | use arch::Chunk; 24 | 25 | //#[derive(Copy, Clone)] 26 | pub struct DBIG { 27 | pub w: [Chunk; big::DNLEN] 28 | } 29 | 30 | impl DBIG { 31 | pub fn new() -> DBIG { 32 | DBIG { 33 | w: [0; big::DNLEN as usize] 34 | } 35 | } 36 | 37 | pub fn new_copy(y:&DBIG) -> DBIG { 38 | let mut s= DBIG::new(); 39 | for i in 0..big::DNLEN {s.w[i]=y.w[i]} 40 | return s; 41 | } 42 | 43 | pub fn new_scopy(x:&BIG) -> DBIG { 44 | let mut b= DBIG::new(); 45 | for i in 0 ..big::NLEN { 46 | b.w[i]=x.w[i]; 47 | } 48 | b.w[big::NLEN-1]=x.get(big::NLEN-1)&big::BMASK; /* top word normalized */ 49 | b.w[big::NLEN]=x.get(big::NLEN-1)>>big::BASEBITS; 50 | 51 | for i in big::NLEN+1 ..big::DNLEN {b.w[i]=0} 52 | return b; 53 | } 54 | 55 | /* split DBIG at position n, return higher half, keep lower half */ 56 | pub fn split(&mut self,n: usize) -> BIG 57 | { 58 | let mut t=BIG::new(); 59 | let m=n%big::BASEBITS; 60 | let mut carry=self.w[big::DNLEN-1]<<(big::BASEBITS-m); 61 | 62 | for i in (big::NLEN-1..big::DNLEN-1).rev() { 63 | let nw=(self.w[i]>>m)|carry; 64 | carry= (self.w[i]<<(big::BASEBITS-m))&big::BMASK; 65 | t.set(i+1-big::NLEN,nw); 66 | } 67 | self.w[big::NLEN-1]&=((1 as Chunk)<>(big::BASEBITS-n)); 77 | for i in (m+1..big::DNLEN-1).rev() { 78 | self.w[i]=((self.w[i-m]<>(big::BASEBITS-n)); 79 | } 80 | 81 | self.w[m]=(self.w[0]<>n)|((self.w[m+i+1]<<(big::BASEBITS-n))&big::BMASK); 91 | } 92 | self.w[big::DNLEN-m-1]=self.w[big::DNLEN-1]>>n; 93 | for i in big::DNLEN - m ..big::DNLEN {self.w[i]=0} 94 | } 95 | 96 | /* Copy from another DBIG */ 97 | pub fn copy(&mut self,x: &DBIG) { 98 | for i in 0 ..big::DNLEN { 99 | self.w[i]=x.w[i]; 100 | } 101 | } 102 | 103 | pub fn ucopy(&mut self,x: &BIG) { 104 | for i in 0 ..big::NLEN { 105 | self.w[i]=0; 106 | } 107 | for i in big::NLEN ..big::DNLEN { 108 | self.w[i]=x.w[i-big::NLEN]; 109 | } 110 | } 111 | 112 | pub fn cmove(&mut self,g:&DBIG,d: isize) { 113 | let b=-d as Chunk; 114 | for i in 0 ..big::DNLEN { 115 | self.w[i]^=(self.w[i]^g.w[i])&b; 116 | } 117 | } 118 | 119 | /* self+=x */ 120 | pub fn add(&mut self,x:&DBIG) { 121 | for i in 0 ..big::DNLEN { 122 | self.w[i]+=x.w[i]; 123 | } 124 | } 125 | 126 | /* self-=x */ 127 | pub fn sub(&mut self,x:&DBIG) { 128 | for i in 0 ..big::DNLEN { 129 | self.w[i]-=x.w[i]; 130 | } 131 | } 132 | 133 | /* self=x-self */ 134 | pub fn rsub(&mut self,x:&DBIG) { 135 | for i in 0 ..big::DNLEN { 136 | self.w[i]=x.w[i]-self.w[i]; 137 | } 138 | } 139 | 140 | 141 | /* Compare a and b, return 0 if a==b, -1 if ab. Inputs must be normalised */ 142 | pub fn comp(a: &DBIG,b: &DBIG) -> isize { 143 | for i in (0 ..big::DNLEN).rev() { 144 | if a.w[i]==b.w[i] {continue} 145 | if a.w[i]>b.w[i] {return 1} 146 | else {return -1} 147 | } 148 | return 0; 149 | } 150 | 151 | /* normalise BIG - force all digits < 2^big::BASEBITS */ 152 | pub fn norm(&mut self) { 153 | let mut carry=0 as Chunk; 154 | for i in 0 ..big::DNLEN-1 { 155 | let d=self.w[i]+carry; 156 | self.w[i]=d&big::BMASK; 157 | carry=d>>big::BASEBITS; 158 | } 159 | self.w[big::DNLEN-1]+=carry 160 | } 161 | 162 | /* reduces self DBIG mod a BIG, and returns the BIG */ 163 | pub fn dmod(&mut self,c: &BIG) -> BIG { 164 | let mut k=0; 165 | self.norm(); 166 | let mut m=DBIG::new_scopy(c); 167 | let mut dr=DBIG::new(); 168 | 169 | if DBIG::comp(self,&m)<0 { 170 | let r=BIG::new_dcopy(self); 171 | return r; 172 | } 173 | 174 | loop { 175 | m.shl(1); 176 | k += 1; 177 | if DBIG::comp(self,&m)<0 {break;} 178 | } 179 | 180 | while k>0 { 181 | m.shr(1); 182 | 183 | dr.copy(self); 184 | dr.sub(&m); 185 | dr.norm(); 186 | self.cmove(&dr,(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize); 187 | /* 188 | if DBIG::comp(self,&m)>=0 { 189 | self.sub(&m); 190 | self.norm(); 191 | } */ 192 | k -= 1; 193 | } 194 | let r=BIG::new_dcopy(self); 195 | return r; 196 | } 197 | 198 | /* return this/c */ 199 | pub fn div(&mut self,c: &BIG) -> BIG { 200 | let mut k=0; 201 | let mut m=DBIG::new_scopy(c); 202 | let mut a=BIG::new(); 203 | let mut e=BIG::new_int(1); 204 | let mut dr=DBIG::new(); 205 | let mut r=BIG::new(); 206 | self.norm(); 207 | 208 | while DBIG::comp(self,&m)>=0 { 209 | e.fshl(1); 210 | m.shl(1); 211 | k+=1; 212 | } 213 | 214 | while k>0 { 215 | m.shr(1); 216 | e.shr(1); 217 | 218 | dr.copy(self); 219 | dr.sub(&m); 220 | dr.norm(); 221 | let d=(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize; 222 | self.cmove(&dr,d); 223 | r.copy(&a); 224 | r.add(&e); 225 | r.norm(); 226 | a.cmove(&r,d); 227 | /* 228 | if DBIG::comp(self,&m)>0 { 229 | a.add(&e); 230 | a.norm(); 231 | self.sub(&m); 232 | self.norm(); 233 | } */ 234 | k-=1; 235 | } 236 | return a; 237 | } 238 | 239 | /* return number of bits */ 240 | pub fn nbits(&mut self) -> usize { 241 | let mut k=big::DNLEN-1; 242 | self.norm(); 243 | while (k as isize)>=0 && self.w[k]==0 {k=k.wrapping_sub(1)} 244 | if (k as isize) <0 {return 0} 245 | let mut bts=(big::BASEBITS as usize)*k; 246 | let mut c=self.w[k]; 247 | while c!=0 {c/=2; bts+=1;} 248 | return bts; 249 | } 250 | 251 | /* Convert to Hex String */ 252 | pub fn to_string(&mut self) -> String { 253 | let mut s = String::new(); 254 | let mut len=self.nbits(); 255 | 256 | if len%4==0 { 257 | len/=4; 258 | } else { 259 | len/=4; 260 | len+=1; 261 | } 262 | 263 | for i in (0 ..len).rev() { 264 | let mut b=DBIG::new_copy(&self); 265 | b.shr(i*4); 266 | s=s + &format!("{:X}", b.w[0]&15); 267 | } 268 | return s; 269 | } 270 | 271 | } 272 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/bls381/dbig.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use arch; 21 | use bls381::big; 22 | use bls381::big::BIG; 23 | use arch::Chunk; 24 | 25 | //#[derive(Copy, Clone)] 26 | pub struct DBIG { 27 | pub w: [Chunk; big::DNLEN] 28 | } 29 | 30 | impl DBIG { 31 | pub fn new() -> DBIG { 32 | DBIG { 33 | w: [0; big::DNLEN as usize] 34 | } 35 | } 36 | 37 | pub fn new_copy(y:&DBIG) -> DBIG { 38 | let mut s= DBIG::new(); 39 | for i in 0..big::DNLEN {s.w[i]=y.w[i]} 40 | return s; 41 | } 42 | 43 | pub fn new_scopy(x:&BIG) -> DBIG { 44 | let mut b= DBIG::new(); 45 | for i in 0 ..big::NLEN { 46 | b.w[i]=x.w[i]; 47 | } 48 | b.w[big::NLEN-1]=x.get(big::NLEN-1)&big::BMASK; /* top word normalized */ 49 | b.w[big::NLEN]=x.get(big::NLEN-1)>>big::BASEBITS; 50 | 51 | for i in big::NLEN+1 ..big::DNLEN {b.w[i]=0} 52 | return b; 53 | } 54 | 55 | /* split DBIG at position n, return higher half, keep lower half */ 56 | pub fn split(&mut self,n: usize) -> BIG 57 | { 58 | let mut t=BIG::new(); 59 | let m=n%big::BASEBITS; 60 | let mut carry=self.w[big::DNLEN-1]<<(big::BASEBITS-m); 61 | 62 | for i in (big::NLEN-1..big::DNLEN-1).rev() { 63 | let nw=(self.w[i]>>m)|carry; 64 | carry= (self.w[i]<<(big::BASEBITS-m))&big::BMASK; 65 | t.set(i+1-big::NLEN,nw); 66 | } 67 | self.w[big::NLEN-1]&=((1 as Chunk)<>(big::BASEBITS-n)); 77 | for i in (m+1..big::DNLEN-1).rev() { 78 | self.w[i]=((self.w[i-m]<>(big::BASEBITS-n)); 79 | } 80 | 81 | self.w[m]=(self.w[0]<>n)|((self.w[m+i+1]<<(big::BASEBITS-n))&big::BMASK); 91 | } 92 | self.w[big::DNLEN-m-1]=self.w[big::DNLEN-1]>>n; 93 | for i in big::DNLEN - m ..big::DNLEN {self.w[i]=0} 94 | } 95 | 96 | /* Copy from another DBIG */ 97 | pub fn copy(&mut self,x: &DBIG) { 98 | for i in 0 ..big::DNLEN { 99 | self.w[i]=x.w[i]; 100 | } 101 | } 102 | 103 | pub fn ucopy(&mut self,x: &BIG) { 104 | for i in 0 ..big::NLEN { 105 | self.w[i]=0; 106 | } 107 | for i in big::NLEN ..big::DNLEN { 108 | self.w[i]=x.w[i-big::NLEN]; 109 | } 110 | } 111 | 112 | pub fn cmove(&mut self,g:&DBIG,d: isize) { 113 | let b=-d as Chunk; 114 | for i in 0 ..big::DNLEN { 115 | self.w[i]^=(self.w[i]^g.w[i])&b; 116 | } 117 | } 118 | 119 | /* self+=x */ 120 | pub fn add(&mut self,x:&DBIG) { 121 | for i in 0 ..big::DNLEN { 122 | self.w[i]+=x.w[i]; 123 | } 124 | } 125 | 126 | /* self-=x */ 127 | pub fn sub(&mut self,x:&DBIG) { 128 | for i in 0 ..big::DNLEN { 129 | self.w[i]-=x.w[i]; 130 | } 131 | } 132 | 133 | /* self=x-self */ 134 | pub fn rsub(&mut self,x:&DBIG) { 135 | for i in 0 ..big::DNLEN { 136 | self.w[i]=x.w[i]-self.w[i]; 137 | } 138 | } 139 | 140 | 141 | /* Compare a and b, return 0 if a==b, -1 if ab. Inputs must be normalised */ 142 | pub fn comp(a: &DBIG,b: &DBIG) -> isize { 143 | for i in (0 ..big::DNLEN).rev() { 144 | if a.w[i]==b.w[i] {continue} 145 | if a.w[i]>b.w[i] {return 1} 146 | else {return -1} 147 | } 148 | return 0; 149 | } 150 | 151 | /* normalise BIG - force all digits < 2^big::BASEBITS */ 152 | pub fn norm(&mut self) { 153 | let mut carry=0 as Chunk; 154 | for i in 0 ..big::DNLEN-1 { 155 | let d=self.w[i]+carry; 156 | self.w[i]=d&big::BMASK; 157 | carry=d>>big::BASEBITS; 158 | } 159 | self.w[big::DNLEN-1]+=carry 160 | } 161 | 162 | /* reduces self DBIG mod a BIG, and returns the BIG */ 163 | pub fn dmod(&mut self,c: &BIG) -> BIG { 164 | let mut k=0; 165 | self.norm(); 166 | let mut m=DBIG::new_scopy(c); 167 | let mut dr=DBIG::new(); 168 | 169 | if DBIG::comp(self,&m)<0 { 170 | let r=BIG::new_dcopy(self); 171 | return r; 172 | } 173 | 174 | loop { 175 | m.shl(1); 176 | k += 1; 177 | if DBIG::comp(self,&m)<0 {break;} 178 | } 179 | 180 | while k>0 { 181 | m.shr(1); 182 | 183 | dr.copy(self); 184 | dr.sub(&m); 185 | dr.norm(); 186 | self.cmove(&dr,(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize); 187 | /* 188 | if DBIG::comp(self,&m)>=0 { 189 | self.sub(&m); 190 | self.norm(); 191 | } */ 192 | k -= 1; 193 | } 194 | let r=BIG::new_dcopy(self); 195 | return r; 196 | } 197 | 198 | /* return this/c */ 199 | pub fn div(&mut self,c: &BIG) -> BIG { 200 | let mut k=0; 201 | let mut m=DBIG::new_scopy(c); 202 | let mut a=BIG::new(); 203 | let mut e=BIG::new_int(1); 204 | let mut dr=DBIG::new(); 205 | let mut r=BIG::new(); 206 | self.norm(); 207 | 208 | while DBIG::comp(self,&m)>=0 { 209 | e.fshl(1); 210 | m.shl(1); 211 | k+=1; 212 | } 213 | 214 | while k>0 { 215 | m.shr(1); 216 | e.shr(1); 217 | 218 | dr.copy(self); 219 | dr.sub(&m); 220 | dr.norm(); 221 | let d=(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize; 222 | self.cmove(&dr,d); 223 | r.copy(&a); 224 | r.add(&e); 225 | r.norm(); 226 | a.cmove(&r,d); 227 | /* 228 | if DBIG::comp(self,&m)>0 { 229 | a.add(&e); 230 | a.norm(); 231 | self.sub(&m); 232 | self.norm(); 233 | } */ 234 | k-=1; 235 | } 236 | return a; 237 | } 238 | 239 | /* return number of bits */ 240 | pub fn nbits(&mut self) -> usize { 241 | let mut k=big::DNLEN-1; 242 | self.norm(); 243 | while (k as isize)>=0 && self.w[k]==0 {k=k.wrapping_sub(1)} 244 | if (k as isize) <0 {return 0} 245 | let mut bts=(big::BASEBITS as usize)*k; 246 | let mut c=self.w[k]; 247 | while c!=0 {c/=2; bts+=1;} 248 | return bts; 249 | } 250 | 251 | /* Convert to Hex String */ 252 | pub fn to_string(&mut self) -> String { 253 | let mut s = String::new(); 254 | let mut len=self.nbits(); 255 | 256 | if len%4==0 { 257 | len/=4; 258 | } else { 259 | len/=4; 260 | len+=1; 261 | } 262 | 263 | for i in (0 ..len).rev() { 264 | let mut b=DBIG::new_copy(&self); 265 | b.shr(i*4); 266 | s=s + &format!("{:X}", b.w[0]&15); 267 | } 268 | return s; 269 | } 270 | 271 | } 272 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/bls461/dbig.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use arch; 21 | use bls461::big; 22 | use bls461::big::BIG; 23 | use arch::Chunk; 24 | 25 | //#[derive(Copy, Clone)] 26 | pub struct DBIG { 27 | pub w: [Chunk; big::DNLEN] 28 | } 29 | 30 | impl DBIG { 31 | pub fn new() -> DBIG { 32 | DBIG { 33 | w: [0; big::DNLEN as usize] 34 | } 35 | } 36 | 37 | pub fn new_copy(y:&DBIG) -> DBIG { 38 | let mut s= DBIG::new(); 39 | for i in 0..big::DNLEN {s.w[i]=y.w[i]} 40 | return s; 41 | } 42 | 43 | pub fn new_scopy(x:&BIG) -> DBIG { 44 | let mut b= DBIG::new(); 45 | for i in 0 ..big::NLEN { 46 | b.w[i]=x.w[i]; 47 | } 48 | b.w[big::NLEN-1]=x.get(big::NLEN-1)&big::BMASK; /* top word normalized */ 49 | b.w[big::NLEN]=x.get(big::NLEN-1)>>big::BASEBITS; 50 | 51 | for i in big::NLEN+1 ..big::DNLEN {b.w[i]=0} 52 | return b; 53 | } 54 | 55 | /* split DBIG at position n, return higher half, keep lower half */ 56 | pub fn split(&mut self,n: usize) -> BIG 57 | { 58 | let mut t=BIG::new(); 59 | let m=n%big::BASEBITS; 60 | let mut carry=self.w[big::DNLEN-1]<<(big::BASEBITS-m); 61 | 62 | for i in (big::NLEN-1..big::DNLEN-1).rev() { 63 | let nw=(self.w[i]>>m)|carry; 64 | carry= (self.w[i]<<(big::BASEBITS-m))&big::BMASK; 65 | t.set(i+1-big::NLEN,nw); 66 | } 67 | self.w[big::NLEN-1]&=((1 as Chunk)<>(big::BASEBITS-n)); 77 | for i in (m+1..big::DNLEN-1).rev() { 78 | self.w[i]=((self.w[i-m]<>(big::BASEBITS-n)); 79 | } 80 | 81 | self.w[m]=(self.w[0]<>n)|((self.w[m+i+1]<<(big::BASEBITS-n))&big::BMASK); 91 | } 92 | self.w[big::DNLEN-m-1]=self.w[big::DNLEN-1]>>n; 93 | for i in big::DNLEN - m ..big::DNLEN {self.w[i]=0} 94 | } 95 | 96 | /* Copy from another DBIG */ 97 | pub fn copy(&mut self,x: &DBIG) { 98 | for i in 0 ..big::DNLEN { 99 | self.w[i]=x.w[i]; 100 | } 101 | } 102 | 103 | pub fn ucopy(&mut self,x: &BIG) { 104 | for i in 0 ..big::NLEN { 105 | self.w[i]=0; 106 | } 107 | for i in big::NLEN ..big::DNLEN { 108 | self.w[i]=x.w[i-big::NLEN]; 109 | } 110 | } 111 | 112 | pub fn cmove(&mut self,g:&DBIG,d: isize) { 113 | let b=-d as Chunk; 114 | for i in 0 ..big::DNLEN { 115 | self.w[i]^=(self.w[i]^g.w[i])&b; 116 | } 117 | } 118 | 119 | /* self+=x */ 120 | pub fn add(&mut self,x:&DBIG) { 121 | for i in 0 ..big::DNLEN { 122 | self.w[i]+=x.w[i]; 123 | } 124 | } 125 | 126 | /* self-=x */ 127 | pub fn sub(&mut self,x:&DBIG) { 128 | for i in 0 ..big::DNLEN { 129 | self.w[i]-=x.w[i]; 130 | } 131 | } 132 | 133 | /* self=x-self */ 134 | pub fn rsub(&mut self,x:&DBIG) { 135 | for i in 0 ..big::DNLEN { 136 | self.w[i]=x.w[i]-self.w[i]; 137 | } 138 | } 139 | 140 | 141 | /* Compare a and b, return 0 if a==b, -1 if ab. Inputs must be normalised */ 142 | pub fn comp(a: &DBIG,b: &DBIG) -> isize { 143 | for i in (0 ..big::DNLEN).rev() { 144 | if a.w[i]==b.w[i] {continue} 145 | if a.w[i]>b.w[i] {return 1} 146 | else {return -1} 147 | } 148 | return 0; 149 | } 150 | 151 | /* normalise BIG - force all digits < 2^big::BASEBITS */ 152 | pub fn norm(&mut self) { 153 | let mut carry=0 as Chunk; 154 | for i in 0 ..big::DNLEN-1 { 155 | let d=self.w[i]+carry; 156 | self.w[i]=d&big::BMASK; 157 | carry=d>>big::BASEBITS; 158 | } 159 | self.w[big::DNLEN-1]+=carry 160 | } 161 | 162 | /* reduces self DBIG mod a BIG, and returns the BIG */ 163 | pub fn dmod(&mut self,c: &BIG) -> BIG { 164 | let mut k=0; 165 | self.norm(); 166 | let mut m=DBIG::new_scopy(c); 167 | let mut dr=DBIG::new(); 168 | 169 | if DBIG::comp(self,&m)<0 { 170 | let r=BIG::new_dcopy(self); 171 | return r; 172 | } 173 | 174 | loop { 175 | m.shl(1); 176 | k += 1; 177 | if DBIG::comp(self,&m)<0 {break;} 178 | } 179 | 180 | while k>0 { 181 | m.shr(1); 182 | 183 | dr.copy(self); 184 | dr.sub(&m); 185 | dr.norm(); 186 | self.cmove(&dr,(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize); 187 | /* 188 | if DBIG::comp(self,&m)>=0 { 189 | self.sub(&m); 190 | self.norm(); 191 | } */ 192 | k -= 1; 193 | } 194 | let r=BIG::new_dcopy(self); 195 | return r; 196 | } 197 | 198 | /* return this/c */ 199 | pub fn div(&mut self,c: &BIG) -> BIG { 200 | let mut k=0; 201 | let mut m=DBIG::new_scopy(c); 202 | let mut a=BIG::new(); 203 | let mut e=BIG::new_int(1); 204 | let mut dr=DBIG::new(); 205 | let mut r=BIG::new(); 206 | self.norm(); 207 | 208 | while DBIG::comp(self,&m)>=0 { 209 | e.fshl(1); 210 | m.shl(1); 211 | k+=1; 212 | } 213 | 214 | while k>0 { 215 | m.shr(1); 216 | e.shr(1); 217 | 218 | dr.copy(self); 219 | dr.sub(&m); 220 | dr.norm(); 221 | let d=(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize; 222 | self.cmove(&dr,d); 223 | r.copy(&a); 224 | r.add(&e); 225 | r.norm(); 226 | a.cmove(&r,d); 227 | /* 228 | if DBIG::comp(self,&m)>0 { 229 | a.add(&e); 230 | a.norm(); 231 | self.sub(&m); 232 | self.norm(); 233 | } */ 234 | k-=1; 235 | } 236 | return a; 237 | } 238 | 239 | /* return number of bits */ 240 | pub fn nbits(&mut self) -> usize { 241 | let mut k=big::DNLEN-1; 242 | self.norm(); 243 | while (k as isize)>=0 && self.w[k]==0 {k=k.wrapping_sub(1)} 244 | if (k as isize) <0 {return 0} 245 | let mut bts=(big::BASEBITS as usize)*k; 246 | let mut c=self.w[k]; 247 | while c!=0 {c/=2; bts+=1;} 248 | return bts; 249 | } 250 | 251 | /* Convert to Hex String */ 252 | pub fn to_string(&mut self) -> String { 253 | let mut s = String::new(); 254 | let mut len=self.nbits(); 255 | 256 | if len%4==0 { 257 | len/=4; 258 | } else { 259 | len/=4; 260 | len+=1; 261 | } 262 | 263 | for i in (0 ..len).rev() { 264 | let mut b=DBIG::new_copy(&self); 265 | b.shr(i*4); 266 | s=s + &format!("{:X}", b.w[0]&15); 267 | } 268 | return s; 269 | } 270 | 271 | } 272 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/c41417/dbig.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use arch; 21 | use c41417::big; 22 | use c41417::big::BIG; 23 | use arch::Chunk; 24 | 25 | //#[derive(Copy, Clone)] 26 | pub struct DBIG { 27 | pub w: [Chunk; big::DNLEN] 28 | } 29 | 30 | impl DBIG { 31 | pub fn new() -> DBIG { 32 | DBIG { 33 | w: [0; big::DNLEN as usize] 34 | } 35 | } 36 | 37 | pub fn new_copy(y:&DBIG) -> DBIG { 38 | let mut s= DBIG::new(); 39 | for i in 0..big::DNLEN {s.w[i]=y.w[i]} 40 | return s; 41 | } 42 | 43 | pub fn new_scopy(x:&BIG) -> DBIG { 44 | let mut b= DBIG::new(); 45 | for i in 0 ..big::NLEN { 46 | b.w[i]=x.w[i]; 47 | } 48 | b.w[big::NLEN-1]=x.get(big::NLEN-1)&big::BMASK; /* top word normalized */ 49 | b.w[big::NLEN]=x.get(big::NLEN-1)>>big::BASEBITS; 50 | 51 | for i in big::NLEN+1 ..big::DNLEN {b.w[i]=0} 52 | return b; 53 | } 54 | 55 | /* split DBIG at position n, return higher half, keep lower half */ 56 | pub fn split(&mut self,n: usize) -> BIG 57 | { 58 | let mut t=BIG::new(); 59 | let m=n%big::BASEBITS; 60 | let mut carry=self.w[big::DNLEN-1]<<(big::BASEBITS-m); 61 | 62 | for i in (big::NLEN-1..big::DNLEN-1).rev() { 63 | let nw=(self.w[i]>>m)|carry; 64 | carry= (self.w[i]<<(big::BASEBITS-m))&big::BMASK; 65 | t.set(i+1-big::NLEN,nw); 66 | } 67 | self.w[big::NLEN-1]&=((1 as Chunk)<>(big::BASEBITS-n)); 77 | for i in (m+1..big::DNLEN-1).rev() { 78 | self.w[i]=((self.w[i-m]<>(big::BASEBITS-n)); 79 | } 80 | 81 | self.w[m]=(self.w[0]<>n)|((self.w[m+i+1]<<(big::BASEBITS-n))&big::BMASK); 91 | } 92 | self.w[big::DNLEN-m-1]=self.w[big::DNLEN-1]>>n; 93 | for i in big::DNLEN - m ..big::DNLEN {self.w[i]=0} 94 | } 95 | 96 | /* Copy from another DBIG */ 97 | pub fn copy(&mut self,x: &DBIG) { 98 | for i in 0 ..big::DNLEN { 99 | self.w[i]=x.w[i]; 100 | } 101 | } 102 | 103 | pub fn ucopy(&mut self,x: &BIG) { 104 | for i in 0 ..big::NLEN { 105 | self.w[i]=0; 106 | } 107 | for i in big::NLEN ..big::DNLEN { 108 | self.w[i]=x.w[i-big::NLEN]; 109 | } 110 | } 111 | 112 | pub fn cmove(&mut self,g:&DBIG,d: isize) { 113 | let b=-d as Chunk; 114 | for i in 0 ..big::DNLEN { 115 | self.w[i]^=(self.w[i]^g.w[i])&b; 116 | } 117 | } 118 | 119 | /* self+=x */ 120 | pub fn add(&mut self,x:&DBIG) { 121 | for i in 0 ..big::DNLEN { 122 | self.w[i]+=x.w[i]; 123 | } 124 | } 125 | 126 | /* self-=x */ 127 | pub fn sub(&mut self,x:&DBIG) { 128 | for i in 0 ..big::DNLEN { 129 | self.w[i]-=x.w[i]; 130 | } 131 | } 132 | 133 | /* self=x-self */ 134 | pub fn rsub(&mut self,x:&DBIG) { 135 | for i in 0 ..big::DNLEN { 136 | self.w[i]=x.w[i]-self.w[i]; 137 | } 138 | } 139 | 140 | 141 | /* Compare a and b, return 0 if a==b, -1 if ab. Inputs must be normalised */ 142 | pub fn comp(a: &DBIG,b: &DBIG) -> isize { 143 | for i in (0 ..big::DNLEN).rev() { 144 | if a.w[i]==b.w[i] {continue} 145 | if a.w[i]>b.w[i] {return 1} 146 | else {return -1} 147 | } 148 | return 0; 149 | } 150 | 151 | /* normalise BIG - force all digits < 2^big::BASEBITS */ 152 | pub fn norm(&mut self) { 153 | let mut carry=0 as Chunk; 154 | for i in 0 ..big::DNLEN-1 { 155 | let d=self.w[i]+carry; 156 | self.w[i]=d&big::BMASK; 157 | carry=d>>big::BASEBITS; 158 | } 159 | self.w[big::DNLEN-1]+=carry 160 | } 161 | 162 | /* reduces self DBIG mod a BIG, and returns the BIG */ 163 | pub fn dmod(&mut self,c: &BIG) -> BIG { 164 | let mut k=0; 165 | self.norm(); 166 | let mut m=DBIG::new_scopy(c); 167 | let mut dr=DBIG::new(); 168 | 169 | if DBIG::comp(self,&m)<0 { 170 | let r=BIG::new_dcopy(self); 171 | return r; 172 | } 173 | 174 | loop { 175 | m.shl(1); 176 | k += 1; 177 | if DBIG::comp(self,&m)<0 {break;} 178 | } 179 | 180 | while k>0 { 181 | m.shr(1); 182 | 183 | dr.copy(self); 184 | dr.sub(&m); 185 | dr.norm(); 186 | self.cmove(&dr,(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize); 187 | /* 188 | if DBIG::comp(self,&m)>=0 { 189 | self.sub(&m); 190 | self.norm(); 191 | } */ 192 | k -= 1; 193 | } 194 | let r=BIG::new_dcopy(self); 195 | return r; 196 | } 197 | 198 | /* return this/c */ 199 | pub fn div(&mut self,c: &BIG) -> BIG { 200 | let mut k=0; 201 | let mut m=DBIG::new_scopy(c); 202 | let mut a=BIG::new(); 203 | let mut e=BIG::new_int(1); 204 | let mut dr=DBIG::new(); 205 | let mut r=BIG::new(); 206 | self.norm(); 207 | 208 | while DBIG::comp(self,&m)>=0 { 209 | e.fshl(1); 210 | m.shl(1); 211 | k+=1; 212 | } 213 | 214 | while k>0 { 215 | m.shr(1); 216 | e.shr(1); 217 | 218 | dr.copy(self); 219 | dr.sub(&m); 220 | dr.norm(); 221 | let d=(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize; 222 | self.cmove(&dr,d); 223 | r.copy(&a); 224 | r.add(&e); 225 | r.norm(); 226 | a.cmove(&r,d); 227 | /* 228 | if DBIG::comp(self,&m)>0 { 229 | a.add(&e); 230 | a.norm(); 231 | self.sub(&m); 232 | self.norm(); 233 | } */ 234 | k-=1; 235 | } 236 | return a; 237 | } 238 | 239 | /* return number of bits */ 240 | pub fn nbits(&mut self) -> usize { 241 | let mut k=big::DNLEN-1; 242 | self.norm(); 243 | while (k as isize)>=0 && self.w[k]==0 {k=k.wrapping_sub(1)} 244 | if (k as isize) <0 {return 0} 245 | let mut bts=(big::BASEBITS as usize)*k; 246 | let mut c=self.w[k]; 247 | while c!=0 {c/=2; bts+=1;} 248 | return bts; 249 | } 250 | 251 | /* Convert to Hex String */ 252 | pub fn to_string(&mut self) -> String { 253 | let mut s = String::new(); 254 | let mut len=self.nbits(); 255 | 256 | if len%4==0 { 257 | len/=4; 258 | } else { 259 | len/=4; 260 | len+=1; 261 | } 262 | 263 | for i in (0 ..len).rev() { 264 | let mut b=DBIG::new_copy(&self); 265 | b.shr(i*4); 266 | s=s + &format!("{:X}", b.w[0]&15); 267 | } 268 | return s; 269 | } 270 | 271 | } 272 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/nist256/dbig.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use arch; 21 | use nist256::big; 22 | use nist256::big::BIG; 23 | use arch::Chunk; 24 | 25 | //#[derive(Copy, Clone)] 26 | pub struct DBIG { 27 | pub w: [Chunk; big::DNLEN] 28 | } 29 | 30 | impl DBIG { 31 | pub fn new() -> DBIG { 32 | DBIG { 33 | w: [0; big::DNLEN as usize] 34 | } 35 | } 36 | 37 | pub fn new_copy(y:&DBIG) -> DBIG { 38 | let mut s= DBIG::new(); 39 | for i in 0..big::DNLEN {s.w[i]=y.w[i]} 40 | return s; 41 | } 42 | 43 | pub fn new_scopy(x:&BIG) -> DBIG { 44 | let mut b= DBIG::new(); 45 | for i in 0 ..big::NLEN { 46 | b.w[i]=x.w[i]; 47 | } 48 | b.w[big::NLEN-1]=x.get(big::NLEN-1)&big::BMASK; /* top word normalized */ 49 | b.w[big::NLEN]=x.get(big::NLEN-1)>>big::BASEBITS; 50 | 51 | for i in big::NLEN+1 ..big::DNLEN {b.w[i]=0} 52 | return b; 53 | } 54 | 55 | /* split DBIG at position n, return higher half, keep lower half */ 56 | pub fn split(&mut self,n: usize) -> BIG 57 | { 58 | let mut t=BIG::new(); 59 | let m=n%big::BASEBITS; 60 | let mut carry=self.w[big::DNLEN-1]<<(big::BASEBITS-m); 61 | 62 | for i in (big::NLEN-1..big::DNLEN-1).rev() { 63 | let nw=(self.w[i]>>m)|carry; 64 | carry= (self.w[i]<<(big::BASEBITS-m))&big::BMASK; 65 | t.set(i+1-big::NLEN,nw); 66 | } 67 | self.w[big::NLEN-1]&=((1 as Chunk)<>(big::BASEBITS-n)); 77 | for i in (m+1..big::DNLEN-1).rev() { 78 | self.w[i]=((self.w[i-m]<>(big::BASEBITS-n)); 79 | } 80 | 81 | self.w[m]=(self.w[0]<>n)|((self.w[m+i+1]<<(big::BASEBITS-n))&big::BMASK); 91 | } 92 | self.w[big::DNLEN-m-1]=self.w[big::DNLEN-1]>>n; 93 | for i in big::DNLEN - m ..big::DNLEN {self.w[i]=0} 94 | } 95 | 96 | /* Copy from another DBIG */ 97 | pub fn copy(&mut self,x: &DBIG) { 98 | for i in 0 ..big::DNLEN { 99 | self.w[i]=x.w[i]; 100 | } 101 | } 102 | 103 | pub fn ucopy(&mut self,x: &BIG) { 104 | for i in 0 ..big::NLEN { 105 | self.w[i]=0; 106 | } 107 | for i in big::NLEN ..big::DNLEN { 108 | self.w[i]=x.w[i-big::NLEN]; 109 | } 110 | } 111 | 112 | pub fn cmove(&mut self,g:&DBIG,d: isize) { 113 | let b=-d as Chunk; 114 | for i in 0 ..big::DNLEN { 115 | self.w[i]^=(self.w[i]^g.w[i])&b; 116 | } 117 | } 118 | 119 | /* self+=x */ 120 | pub fn add(&mut self,x:&DBIG) { 121 | for i in 0 ..big::DNLEN { 122 | self.w[i]+=x.w[i]; 123 | } 124 | } 125 | 126 | /* self-=x */ 127 | pub fn sub(&mut self,x:&DBIG) { 128 | for i in 0 ..big::DNLEN { 129 | self.w[i]-=x.w[i]; 130 | } 131 | } 132 | 133 | /* self=x-self */ 134 | pub fn rsub(&mut self,x:&DBIG) { 135 | for i in 0 ..big::DNLEN { 136 | self.w[i]=x.w[i]-self.w[i]; 137 | } 138 | } 139 | 140 | 141 | /* Compare a and b, return 0 if a==b, -1 if ab. Inputs must be normalised */ 142 | pub fn comp(a: &DBIG,b: &DBIG) -> isize { 143 | for i in (0 ..big::DNLEN).rev() { 144 | if a.w[i]==b.w[i] {continue} 145 | if a.w[i]>b.w[i] {return 1} 146 | else {return -1} 147 | } 148 | return 0; 149 | } 150 | 151 | /* normalise BIG - force all digits < 2^big::BASEBITS */ 152 | pub fn norm(&mut self) { 153 | let mut carry=0 as Chunk; 154 | for i in 0 ..big::DNLEN-1 { 155 | let d=self.w[i]+carry; 156 | self.w[i]=d&big::BMASK; 157 | carry=d>>big::BASEBITS; 158 | } 159 | self.w[big::DNLEN-1]+=carry 160 | } 161 | 162 | /* reduces self DBIG mod a BIG, and returns the BIG */ 163 | pub fn dmod(&mut self,c: &BIG) -> BIG { 164 | let mut k=0; 165 | self.norm(); 166 | let mut m=DBIG::new_scopy(c); 167 | let mut dr=DBIG::new(); 168 | 169 | if DBIG::comp(self,&m)<0 { 170 | let r=BIG::new_dcopy(self); 171 | return r; 172 | } 173 | 174 | loop { 175 | m.shl(1); 176 | k += 1; 177 | if DBIG::comp(self,&m)<0 {break;} 178 | } 179 | 180 | while k>0 { 181 | m.shr(1); 182 | 183 | dr.copy(self); 184 | dr.sub(&m); 185 | dr.norm(); 186 | self.cmove(&dr,(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize); 187 | /* 188 | if DBIG::comp(self,&m)>=0 { 189 | self.sub(&m); 190 | self.norm(); 191 | } */ 192 | k -= 1; 193 | } 194 | let r=BIG::new_dcopy(self); 195 | return r; 196 | } 197 | 198 | /* return this/c */ 199 | pub fn div(&mut self,c: &BIG) -> BIG { 200 | let mut k=0; 201 | let mut m=DBIG::new_scopy(c); 202 | let mut a=BIG::new(); 203 | let mut e=BIG::new_int(1); 204 | let mut dr=DBIG::new(); 205 | let mut r=BIG::new(); 206 | self.norm(); 207 | 208 | while DBIG::comp(self,&m)>=0 { 209 | e.fshl(1); 210 | m.shl(1); 211 | k+=1; 212 | } 213 | 214 | while k>0 { 215 | m.shr(1); 216 | e.shr(1); 217 | 218 | dr.copy(self); 219 | dr.sub(&m); 220 | dr.norm(); 221 | let d=(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize; 222 | self.cmove(&dr,d); 223 | r.copy(&a); 224 | r.add(&e); 225 | r.norm(); 226 | a.cmove(&r,d); 227 | /* 228 | if DBIG::comp(self,&m)>0 { 229 | a.add(&e); 230 | a.norm(); 231 | self.sub(&m); 232 | self.norm(); 233 | } */ 234 | k-=1; 235 | } 236 | return a; 237 | } 238 | 239 | /* return number of bits */ 240 | pub fn nbits(&mut self) -> usize { 241 | let mut k=big::DNLEN-1; 242 | self.norm(); 243 | while (k as isize)>=0 && self.w[k]==0 {k=k.wrapping_sub(1)} 244 | if (k as isize) <0 {return 0} 245 | let mut bts=(big::BASEBITS as usize)*k; 246 | let mut c=self.w[k]; 247 | while c!=0 {c/=2; bts+=1;} 248 | return bts; 249 | } 250 | 251 | /* Convert to Hex String */ 252 | pub fn to_string(&mut self) -> String { 253 | let mut s = String::new(); 254 | let mut len=self.nbits(); 255 | 256 | if len%4==0 { 257 | len/=4; 258 | } else { 259 | len/=4; 260 | len+=1; 261 | } 262 | 263 | for i in (0 ..len).rev() { 264 | let mut b=DBIG::new_copy(&self); 265 | b.shr(i*4); 266 | s=s + &format!("{:X}", b.w[0]&15); 267 | } 268 | return s; 269 | } 270 | 271 | } 272 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/nist384/dbig.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use arch; 21 | use nist384::big; 22 | use nist384::big::BIG; 23 | use arch::Chunk; 24 | 25 | //#[derive(Copy, Clone)] 26 | pub struct DBIG { 27 | pub w: [Chunk; big::DNLEN] 28 | } 29 | 30 | impl DBIG { 31 | pub fn new() -> DBIG { 32 | DBIG { 33 | w: [0; big::DNLEN as usize] 34 | } 35 | } 36 | 37 | pub fn new_copy(y:&DBIG) -> DBIG { 38 | let mut s= DBIG::new(); 39 | for i in 0..big::DNLEN {s.w[i]=y.w[i]} 40 | return s; 41 | } 42 | 43 | pub fn new_scopy(x:&BIG) -> DBIG { 44 | let mut b= DBIG::new(); 45 | for i in 0 ..big::NLEN { 46 | b.w[i]=x.w[i]; 47 | } 48 | b.w[big::NLEN-1]=x.get(big::NLEN-1)&big::BMASK; /* top word normalized */ 49 | b.w[big::NLEN]=x.get(big::NLEN-1)>>big::BASEBITS; 50 | 51 | for i in big::NLEN+1 ..big::DNLEN {b.w[i]=0} 52 | return b; 53 | } 54 | 55 | /* split DBIG at position n, return higher half, keep lower half */ 56 | pub fn split(&mut self,n: usize) -> BIG 57 | { 58 | let mut t=BIG::new(); 59 | let m=n%big::BASEBITS; 60 | let mut carry=self.w[big::DNLEN-1]<<(big::BASEBITS-m); 61 | 62 | for i in (big::NLEN-1..big::DNLEN-1).rev() { 63 | let nw=(self.w[i]>>m)|carry; 64 | carry= (self.w[i]<<(big::BASEBITS-m))&big::BMASK; 65 | t.set(i+1-big::NLEN,nw); 66 | } 67 | self.w[big::NLEN-1]&=((1 as Chunk)<>(big::BASEBITS-n)); 77 | for i in (m+1..big::DNLEN-1).rev() { 78 | self.w[i]=((self.w[i-m]<>(big::BASEBITS-n)); 79 | } 80 | 81 | self.w[m]=(self.w[0]<>n)|((self.w[m+i+1]<<(big::BASEBITS-n))&big::BMASK); 91 | } 92 | self.w[big::DNLEN-m-1]=self.w[big::DNLEN-1]>>n; 93 | for i in big::DNLEN - m ..big::DNLEN {self.w[i]=0} 94 | } 95 | 96 | /* Copy from another DBIG */ 97 | pub fn copy(&mut self,x: &DBIG) { 98 | for i in 0 ..big::DNLEN { 99 | self.w[i]=x.w[i]; 100 | } 101 | } 102 | 103 | pub fn ucopy(&mut self,x: &BIG) { 104 | for i in 0 ..big::NLEN { 105 | self.w[i]=0; 106 | } 107 | for i in big::NLEN ..big::DNLEN { 108 | self.w[i]=x.w[i-big::NLEN]; 109 | } 110 | } 111 | 112 | pub fn cmove(&mut self,g:&DBIG,d: isize) { 113 | let b=-d as Chunk; 114 | for i in 0 ..big::DNLEN { 115 | self.w[i]^=(self.w[i]^g.w[i])&b; 116 | } 117 | } 118 | 119 | /* self+=x */ 120 | pub fn add(&mut self,x:&DBIG) { 121 | for i in 0 ..big::DNLEN { 122 | self.w[i]+=x.w[i]; 123 | } 124 | } 125 | 126 | /* self-=x */ 127 | pub fn sub(&mut self,x:&DBIG) { 128 | for i in 0 ..big::DNLEN { 129 | self.w[i]-=x.w[i]; 130 | } 131 | } 132 | 133 | /* self=x-self */ 134 | pub fn rsub(&mut self,x:&DBIG) { 135 | for i in 0 ..big::DNLEN { 136 | self.w[i]=x.w[i]-self.w[i]; 137 | } 138 | } 139 | 140 | 141 | /* Compare a and b, return 0 if a==b, -1 if ab. Inputs must be normalised */ 142 | pub fn comp(a: &DBIG,b: &DBIG) -> isize { 143 | for i in (0 ..big::DNLEN).rev() { 144 | if a.w[i]==b.w[i] {continue} 145 | if a.w[i]>b.w[i] {return 1} 146 | else {return -1} 147 | } 148 | return 0; 149 | } 150 | 151 | /* normalise BIG - force all digits < 2^big::BASEBITS */ 152 | pub fn norm(&mut self) { 153 | let mut carry=0 as Chunk; 154 | for i in 0 ..big::DNLEN-1 { 155 | let d=self.w[i]+carry; 156 | self.w[i]=d&big::BMASK; 157 | carry=d>>big::BASEBITS; 158 | } 159 | self.w[big::DNLEN-1]+=carry 160 | } 161 | 162 | /* reduces self DBIG mod a BIG, and returns the BIG */ 163 | pub fn dmod(&mut self,c: &BIG) -> BIG { 164 | let mut k=0; 165 | self.norm(); 166 | let mut m=DBIG::new_scopy(c); 167 | let mut dr=DBIG::new(); 168 | 169 | if DBIG::comp(self,&m)<0 { 170 | let r=BIG::new_dcopy(self); 171 | return r; 172 | } 173 | 174 | loop { 175 | m.shl(1); 176 | k += 1; 177 | if DBIG::comp(self,&m)<0 {break;} 178 | } 179 | 180 | while k>0 { 181 | m.shr(1); 182 | 183 | dr.copy(self); 184 | dr.sub(&m); 185 | dr.norm(); 186 | self.cmove(&dr,(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize); 187 | /* 188 | if DBIG::comp(self,&m)>=0 { 189 | self.sub(&m); 190 | self.norm(); 191 | } */ 192 | k -= 1; 193 | } 194 | let r=BIG::new_dcopy(self); 195 | return r; 196 | } 197 | 198 | /* return this/c */ 199 | pub fn div(&mut self,c: &BIG) -> BIG { 200 | let mut k=0; 201 | let mut m=DBIG::new_scopy(c); 202 | let mut a=BIG::new(); 203 | let mut e=BIG::new_int(1); 204 | let mut dr=DBIG::new(); 205 | let mut r=BIG::new(); 206 | self.norm(); 207 | 208 | while DBIG::comp(self,&m)>=0 { 209 | e.fshl(1); 210 | m.shl(1); 211 | k+=1; 212 | } 213 | 214 | while k>0 { 215 | m.shr(1); 216 | e.shr(1); 217 | 218 | dr.copy(self); 219 | dr.sub(&m); 220 | dr.norm(); 221 | let d=(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize; 222 | self.cmove(&dr,d); 223 | r.copy(&a); 224 | r.add(&e); 225 | r.norm(); 226 | a.cmove(&r,d); 227 | /* 228 | if DBIG::comp(self,&m)>0 { 229 | a.add(&e); 230 | a.norm(); 231 | self.sub(&m); 232 | self.norm(); 233 | } */ 234 | k-=1; 235 | } 236 | return a; 237 | } 238 | 239 | /* return number of bits */ 240 | pub fn nbits(&mut self) -> usize { 241 | let mut k=big::DNLEN-1; 242 | self.norm(); 243 | while (k as isize)>=0 && self.w[k]==0 {k=k.wrapping_sub(1)} 244 | if (k as isize) <0 {return 0} 245 | let mut bts=(big::BASEBITS as usize)*k; 246 | let mut c=self.w[k]; 247 | while c!=0 {c/=2; bts+=1;} 248 | return bts; 249 | } 250 | 251 | /* Convert to Hex String */ 252 | pub fn to_string(&mut self) -> String { 253 | let mut s = String::new(); 254 | let mut len=self.nbits(); 255 | 256 | if len%4==0 { 257 | len/=4; 258 | } else { 259 | len/=4; 260 | len+=1; 261 | } 262 | 263 | for i in (0 ..len).rev() { 264 | let mut b=DBIG::new_copy(&self); 265 | b.shr(i*4); 266 | s=s + &format!("{:X}", b.w[0]&15); 267 | } 268 | return s; 269 | } 270 | 271 | } 272 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/nist521/dbig.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use arch; 21 | use nist521::big; 22 | use nist521::big::BIG; 23 | use arch::Chunk; 24 | 25 | //#[derive(Copy, Clone)] 26 | pub struct DBIG { 27 | pub w: [Chunk; big::DNLEN] 28 | } 29 | 30 | impl DBIG { 31 | pub fn new() -> DBIG { 32 | DBIG { 33 | w: [0; big::DNLEN as usize] 34 | } 35 | } 36 | 37 | pub fn new_copy(y:&DBIG) -> DBIG { 38 | let mut s= DBIG::new(); 39 | for i in 0..big::DNLEN {s.w[i]=y.w[i]} 40 | return s; 41 | } 42 | 43 | pub fn new_scopy(x:&BIG) -> DBIG { 44 | let mut b= DBIG::new(); 45 | for i in 0 ..big::NLEN { 46 | b.w[i]=x.w[i]; 47 | } 48 | b.w[big::NLEN-1]=x.get(big::NLEN-1)&big::BMASK; /* top word normalized */ 49 | b.w[big::NLEN]=x.get(big::NLEN-1)>>big::BASEBITS; 50 | 51 | for i in big::NLEN+1 ..big::DNLEN {b.w[i]=0} 52 | return b; 53 | } 54 | 55 | /* split DBIG at position n, return higher half, keep lower half */ 56 | pub fn split(&mut self,n: usize) -> BIG 57 | { 58 | let mut t=BIG::new(); 59 | let m=n%big::BASEBITS; 60 | let mut carry=self.w[big::DNLEN-1]<<(big::BASEBITS-m); 61 | 62 | for i in (big::NLEN-1..big::DNLEN-1).rev() { 63 | let nw=(self.w[i]>>m)|carry; 64 | carry= (self.w[i]<<(big::BASEBITS-m))&big::BMASK; 65 | t.set(i+1-big::NLEN,nw); 66 | } 67 | self.w[big::NLEN-1]&=((1 as Chunk)<>(big::BASEBITS-n)); 77 | for i in (m+1..big::DNLEN-1).rev() { 78 | self.w[i]=((self.w[i-m]<>(big::BASEBITS-n)); 79 | } 80 | 81 | self.w[m]=(self.w[0]<>n)|((self.w[m+i+1]<<(big::BASEBITS-n))&big::BMASK); 91 | } 92 | self.w[big::DNLEN-m-1]=self.w[big::DNLEN-1]>>n; 93 | for i in big::DNLEN - m ..big::DNLEN {self.w[i]=0} 94 | } 95 | 96 | /* Copy from another DBIG */ 97 | pub fn copy(&mut self,x: &DBIG) { 98 | for i in 0 ..big::DNLEN { 99 | self.w[i]=x.w[i]; 100 | } 101 | } 102 | 103 | pub fn ucopy(&mut self,x: &BIG) { 104 | for i in 0 ..big::NLEN { 105 | self.w[i]=0; 106 | } 107 | for i in big::NLEN ..big::DNLEN { 108 | self.w[i]=x.w[i-big::NLEN]; 109 | } 110 | } 111 | 112 | pub fn cmove(&mut self,g:&DBIG,d: isize) { 113 | let b=-d as Chunk; 114 | for i in 0 ..big::DNLEN { 115 | self.w[i]^=(self.w[i]^g.w[i])&b; 116 | } 117 | } 118 | 119 | /* self+=x */ 120 | pub fn add(&mut self,x:&DBIG) { 121 | for i in 0 ..big::DNLEN { 122 | self.w[i]+=x.w[i]; 123 | } 124 | } 125 | 126 | /* self-=x */ 127 | pub fn sub(&mut self,x:&DBIG) { 128 | for i in 0 ..big::DNLEN { 129 | self.w[i]-=x.w[i]; 130 | } 131 | } 132 | 133 | /* self=x-self */ 134 | pub fn rsub(&mut self,x:&DBIG) { 135 | for i in 0 ..big::DNLEN { 136 | self.w[i]=x.w[i]-self.w[i]; 137 | } 138 | } 139 | 140 | 141 | /* Compare a and b, return 0 if a==b, -1 if ab. Inputs must be normalised */ 142 | pub fn comp(a: &DBIG,b: &DBIG) -> isize { 143 | for i in (0 ..big::DNLEN).rev() { 144 | if a.w[i]==b.w[i] {continue} 145 | if a.w[i]>b.w[i] {return 1} 146 | else {return -1} 147 | } 148 | return 0; 149 | } 150 | 151 | /* normalise BIG - force all digits < 2^big::BASEBITS */ 152 | pub fn norm(&mut self) { 153 | let mut carry=0 as Chunk; 154 | for i in 0 ..big::DNLEN-1 { 155 | let d=self.w[i]+carry; 156 | self.w[i]=d&big::BMASK; 157 | carry=d>>big::BASEBITS; 158 | } 159 | self.w[big::DNLEN-1]+=carry 160 | } 161 | 162 | /* reduces self DBIG mod a BIG, and returns the BIG */ 163 | pub fn dmod(&mut self,c: &BIG) -> BIG { 164 | let mut k=0; 165 | self.norm(); 166 | let mut m=DBIG::new_scopy(c); 167 | let mut dr=DBIG::new(); 168 | 169 | if DBIG::comp(self,&m)<0 { 170 | let r=BIG::new_dcopy(self); 171 | return r; 172 | } 173 | 174 | loop { 175 | m.shl(1); 176 | k += 1; 177 | if DBIG::comp(self,&m)<0 {break;} 178 | } 179 | 180 | while k>0 { 181 | m.shr(1); 182 | 183 | dr.copy(self); 184 | dr.sub(&m); 185 | dr.norm(); 186 | self.cmove(&dr,(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize); 187 | /* 188 | if DBIG::comp(self,&m)>=0 { 189 | self.sub(&m); 190 | self.norm(); 191 | } */ 192 | k -= 1; 193 | } 194 | let r=BIG::new_dcopy(self); 195 | return r; 196 | } 197 | 198 | /* return this/c */ 199 | pub fn div(&mut self,c: &BIG) -> BIG { 200 | let mut k=0; 201 | let mut m=DBIG::new_scopy(c); 202 | let mut a=BIG::new(); 203 | let mut e=BIG::new_int(1); 204 | let mut dr=DBIG::new(); 205 | let mut r=BIG::new(); 206 | self.norm(); 207 | 208 | while DBIG::comp(self,&m)>=0 { 209 | e.fshl(1); 210 | m.shl(1); 211 | k+=1; 212 | } 213 | 214 | while k>0 { 215 | m.shr(1); 216 | e.shr(1); 217 | 218 | dr.copy(self); 219 | dr.sub(&m); 220 | dr.norm(); 221 | let d=(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize; 222 | self.cmove(&dr,d); 223 | r.copy(&a); 224 | r.add(&e); 225 | r.norm(); 226 | a.cmove(&r,d); 227 | /* 228 | if DBIG::comp(self,&m)>0 { 229 | a.add(&e); 230 | a.norm(); 231 | self.sub(&m); 232 | self.norm(); 233 | } */ 234 | k-=1; 235 | } 236 | return a; 237 | } 238 | 239 | /* return number of bits */ 240 | pub fn nbits(&mut self) -> usize { 241 | let mut k=big::DNLEN-1; 242 | self.norm(); 243 | while (k as isize)>=0 && self.w[k]==0 {k=k.wrapping_sub(1)} 244 | if (k as isize) <0 {return 0} 245 | let mut bts=(big::BASEBITS as usize)*k; 246 | let mut c=self.w[k]; 247 | while c!=0 {c/=2; bts+=1;} 248 | return bts; 249 | } 250 | 251 | /* Convert to Hex String */ 252 | pub fn to_string(&mut self) -> String { 253 | let mut s = String::new(); 254 | let mut len=self.nbits(); 255 | 256 | if len%4==0 { 257 | len/=4; 258 | } else { 259 | len/=4; 260 | len+=1; 261 | } 262 | 263 | for i in (0 ..len).rev() { 264 | let mut b=DBIG::new_copy(&self); 265 | b.shr(i*4); 266 | s=s + &format!("{:X}", b.w[0]&15); 267 | } 268 | return s; 269 | } 270 | 271 | } 272 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/rsa2048/dbig.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use arch; 21 | use rsa2048::big; 22 | use rsa2048::big::BIG; 23 | use arch::Chunk; 24 | 25 | //#[derive(Copy, Clone)] 26 | pub struct DBIG { 27 | pub w: [Chunk; big::DNLEN] 28 | } 29 | 30 | impl DBIG { 31 | pub fn new() -> DBIG { 32 | DBIG { 33 | w: [0; big::DNLEN as usize] 34 | } 35 | } 36 | 37 | pub fn new_copy(y:&DBIG) -> DBIG { 38 | let mut s= DBIG::new(); 39 | for i in 0..big::DNLEN {s.w[i]=y.w[i]} 40 | return s; 41 | } 42 | 43 | pub fn new_scopy(x:&BIG) -> DBIG { 44 | let mut b= DBIG::new(); 45 | for i in 0 ..big::NLEN { 46 | b.w[i]=x.w[i]; 47 | } 48 | b.w[big::NLEN-1]=x.get(big::NLEN-1)&big::BMASK; /* top word normalized */ 49 | b.w[big::NLEN]=x.get(big::NLEN-1)>>big::BASEBITS; 50 | 51 | for i in big::NLEN+1 ..big::DNLEN {b.w[i]=0} 52 | return b; 53 | } 54 | 55 | /* split DBIG at position n, return higher half, keep lower half */ 56 | pub fn split(&mut self,n: usize) -> BIG 57 | { 58 | let mut t=BIG::new(); 59 | let m=n%big::BASEBITS; 60 | let mut carry=self.w[big::DNLEN-1]<<(big::BASEBITS-m); 61 | 62 | for i in (big::NLEN-1..big::DNLEN-1).rev() { 63 | let nw=(self.w[i]>>m)|carry; 64 | carry= (self.w[i]<<(big::BASEBITS-m))&big::BMASK; 65 | t.set(i+1-big::NLEN,nw); 66 | } 67 | self.w[big::NLEN-1]&=((1 as Chunk)<>(big::BASEBITS-n)); 77 | for i in (m+1..big::DNLEN-1).rev() { 78 | self.w[i]=((self.w[i-m]<>(big::BASEBITS-n)); 79 | } 80 | 81 | self.w[m]=(self.w[0]<>n)|((self.w[m+i+1]<<(big::BASEBITS-n))&big::BMASK); 91 | } 92 | self.w[big::DNLEN-m-1]=self.w[big::DNLEN-1]>>n; 93 | for i in big::DNLEN - m ..big::DNLEN {self.w[i]=0} 94 | } 95 | 96 | /* Copy from another DBIG */ 97 | pub fn copy(&mut self,x: &DBIG) { 98 | for i in 0 ..big::DNLEN { 99 | self.w[i]=x.w[i]; 100 | } 101 | } 102 | 103 | pub fn ucopy(&mut self,x: &BIG) { 104 | for i in 0 ..big::NLEN { 105 | self.w[i]=0; 106 | } 107 | for i in big::NLEN ..big::DNLEN { 108 | self.w[i]=x.w[i-big::NLEN]; 109 | } 110 | } 111 | 112 | pub fn cmove(&mut self,g:&DBIG,d: isize) { 113 | let b=-d as Chunk; 114 | for i in 0 ..big::DNLEN { 115 | self.w[i]^=(self.w[i]^g.w[i])&b; 116 | } 117 | } 118 | 119 | /* self+=x */ 120 | pub fn add(&mut self,x:&DBIG) { 121 | for i in 0 ..big::DNLEN { 122 | self.w[i]+=x.w[i]; 123 | } 124 | } 125 | 126 | /* self-=x */ 127 | pub fn sub(&mut self,x:&DBIG) { 128 | for i in 0 ..big::DNLEN { 129 | self.w[i]-=x.w[i]; 130 | } 131 | } 132 | 133 | /* self=x-self */ 134 | pub fn rsub(&mut self,x:&DBIG) { 135 | for i in 0 ..big::DNLEN { 136 | self.w[i]=x.w[i]-self.w[i]; 137 | } 138 | } 139 | 140 | 141 | /* Compare a and b, return 0 if a==b, -1 if ab. Inputs must be normalised */ 142 | pub fn comp(a: &DBIG,b: &DBIG) -> isize { 143 | for i in (0 ..big::DNLEN).rev() { 144 | if a.w[i]==b.w[i] {continue} 145 | if a.w[i]>b.w[i] {return 1} 146 | else {return -1} 147 | } 148 | return 0; 149 | } 150 | 151 | /* normalise BIG - force all digits < 2^big::BASEBITS */ 152 | pub fn norm(&mut self) { 153 | let mut carry=0 as Chunk; 154 | for i in 0 ..big::DNLEN-1 { 155 | let d=self.w[i]+carry; 156 | self.w[i]=d&big::BMASK; 157 | carry=d>>big::BASEBITS; 158 | } 159 | self.w[big::DNLEN-1]+=carry 160 | } 161 | 162 | /* reduces self DBIG mod a BIG, and returns the BIG */ 163 | pub fn dmod(&mut self,c: &BIG) -> BIG { 164 | let mut k=0; 165 | self.norm(); 166 | let mut m=DBIG::new_scopy(c); 167 | let mut dr=DBIG::new(); 168 | 169 | if DBIG::comp(self,&m)<0 { 170 | let r=BIG::new_dcopy(self); 171 | return r; 172 | } 173 | 174 | loop { 175 | m.shl(1); 176 | k += 1; 177 | if DBIG::comp(self,&m)<0 {break;} 178 | } 179 | 180 | while k>0 { 181 | m.shr(1); 182 | 183 | dr.copy(self); 184 | dr.sub(&m); 185 | dr.norm(); 186 | self.cmove(&dr,(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize); 187 | /* 188 | if DBIG::comp(self,&m)>=0 { 189 | self.sub(&m); 190 | self.norm(); 191 | } */ 192 | k -= 1; 193 | } 194 | let r=BIG::new_dcopy(self); 195 | return r; 196 | } 197 | 198 | /* return this/c */ 199 | pub fn div(&mut self,c: &BIG) -> BIG { 200 | let mut k=0; 201 | let mut m=DBIG::new_scopy(c); 202 | let mut a=BIG::new(); 203 | let mut e=BIG::new_int(1); 204 | let mut dr=DBIG::new(); 205 | let mut r=BIG::new(); 206 | self.norm(); 207 | 208 | while DBIG::comp(self,&m)>=0 { 209 | e.fshl(1); 210 | m.shl(1); 211 | k+=1; 212 | } 213 | 214 | while k>0 { 215 | m.shr(1); 216 | e.shr(1); 217 | 218 | dr.copy(self); 219 | dr.sub(&m); 220 | dr.norm(); 221 | let d=(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize; 222 | self.cmove(&dr,d); 223 | r.copy(&a); 224 | r.add(&e); 225 | r.norm(); 226 | a.cmove(&r,d); 227 | /* 228 | if DBIG::comp(self,&m)>0 { 229 | a.add(&e); 230 | a.norm(); 231 | self.sub(&m); 232 | self.norm(); 233 | } */ 234 | k-=1; 235 | } 236 | return a; 237 | } 238 | 239 | /* return number of bits */ 240 | pub fn nbits(&mut self) -> usize { 241 | let mut k=big::DNLEN-1; 242 | self.norm(); 243 | while (k as isize)>=0 && self.w[k]==0 {k=k.wrapping_sub(1)} 244 | if (k as isize) <0 {return 0} 245 | let mut bts=(big::BASEBITS as usize)*k; 246 | let mut c=self.w[k]; 247 | while c!=0 {c/=2; bts+=1;} 248 | return bts; 249 | } 250 | 251 | /* Convert to Hex String */ 252 | pub fn to_string(&mut self) -> String { 253 | let mut s = String::new(); 254 | let mut len=self.nbits(); 255 | 256 | if len%4==0 { 257 | len/=4; 258 | } else { 259 | len/=4; 260 | len+=1; 261 | } 262 | 263 | for i in (0 ..len).rev() { 264 | let mut b=DBIG::new_copy(&self); 265 | b.shr(i*4); 266 | s=s + &format!("{:X}", b.w[0]&15); 267 | } 268 | return s; 269 | } 270 | 271 | } 272 | -------------------------------------------------------------------------------- /libhl-crypto/amcl/src/rsa3072/dbig.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed to the Apache Software Foundation (ASF) under one 3 | or more contributor license agreements. See the NOTICE file 4 | distributed with this work for additional information 5 | regarding copyright ownership. The ASF licenses this file 6 | to you under the Apache License, Version 2.0 (the 7 | "License"); you may not use this file except in compliance 8 | with the License. You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, 13 | software distributed under the License is distributed on an 14 | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | KIND, either express or implied. See the License for the 16 | specific language governing permissions and limitations 17 | under the License. 18 | */ 19 | 20 | use arch; 21 | use rsa3072::big; 22 | use rsa3072::big::BIG; 23 | use arch::Chunk; 24 | 25 | //#[derive(Copy, Clone)] 26 | pub struct DBIG { 27 | pub w: [Chunk; big::DNLEN] 28 | } 29 | 30 | impl DBIG { 31 | pub fn new() -> DBIG { 32 | DBIG { 33 | w: [0; big::DNLEN as usize] 34 | } 35 | } 36 | 37 | pub fn new_copy(y:&DBIG) -> DBIG { 38 | let mut s= DBIG::new(); 39 | for i in 0..big::DNLEN {s.w[i]=y.w[i]} 40 | return s; 41 | } 42 | 43 | pub fn new_scopy(x:&BIG) -> DBIG { 44 | let mut b= DBIG::new(); 45 | for i in 0 ..big::NLEN { 46 | b.w[i]=x.w[i]; 47 | } 48 | b.w[big::NLEN-1]=x.get(big::NLEN-1)&big::BMASK; /* top word normalized */ 49 | b.w[big::NLEN]=x.get(big::NLEN-1)>>big::BASEBITS; 50 | 51 | for i in big::NLEN+1 ..big::DNLEN {b.w[i]=0} 52 | return b; 53 | } 54 | 55 | /* split DBIG at position n, return higher half, keep lower half */ 56 | pub fn split(&mut self,n: usize) -> BIG 57 | { 58 | let mut t=BIG::new(); 59 | let m=n%big::BASEBITS; 60 | let mut carry=self.w[big::DNLEN-1]<<(big::BASEBITS-m); 61 | 62 | for i in (big::NLEN-1..big::DNLEN-1).rev() { 63 | let nw=(self.w[i]>>m)|carry; 64 | carry= (self.w[i]<<(big::BASEBITS-m))&big::BMASK; 65 | t.set(i+1-big::NLEN,nw); 66 | } 67 | self.w[big::NLEN-1]&=((1 as Chunk)<>(big::BASEBITS-n)); 77 | for i in (m+1..big::DNLEN-1).rev() { 78 | self.w[i]=((self.w[i-m]<>(big::BASEBITS-n)); 79 | } 80 | 81 | self.w[m]=(self.w[0]<>n)|((self.w[m+i+1]<<(big::BASEBITS-n))&big::BMASK); 91 | } 92 | self.w[big::DNLEN-m-1]=self.w[big::DNLEN-1]>>n; 93 | for i in big::DNLEN - m ..big::DNLEN {self.w[i]=0} 94 | } 95 | 96 | /* Copy from another DBIG */ 97 | pub fn copy(&mut self,x: &DBIG) { 98 | for i in 0 ..big::DNLEN { 99 | self.w[i]=x.w[i]; 100 | } 101 | } 102 | 103 | pub fn ucopy(&mut self,x: &BIG) { 104 | for i in 0 ..big::NLEN { 105 | self.w[i]=0; 106 | } 107 | for i in big::NLEN ..big::DNLEN { 108 | self.w[i]=x.w[i-big::NLEN]; 109 | } 110 | } 111 | 112 | pub fn cmove(&mut self,g:&DBIG,d: isize) { 113 | let b=-d as Chunk; 114 | for i in 0 ..big::DNLEN { 115 | self.w[i]^=(self.w[i]^g.w[i])&b; 116 | } 117 | } 118 | 119 | /* self+=x */ 120 | pub fn add(&mut self,x:&DBIG) { 121 | for i in 0 ..big::DNLEN { 122 | self.w[i]+=x.w[i]; 123 | } 124 | } 125 | 126 | /* self-=x */ 127 | pub fn sub(&mut self,x:&DBIG) { 128 | for i in 0 ..big::DNLEN { 129 | self.w[i]-=x.w[i]; 130 | } 131 | } 132 | 133 | /* self=x-self */ 134 | pub fn rsub(&mut self,x:&DBIG) { 135 | for i in 0 ..big::DNLEN { 136 | self.w[i]=x.w[i]-self.w[i]; 137 | } 138 | } 139 | 140 | 141 | /* Compare a and b, return 0 if a==b, -1 if ab. Inputs must be normalised */ 142 | pub fn comp(a: &DBIG,b: &DBIG) -> isize { 143 | for i in (0 ..big::DNLEN).rev() { 144 | if a.w[i]==b.w[i] {continue} 145 | if a.w[i]>b.w[i] {return 1} 146 | else {return -1} 147 | } 148 | return 0; 149 | } 150 | 151 | /* normalise BIG - force all digits < 2^big::BASEBITS */ 152 | pub fn norm(&mut self) { 153 | let mut carry=0 as Chunk; 154 | for i in 0 ..big::DNLEN-1 { 155 | let d=self.w[i]+carry; 156 | self.w[i]=d&big::BMASK; 157 | carry=d>>big::BASEBITS; 158 | } 159 | self.w[big::DNLEN-1]+=carry 160 | } 161 | 162 | /* reduces self DBIG mod a BIG, and returns the BIG */ 163 | pub fn dmod(&mut self,c: &BIG) -> BIG { 164 | let mut k=0; 165 | self.norm(); 166 | let mut m=DBIG::new_scopy(c); 167 | let mut dr=DBIG::new(); 168 | 169 | if DBIG::comp(self,&m)<0 { 170 | let r=BIG::new_dcopy(self); 171 | return r; 172 | } 173 | 174 | loop { 175 | m.shl(1); 176 | k += 1; 177 | if DBIG::comp(self,&m)<0 {break;} 178 | } 179 | 180 | while k>0 { 181 | m.shr(1); 182 | 183 | dr.copy(self); 184 | dr.sub(&m); 185 | dr.norm(); 186 | self.cmove(&dr,(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize); 187 | /* 188 | if DBIG::comp(self,&m)>=0 { 189 | self.sub(&m); 190 | self.norm(); 191 | } */ 192 | k -= 1; 193 | } 194 | let r=BIG::new_dcopy(self); 195 | return r; 196 | } 197 | 198 | /* return this/c */ 199 | pub fn div(&mut self,c: &BIG) -> BIG { 200 | let mut k=0; 201 | let mut m=DBIG::new_scopy(c); 202 | let mut a=BIG::new(); 203 | let mut e=BIG::new_int(1); 204 | let mut dr=DBIG::new(); 205 | let mut r=BIG::new(); 206 | self.norm(); 207 | 208 | while DBIG::comp(self,&m)>=0 { 209 | e.fshl(1); 210 | m.shl(1); 211 | k+=1; 212 | } 213 | 214 | while k>0 { 215 | m.shr(1); 216 | e.shr(1); 217 | 218 | dr.copy(self); 219 | dr.sub(&m); 220 | dr.norm(); 221 | let d=(1-((dr.w[big::DNLEN-1]>>(arch::CHUNK-1))&1)) as isize; 222 | self.cmove(&dr,d); 223 | r.copy(&a); 224 | r.add(&e); 225 | r.norm(); 226 | a.cmove(&r,d); 227 | /* 228 | if DBIG::comp(self,&m)>0 { 229 | a.add(&e); 230 | a.norm(); 231 | self.sub(&m); 232 | self.norm(); 233 | } */ 234 | k-=1; 235 | } 236 | return a; 237 | } 238 | 239 | /* return number of bits */ 240 | pub fn nbits(&mut self) -> usize { 241 | let mut k=big::DNLEN-1; 242 | self.norm(); 243 | while (k as isize)>=0 && self.w[k]==0 {k=k.wrapping_sub(1)} 244 | if (k as isize) <0 {return 0} 245 | let mut bts=(big::BASEBITS as usize)*k; 246 | let mut c=self.w[k]; 247 | while c!=0 {c/=2; bts+=1;} 248 | return bts; 249 | } 250 | 251 | /* Convert to Hex String */ 252 | pub fn to_string(&mut self) -> String { 253 | let mut s = String::new(); 254 | let mut len=self.nbits(); 255 | 256 | if len%4==0 { 257 | len/=4; 258 | } else { 259 | len/=4; 260 | len+=1; 261 | } 262 | 263 | for i in (0 ..len).rev() { 264 | let mut b=DBIG::new_copy(&self); 265 | b.shr(i*4); 266 | s=s + &format!("{:X}", b.w[0]&15); 267 | } 268 | return s; 269 | } 270 | 271 | } 272 | --------------------------------------------------------------------------------