Nevermind on the whole fixed size thing?

This commit is contained in:
2018-03-22 21:04:22 -07:00
parent 667e32694e
commit 7a8bb7b4fd
8 changed files with 0 additions and 2119 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -1,332 +0,0 @@
use std::cmp::Ordering;
#[inline(always)]
pub fn generic_cmp(a: &[u64], b: &[u64]) -> Ordering {
let mut i = a.len() - 1;
assert!(a.len() == b.len());
loop {
match a[i].cmp(&b[i]) {
Ordering::Equal if i == 0 =>
return Ordering::Equal,
Ordering::Equal =>
i -= 1,
res =>
return res
}
}
}
fn le(a: &[u64], b: &[u64]) -> bool {
generic_cmp(a, b) != Ordering::Greater
}
pub fn ge(a: &[u64], b: &[u64]) -> bool {
generic_cmp(a, b) != Ordering::Less
}
#[inline(always)]
pub fn generic_bitand(a: &mut [u64], b: &[u64]) {
let mut i = 0;
assert!(a.len() == b.len());
while i < a.len() {
a[i] &= b[i];
i += 1;
}
}
#[inline(always)]
pub fn generic_bitor(a: &mut [u64], b: &[u64]) {
let mut i = 0;
assert!(a.len() == b.len());
while i < a.len() {
a[i] |= b[i];
i += 1;
}
}
#[inline(always)]
pub fn generic_bitxor(a: &mut [u64], b: &[u64]) {
let mut i = 0;
assert!(a.len() == b.len());
while i < a.len() {
a[i] ^= b[i];
i += 1;
}
}
#[inline(always)]
pub fn generic_not(a: &mut [u64]) {
for x in a.iter_mut() {
*x = !*x;
}
}
#[inline(always)]
pub fn generic_shl(a: &mut [u64], orig: &[u64], amount: usize) {
let digits = amount / 64;
let bits = amount % 64;
assert!(a.len() == orig.len());
for i in 0..a.len() {
if i < digits {
a[i] = 0;
} else {
let origidx = i - digits;
let prev = if origidx == 0 { 0 } else { orig[origidx - 1] };
let (carry,_) = if bits == 0 { (0, false) }
else { prev.overflowing_shr(64 - bits as u32) };
a[i] = (orig[origidx] << bits) | carry;
}
}
}
#[inline(always)]
pub fn generic_shr(a: &mut [u64], orig: &[u64], amount: usize) {
let digits = amount / 64;
let bits = amount % 64;
assert!(a.len() == orig.len());
for i in 0..a.len() {
let oldidx = i + digits;
let caridx = i + digits + 1;
let old = if oldidx >= a.len() { 0 } else { orig[oldidx] };
let carry = if caridx >= a.len() { 0 } else { orig[caridx] };
let cb = if bits == 0 { 0 } else { carry << (64 - bits) };
a[i] = (old >> bits) | cb;
}
}
#[inline(always)]
pub fn generic_add(a: &mut [u64], b: &[u64]) {
let mut carry = 0;
assert!(a.len() == b.len());
for i in 0..a.len() {
let x = a[i] as u128;
let y = b[i] as u128;
let total = x + y + carry;
a[i] = total as u64;
carry = total >> 64;
}
}
#[inline(always)]
pub fn generic_sub(a: &mut [u64], b: &[u64]) {
let mut negated_rhs = b.to_vec();
generic_not(&mut negated_rhs);
let mut one = Vec::with_capacity(a.len());
one.resize(a.len(), 0);
one[0] = 1;
generic_add(&mut negated_rhs, &one);
generic_add(a, &negated_rhs);
}
#[inline(always)]
pub fn generic_mul(a: &mut [u64], orig: &[u64], b: &[u64]) {
assert!(a.len() == orig.len());
assert!(a.len() == b.len());
assert!(a == orig);
// Build the output table. This is a little bit awkward because we don't
// know how big we're running, but hopefully the compiler is smart enough
// to work all this out.
let mut table = Vec::with_capacity(a.len());
for _ in 0..a.len() {
let mut row = Vec::with_capacity(a.len());
row.resize(a.len(), 0);
table.push(row);
}
// This uses "simple" grade school techniques to work things out. But,
// for reference, consider two 4 digit numbers:
//
// l0c3 l0c2 l0c1 l0c0 [orig]
// x l1c3 l1c2 l1c1 l1c0 [b]
// ------------------------------------------------------------
// (l0c3*l1c0) (l0c2*l1c0) (l0c1*l1c0) (l0c0*l1c0)
// (l0c2*l1c1) (l0c1*l1c1) (l0c0*l1c1)
// (l0c1*l1c2) (l0c0*l1c2)
// (l0c0*l1c3)
// ------------------------------------------------------------
// AAAAA BBBBB CCCCC DDDDD
for line in 0..a.len() {
let maxcol = a.len() - line;
for col in 0..maxcol {
let left = orig[col] as u128;
let right = b[line] as u128;
table[line][col + line] = left * right;
}
}
// ripple the carry across each line, ensuring that each entry in the
// table is 64-bits
for line in 0..a.len() {
let mut carry = 0;
for col in 0..a.len() {
table[line][col] = table[line][col] + carry;
carry = table[line][col] >> 64;
table[line][col] &= 0xFFFFFFFFFFFFFFFF;
}
}
// now do the final addition across the lines, rippling the carry as
// normal
let mut carry = 0;
for col in 0..a.len() {
let mut total = carry;
for line in 0..a.len() {
total += table[line][col];
}
a[col] = total as u64;
carry = total >> 64;
}
}
#[inline(always)]
pub fn expanding_mul(a: &[u64], b: &[u64]) -> Vec<u64> {
assert!(a.len() == b.len());
// The maximum size of an n x n digit multiplication is 2n digits, so
// here's our output array.
let mut result = Vec::with_capacity(a.len() * 2);
result.resize(a.len() * 2, 0);
for (base_idx, digit) in b.iter().enumerate() {
let mut myrow = Vec::with_capacity(a.len() * 2);
let mut carry = 0;
myrow.resize(a.len() * 2, 0);
for (col_idx, digit2) in a.iter().enumerate() {
let left = *digit2 as u128;
let right = *digit as u128;
let combo = (left * right) + carry;
myrow[base_idx + col_idx] = combo as u64;
carry = combo >> 64;
}
generic_add(&mut result, &myrow);
}
result
}
#[inline(always)]
pub fn generic_div(inx: &[u64], iny: &[u64],
outq: &mut [u64], outr: &mut [u64])
{
assert!(inx.len() == inx.len());
assert!(inx.len() == iny.len());
assert!(inx.len() == outq.len());
assert!(inx.len() == outr.len());
// This algorithm is from the Handbook of Applied Cryptography, Chapter 14,
// algorithm 14.20. It has a couple assumptions about the inputs, namely that
// n >= t >= 1 and y[t] != 0, where n and t refer to the number of digits in
// the numbers. Which means that if we used the inputs unmodified, we can't
// divide by single-digit numbers.
//
// To deal with this, we multiply inx and iny by 2^64, so that we push out
// t by one.
//
// In addition, this algorithm starts to go badly when y[t] is very small
// and x[n] is very large. Really, really badly. This can be fixed by
// insuring that the top bit is set in y[t], which we can achieve by
// shifting everyone over a maxiumum of 63 bits.
//
// What this means is, just for safety, we add a 0 at the beginning and
// end of each number.
let mut y = iny.to_vec();
let mut x = inx.to_vec();
y.insert(0,0); y.push(0);
x.insert(0,0); x.push(0);
// 0. Compute 'n' and 't'
let n = x.len() - 1;
let mut t = y.len() - 1;
while (t > 0) && (y[t] == 0) { t -= 1 }
assert!(y[t] != 0); // this is where division by zero will fire
// 0.5. Figure out a shift we can do such that the high bit of y[t] is
// set, and then shift x and y left by that much.
let additional_shift: usize = y[t].leading_zeros() as usize;
let origx = x.clone();
let origy = y.clone();
generic_shl(&mut x, &origx, additional_shift);
generic_shl(&mut y, &origy, additional_shift);
// 1. For j from 0 to (n - 1) do: q_j <- 0
let mut q = Vec::with_capacity(y.len());
q.resize(y.len(), 0);
for qj in q.iter_mut() { *qj = 0 }
// 2. While (x >= yb^(n-t)) do the following:
// q_(n-t) <- q_(n-t) + 1
// x <- x - yb^(n-t)
let mut ybnt = y.clone();
generic_shl(&mut ybnt, &y, 64 * (n - t));
while ge(&x, &ybnt) {
q[n-t] = q[n-t] + 1;
generic_sub(&mut x, &ybnt);
}
// 3. For i from n down to (t + 1) do the following:
let mut i = n;
while i >= (t + 1) {
// 3.1. if x_i = y_t, then set q_(i-t-1) <- b - 1; otherwise set
// q_(i-t-1) <- floor((x_i * b + x_(i-1)) / y_t).
if x[i] == y[t] {
q[i-t-1] = 0xFFFFFFFFFFFFFFFF;
} else {
let top = ((x[i] as u128) << 64) + (x[i-1] as u128);
let bot = y[t] as u128;
let solution = top / bot;
q[i-t-1] = solution as u64;
}
// 3.2. While (q_(i-t-1)(y_t * b + y_(t-1)) > x_i(b2) + x_(i-1)b +
// x_(i-2)) do:
// q_(i - t - 1) <- q_(i - t 1) - 1.
loop {
let mut left = Vec::with_capacity(x.len());
left.resize(x.len(), 0);
left[0] = q[i - t - 1];
let mut leftright = Vec::with_capacity(x.len());
leftright.resize(x.len(), 0);
leftright[0] = y[t-1];
let copy = left.clone();
generic_mul(&mut left, &copy, &leftright);
let mut right = Vec::with_capacity(x.len());
right.resize(x.len(), 0);
right[0] = x[i-2];
right[1] = x[i-1];
right[2] = x[i];
if le(&left, &right) {
break
}
q[i - t - 1] -= 1;
}
// 3.3. x <- x - q_(i - t - 1) * y * b^(i-t-1)
let mut right = Vec::with_capacity(y.len());
right.resize(y.len(), 0);
right[i - t - 1] = q[i - t - 1];
let rightclone = right.clone();
generic_mul(&mut right, &rightclone, &y);
let wentnegative = generic_cmp(&x, &right) == Ordering::Less;
generic_sub(&mut x, &right);
// 3.4. if x < 0 then set x <- x + yb^(i-t-1) and
// q_(i-t-1) <- q_(i-t-1) - 1
if wentnegative {
let mut ybit1 = y.to_vec();
generic_shl(&mut ybit1, &y, 64 * (i - t - 1));
generic_add(&mut x, &ybit1);
q[i - t - 1] -= 1;
}
i -= 1;
}
// 4. r <- x
let finalx = x.clone();
generic_shr(&mut x, &finalx, additional_shift);
for i in 0..outr.len() {
outr[i] = x[i + 1]; // note that for the remainder, we're dividing by
// our normalization value.
}
// 5. return (q,r)
for i in 0..outq.len() {
outq[i] = q[i];
}
}

