public void TestGetLengthBigInteger(int valueInt, int expectedBitLength) { var value = new BigInteger(valueInt); var result = NumberLength.GetLength(value).InBits; Assert.AreEqual(expectedBitLength, result); }
/// <summary> /// Multiplies a group element with a scalar factor. /// /// Scalar multiplication is understood as adding the group element to itself /// as many times as dictated by the scalar factor. /// /// The optional parameter factorBitLength allows to specify the bit length /// of the scalar, which increases performance if it is significantly below /// that of the order. However, this value should be held constant over /// subsequent calls to this method to discourage timing and other side channel /// attacks. /// </summary> /// <param name="e">A group element.</param> /// <param name="k">A scalar.</param> /// <param name="factorBitLength">Maximum bit length of a scalar.</param> /// <returns>The given element multiplied with the given scalar.</returns> public T MultiplyScalar(T e, BigInteger k, int factorBitLength) { if (k < BigInteger.Zero) { throw new ArgumentOutOfRangeException(nameof(k), "The given factor must be non-negative."); } if (NumberLength.GetLength(k).InBits > factorBitLength) { throw new ArgumentOutOfRangeException(nameof(k), "The given factor must not exceed the admittable factor bit length."); } return(MultiplyScalarUnchecked(e, k, factorBitLength)); }
/// <summary> /// Returns a random <see cref="BigInteger"/> between (and including) /// <paramref name="lower"/> and <paramref name="upper"/>. /// </summary> /// <returns>The <see cref="T:System.Numerics.BigInteger"/>.</returns> /// <param name="randomNumberGenerator">Random number generator.</param> /// <param name="lower">Inclusive lower bound.</param> /// <param name="upper">Inclusive upper bound.</param> public static BigInteger GetBigIntegerBetween( this RandomNumberGenerator randomNumberGenerator, BigInteger lower, BigInteger upper ) { NumberLength length = NumberLength.GetLength(upper - lower); BigInteger delta; do { byte[] buffer = new byte[length.InBytes]; randomNumberGenerator.GetBytes(buffer); delta = new BigInteger(buffer); }while (delta >= upper - lower); delta *= delta.Sign; Debug.Assert(delta >= BigInteger.Zero); return(lower + delta); }
/// <inheritdoc/> public bool IsSafeElement(T element) { if (!IsPotentialElement(element)) { return(false); } // verifying that the point is not from a small subgroup of the whole curve (and thus outside // of the safe subgroup over which operations are considered) T check = MultiplyScalarUnchecked(element, Cofactor, NumberLength.GetLength(Cofactor).InBits); if (check.Equals(NeutralElement)) { return(false); } return(true); }