View File

@@ -1,71 +0,0 @@
use cryptonum::signed::Signed;
use cryptonum::traits::*;
use std::ops::*;
pub fn modinv<'a,T>(e: &T, phi: &T) -> T
where
T: Clone + CryptoNumBase + Ord,
T: AddAssign + SubAssign + MulAssign + DivAssign,
T: Add<Output=T> + Sub<Output=T> + Mul<Output=T> + Div<Output=T>,
&'a T: Sub<Output=T>,
T: 'a
{
let (_, mut x, _) = extended_euclidean(e, phi);
let int_phi = Signed::<T>::new(phi.clone());
while x.is_negative() {
x += &int_phi;
}
x.abs()
}
pub fn modexp<T>(b: &T, e: &T, m: &T) -> T
{
panic!("modexp")
}
pub fn extended_euclidean<T>(a: &T, b: &T) -> (Signed<T>, Signed<T>, Signed<T>)
where
T: Clone + CryptoNumBase + Div + Mul + Sub
{
let posinta = Signed::<T>::new(a.clone());
let posintb = Signed::<T>::new(b.clone());
let (mut d, mut x, mut y) = egcd(&posinta, &posintb);
if d.is_negative() {
d.negate();
x.negate();
y.negate();
}
(d, x, y)
}
pub fn egcd<T>(a: &Signed<T>, b: &Signed<T>) -> (Signed<T>,Signed<T>,Signed<T>)
where
T: Clone + CryptoNumBase + Div + Mul + Sub
{
let mut s = Signed::<T>::zero();
let mut old_s = Signed::<T>::from_u8(1);
let mut t = Signed::<T>::from_u8(1);
let mut old_t = Signed::<T>::zero();
let mut r = b.clone();
let mut old_r = a.clone();
while !r.is_zero() {
let quotient = old_r.clone() / r.clone();
let prov_r = r.clone();
let prov_s = s.clone();
let prov_t = t.clone();
r = old_r - (r * &quotient);
s = old_s - (s * &quotient);
t = old_t - (t * &quotient);
old_r = prov_r;
old_s = prov_s;
old_t = prov_t;
}
(old_r, old_s, old_t)
}

View File

@@ -1,18 +0,0 @@
//! # Simple-Crypto CryptoNum
//!
//! This module is designed to provide large, fixed-width number support for
//! the rest of the Simple-Crypto libraries. Feel free to use it other places,
//! of course, but that's its origin.
mod core;
#[macro_use]
mod builder;
//mod extended_math;
// mod primes;
mod signed;
mod traits;
mod unsigned;
// pub use self::extended_math::{modexp,modinv,extended_euclidean,egcd};
// pub use self::primes::{probably_prime};
pub use self::signed::{Signed};
pub use self::unsigned::{U512,U1024,U2048,U3072,U4096,U7680,U8192,U15360};

View File

@@ -1,129 +0,0 @@
use cryptonum::extended_math::modexp;
use cryptonum::traits::*;
use rand::Rng;
use std::ops::*;
static SMALL_PRIMES: [u64; 310] = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053];
pub fn probably_prime<G,T>(x: &T, g: &mut G, iters: usize) -> bool
where
G: Rng,
T: Clone + PartialOrd + Rem + Sub,
T: CryptoNumBase + CryptoNumSerialization,
{
for tester in SMALL_PRIMES.iter() {
if (x % T::from_u64(*tester)) == T::zero() {
return false;
}
}
miller_rabin(g, x, iters)
}
fn miller_rabin<G,T>(g: &mut G, n: T, iters: usize) -> bool
where
G: Rng,
T: Clone + PartialEq + PartialOrd + Sub,
T: CryptoNumBase + CryptoNumSerialization,
{
let one = T::from_u8(1);
let two = T::from_u8(2);
let nm1 = n - one;
// Quoth Wikipedia:
// write n - 1 as 2^r*d with d odd by factoring powers of 2 from n - 1
let mut d = nm1.clone();
let mut r = 0;
while d.is_even() {
d >>= 1;
r += 1;
assert!(r < n.bit_size());
}
// WitnessLoop: repeat k times
'WitnessLoop: for _k in 0..iters {
// pick a random integer a in the range [2, n - 2]
let a = random_in_range(g, &two, &nm1);
// x <- a^d mod n
let mut x = modexp(&a, &d, &n);
// if x = 1 or x = n - 1 then
if (&x == &one) || (&x == &nm1) {
// continue WitnessLoop
continue 'WitnessLoop;
}
// repeat r - 1 times:
for _i in 0..r {
// x <- x^2 mod n
x = modexp(&x, &two, &n);
// if x = 1 then
if &x == &one {
// return composite
return false;
}
// if x = n - 1 then
if &x == &nm1 {
// continue WitnessLoop
continue 'WitnessLoop;
}
}
// return composite
return false;
}
// return probably prime
true
}
fn random_in_range<G,T>(rng: &mut G, min: &T, max: &T) -> T
where
G: Rng,
T: CryptoNumSerialization + PartialOrd
{
assert_eq!(min.byte_size(), max.byte_size());
loop {
let candidate = random_number(rng, min.byte_size());
if (&candidate >= min) && (&candidate < max) {
return candidate;
}
}
}
fn random_number<G,T>(rng: &mut G, bytelen: usize) -> T
where
G: Rng,
T: CryptoNumSerialization
{
let components: Vec<u8> = rng.gen_iter().take(bytelen).collect();
T::from_bytes(&components)
}

View File

@@ -1,431 +0,0 @@
use cryptonum::traits::*;
use std::cmp::Ordering;
use std::fmt::{Debug,Error,Formatter};
use std::ops::*;
pub struct Signed<T: Sized> {
positive: bool,
value: T
}
impl<T> Signed<T> {
pub fn new(v: T) -> Signed<T> {
Signed{ positive: true, value: v }
}
pub fn abs(&self) -> T
where T: Clone
{
self.value.clone()
}
pub fn is_positive(&self) -> bool
where T: CryptoNumBase
{
self.positive && !self.value.is_zero()
}
pub fn is_negative(&self) -> bool
where T: CryptoNumBase
{
!self.positive && !self.value.is_zero()
}
pub fn negate(&mut self)
{
self.positive = !self.positive;
}
}
impl<T: CryptoNumBase> CryptoNumBase for Signed<T> {
fn zero() -> Signed<T> {
Signed{ positive: true, value: T::zero() }
}
fn max_value() -> Signed<T> {
Signed{ positive: true, value: T::max_value() }
}
fn is_zero(&self) -> bool {
self.value.is_zero()
}
fn is_odd(&self) -> bool {
self.value.is_odd()
}
fn is_even(&self) -> bool {
self.value.is_even()
}
fn from_u8(x: u8) -> Signed<T> {
Signed{ positive: true, value: T::from_u8(x) }
}
fn to_u8(&self) -> u8 {
self.value.to_u8()
}
fn from_u16(x: u16) -> Signed<T> {
Signed{ positive: true, value: T::from_u16(x) }
}
fn to_u16(&self) -> u16 {
self.value.to_u16()
}
fn from_u32(x: u32) -> Signed<T> {
Signed{ positive: true, value: T::from_u32(x) }
}
fn to_u32(&self) -> u32 {
self.value.to_u32()
}
fn from_u64(x: u64) -> Signed<T> {
Signed{ positive: true, value: T::from_u64(x) }
}
fn to_u64(&self) -> u64 {
self.value.to_u64()
}
}
impl<T: CryptoNumFastMod> CryptoNumFastMod for Signed<T> {
type BarrettMu = T::BarrettMu;
fn barrett_mu(&self) -> Option<T::BarrettMu> {
if self.positive {
self.value.barrett_mu()
} else {
None
}
}
fn fastmod(&self, mu: &T::BarrettMu) -> Signed<T> {
Signed{ positive: self.positive, value: self.value.fastmod(&mu) }
}
}
impl<T: Clone> Clone for Signed<T> {
fn clone(&self) -> Signed<T> {
Signed{ positive: self.positive, value: self.value.clone() }
}
}
impl<'a,T: PartialEq> PartialEq<&'a Signed<T>> for Signed<T> {
fn eq(&self, other: &&Signed<T>) -> bool {
(self.positive == other.positive) && (self.value == other.value)
}
}
impl<'a,T: PartialEq> PartialEq<Signed<T>> for &'a Signed<T> {
fn eq(&self, other: &Signed<T>) -> bool {
(self.positive == other.positive) && (self.value == other.value)
}
}
impl<T: PartialEq> PartialEq for Signed<T> {
fn eq(&self, other: &Signed<T>) -> bool {
(self.positive == other.positive) && (self.value == other.value)
}
}
impl<T: Eq> Eq for Signed<T> {}
impl<T: Debug> Debug for Signed<T> {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
if self.positive {
f.write_str("+")?;
} else {
f.write_str("-")?;
}
self.value.fmt(f)
}
}
impl<T: Ord> Ord for Signed<T> {
fn cmp(&self, other: &Signed<T>) -> Ordering {
match (self.positive, other.positive) {
(true, true) => self.value.cmp(&other.value),
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) =>
self.value.cmp(&other.value).reverse()
}
}
}
impl<T: Ord> PartialOrd for Signed<T> {
fn partial_cmp(&self, other: &Signed<T>) -> Option<Ordering>{
Some(self.cmp(other))
}
}
//------------------------------------------------------------------------------
impl<T: Clone> Neg for Signed<T> {
type Output = Signed<T>;
fn neg(self) -> Signed<T> {
Signed {
positive: !self.positive,
value: self.value.clone()
}
}
}
impl<'a,T: Clone> Neg for &'a Signed<T> {
type Output = Signed<T>;
fn neg(self) -> Signed<T> {
Signed {
positive: !self.positive,
value: self.value.clone()
}
}
}
//------------------------------------------------------------------------------
impl<T> AddAssign for Signed<T>
where
T: Clone + Ord,
T: AddAssign + SubAssign,
{
fn add_assign(&mut self, other: Signed<T>) {
match (self.positive, other.positive, self.value.cmp(&other.value)) {
// if the signs are the same, we maintain the sign and just increase
// the magnitude
(x, y, _) if x == y =>
self.value.add_assign(other.value),
// if the signs are different and the numbers are equal, we just set
// this to zero. However, we actually do the subtraction to make the
// timing roughly similar.
(_, _, Ordering::Equal) => {
self.positive = true;
self.value.sub_assign(other.value);
}
// if the signs are different and the first one is less than the
// second, then we flip the sign and subtract.
(_, _, Ordering::Less) => {
self.positive = !self.positive;
let temp = self.value.clone();
self.value = other.value.clone();
self.value.sub_assign(temp);
}
// if the signs are different and the first one is greater than the
// second, then we leave the sign and subtract.
(_, _, Ordering::Greater) => {
self.value.sub_assign(other.value);
}
}
}
}
impl<'a,T> AddAssign<&'a Signed<T>> for Signed<T>
where
T: Clone + Ord,
T: AddAssign + SubAssign,
T: AddAssign<&'a T> + SubAssign<&'a T>
{
fn add_assign(&mut self, other: &'a Signed<T>) {
match (self.positive, other.positive, self.value.cmp(&other.value)) {
// if the signs are the same, we maintain the sign and just increase
// the magnitude
(x, y, _) if x == y =>
self.value.add_assign(&other.value),
// if the signs are different and the numbers are equal, we just set
// this to zero. However, we actually do the subtraction to make the
// timing roughly similar.
(_, _, Ordering::Equal) => {
self.positive = true;
self.value.sub_assign(&other.value);
}
// if the signs are different and the first one is less than the
// second, then we flip the sign and subtract.
(_, _, Ordering::Less) => {
self.positive = !self.positive;
let temp = self.value.clone();
self.value = other.value.clone();
self.value.sub_assign(temp);
}
// if the signs are different and the first one is greater than the
// second, then we leave the sign and subtract.
(_, _, Ordering::Greater) => {
self.value.sub_assign(&other.value);
}
}
}
}
math_operator!(Add,add,add_assign);
//------------------------------------------------------------------------------
impl<T> SubAssign for Signed<T>
where
T: Clone + Ord,
T: AddAssign + SubAssign,
{
fn sub_assign(&mut self, other: Signed<T>) {
let mut other2 = other.clone();
other2.positive = !other.positive;
self.add_assign(other2);
}
}
impl<'a,T> SubAssign<&'a Signed<T>> for Signed<T>
where
T: Clone + Ord,
T: AddAssign + SubAssign,
T: AddAssign<&'a T> + SubAssign<&'a T>
{
fn sub_assign(&mut self, other: &'a Signed<T>) {
let mut other2 = other.clone();
other2.positive = !other.positive;
self.add_assign(other2);
}
}
math_operator!(Sub,sub,sub_assign);
//------------------------------------------------------------------------------
impl<T> MulAssign for Signed<T>
where
T: MulAssign
{
fn mul_assign(&mut self, other: Signed<T>) {
self.positive = !(self.positive ^ other.positive);
self.value *= other.value;
}
}
impl<'a,T> MulAssign<&'a Signed<T>> for Signed<T>
where
T: MulAssign + MulAssign<&'a T>
{
fn mul_assign(&mut self, other: &'a Signed<T>) {
self.positive = !(self.positive ^ other.positive);
self.value *= &other.value;
}
}
math_operator!(Mul,mul,mul_assign);
//------------------------------------------------------------------------------
impl<T> DivAssign for Signed<T>
where
T: DivAssign
{
fn div_assign(&mut self, other: Signed<T>) {
self.positive = !(self.positive ^ other.positive);
self.value /= other.value;
}
}
impl<'a,T> DivAssign<&'a Signed<T>> for Signed<T>
where
T: DivAssign + DivAssign<&'a T>
{
fn div_assign(&mut self, other: &'a Signed<T>) {
self.positive = !(self.positive ^ other.positive);
self.value /= &other.value;
}
}
math_operator!(Div,div,div_assign);
//------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use cryptonum::unsigned::U512;
use quickcheck::{Arbitrary,Gen};
use std::cmp::{max,min};
use super::*;
impl<T: Arbitrary + CryptoNumBase> Arbitrary for Signed<T> {
fn arbitrary<G: Gen>(g: &mut G) -> Signed<T> {
let value = T::arbitrary(g);
if value.is_zero() {
Signed {
positive: true,
value: value
}
} else {
Signed {
positive: g.gen_weighted_bool(2),
value: value
}
}
}
}
quickcheck! {
fn double_negation(x: Signed<U512>) -> bool {
&x == (- (- &x))
}
}
quickcheck! {
fn add_associates(x: Signed<U512>, y: Signed<U512>, z: Signed<U512>)
-> bool
{
let mut a = x.clone();
let mut b = y.clone();
let mut c = z.clone();
// we shift these right because rollover makes for weird behavior
a.value >>= 2;
b.value >>= 2;
c.value >>= 2;
(&a + (&b + &c)) == ((&a + &b) + &c)
}
fn add_commutes(x: Signed<U512>, y: Signed<U512>) -> bool {
(&x + &y) == (&y + &x)
}
fn add_identity(x: Signed<U512>) -> bool {
let zero = Signed{ positive: true, value: U512::zero() };
(&x + &zero) == &x
}
}
quickcheck! {
fn sub_is_add_negation(x: Signed<U512>, y: Signed<U512>) -> bool {
(&x - &y) == (&x + (- &y))
}
}
quickcheck! {
fn mul_associates(x: Signed<U512>, y: Signed<U512>, z: Signed<U512>)
-> bool
{
let mut a = x.clone();
let mut b = y.clone();
let mut c = z.clone();
// we shift these right because rollover makes for weird behavior
a.value >>= 258;
b.value >>= 258;
c.value >>= 258;
(&a * (&b * &c)) == ((&a * &b) * &c)
}
fn mul_commutes(x: Signed<U512>, y: Signed<U512>) -> bool {
(&x * &y) == (&y * &x)
}
fn mul_identity(x: Signed<U512>) -> bool {
let one = Signed{ positive: true, value: U512::from_u8(1) };
(&x * &one) == &x
}
}
quickcheck! {
fn add_mul_distribution(x:Signed<U512>,y:Signed<U512>,z:Signed<U512>)
-> bool
{
let mut a = x.clone();
let mut b = y.clone();
let mut c = z.clone();
// we shift these right because rollover makes for weird behavior
a.value >>= 258;
b.value >>= 258;
c.value >>= 258;
(&a * (&b + &c)) == ((&a * &b) + (&a * &c))
}
}
}

View File

@@ -1,58 +0,0 @@
pub trait CryptoNumBase {
/// Generate the zero value for this type.
fn zero() -> Self;
/// Generate the maximum possible value for this type.
fn max_value() -> Self;
/// Test if the number is zero.
fn is_zero(&self) -> bool;
/// Test if the number is odd (a.k.a., the low bit is set)
fn is_odd(&self) -> bool;
/// Test if the number is even (a.k.a., the low bit is clear)
fn is_even(&self) -> bool;
/// Translate a `u8` to this type. This must be safe.
fn from_u8(x: u8) -> Self;
/// Convert this back into a `u8`. This is the equivalent of masking off
/// the lowest 8 bits and then casting to a `u8`.
fn to_u8(&self) -> u8;
/// Translate a `u16` to this type. This must be safe.
fn from_u16(x: u16) -> Self;
/// Convert this back into a `u16`. This is the equivalent of masking off
/// the lowest 16 bits and then casting to a `u16`.
fn to_u16(&self) -> u16;
/// Translate a `u32` to this type. This must be safe.
fn from_u32(x: u32) -> Self;
/// Convert this back into a `u32`. This is the equivalent of masking off
/// the lowest 32 bits and then casting to a `u32`.
fn to_u32(&self) -> u32;
/// Translate a `u64` to this type. This must be safe.
fn from_u64(x: u64) -> Self;
/// Convert this back into a `u64`. This is the equivalent of masking off
/// the lowest 64 bits and then casting to a `u64`.
fn to_u64(&self) -> u64;
}
pub trait CryptoNumSerialization {
/// The number of bits used when this number is serialized.
fn bit_size(&self) -> usize;
/// The number of bytes used when this number is serialized.
fn byte_size(&self) -> usize;
/// Convert a number to a series of bytes, in standard order (most to
/// least significant)
fn to_bytes(&self) -> Vec<u8>;
/// Convert a series of bytes into the number. The size of the given slice
/// must be greater than or equal to the size of the number, and must be
/// a multiple of 8 bytes long. Unused bytes should be ignored.
fn from_bytes(&[u8]) -> Self;
}
pub trait CryptoNumFastMod {
/// A related type that can hold the constant required for Barrett
/// reduction.
type BarrettMu;
/// Compute the Barett constant mu, using this as a modulus, which we can
/// use later to perform faster mod operations.
fn barrett_mu(&self) -> Option<Self::BarrettMu>;
/// Faster modulo through the use of the Barrett constant, above.
fn fastmod(&self, &Self::BarrettMu) -> Self;
}

View File

@@ -1,14 +0,0 @@
use cryptonum::core::*;
use cryptonum::traits::*;
use std::cmp::Ordering;
use std::fmt::{Debug,Error,Formatter};
use std::ops::*;
construct_unsigned!(U512, BarretMu512, u512, 8);
construct_unsigned!(U1024, BarretMu1024, u1024, 16);
construct_unsigned!(U2048, BarretMu2048, u2048, 32);
construct_unsigned!(U3072, BarretMu3072, u3072, 48);
construct_unsigned!(U4096, BarretMu4096, u4096, 64);
construct_unsigned!(U7680, BarretMu7680, u7680, 120);
construct_unsigned!(U8192, BarretMu8192, u8192, 128);
construct_unsigned!(U15360, BarretMu15360, u15360, 240);