예제 #1
0
        public static string ByteArrayToBase58(this byte[] ba)
        {
            byte[] tmp = ba;
            Array.Reverse(tmp);
            byte[] positiveBa;
            if (tmp[tmp.Length - 1] >= 0x80)
            {
                positiveBa = new byte[ba.Length + 1];
                Array.Copy(tmp, positiveBa, tmp.Length);
            }
            else positiveBa = tmp;

            BigInteger addrremain = new BigInteger(positiveBa);
            if (addrremain<0) throw new Exception("Negative? I wont positive");

            StringBuilder rv = new StringBuilder(100);

            while (addrremain.CompareTo(BigInteger.Zero) > 0)
            {
                var remainder = addrremain % 58;
                addrremain    = addrremain / 58;
                rv.Insert(0, B58[(int) remainder]);
            }

            // handle leading zeroes
            foreach (byte b in ba)
            {
                if (b != 0) break;
                rv = rv.Insert(0, '1');
            }
            string result = rv.ToString();
            return result;
        }
예제 #2
0
        public static string Encode(byte[] plaintext)
        {
            ContractsCommon.NotNull(plaintext, "plaintext");
            ContractsCommon.ResultIsNonNull<string>();

            var plaintextArr = new byte[plaintext.Length + 1];
            Array.Copy(plaintext, 0, plaintextArr, 1, plaintext.Length);
            Array.Reverse(plaintextArr);
            var workingValue = new BigInteger(plaintextArr);
            StringBuilder sb = new StringBuilder(plaintext.Length * 138 / 100 + 1);
            while (workingValue.CompareTo(BigInteger.Zero) > 0)
            {
                BigInteger remainder;
                workingValue = BigInteger.DivRem(workingValue, Base, out remainder);
                sb.Append(Alphabet[(int)remainder]);
            }
            Contract.Assert(workingValue.Sign >= 0);
            //sb.Insert(0, Alphabet[(int)workingValue]);

            for (int i = 0; i < plaintext.Length && plaintext[i] == 0; ++i)
            {
                sb.Append(Alphabet[0]);
            }

            var retVal = new char[sb.Length];
            sb.CopyTo(0, retVal, 0, sb.Length);
            Array.Reverse(retVal);
            return new string(retVal);
        }
        /**
         * An implementation of the RSASP method: Assuming that the designated
         * RSA private key is a valid one, this method computes a signature
         * representative for a designated message representative signed
         * by the holder of the designated RSA private key.
         * 
         * @param K the RSA private key.
         * @param m the message representative: an integer between
         *          0 and n - 1, where n
         *          is the RSA modulus.
         * @return the signature representative, an integer between
         *         0 and n - 1, where n
         *         is the RSA modulus.
         */
        public static BigInteger RSASP1(RSAKey K, BigInteger m)
        {
            // 1. If the representative c is not between 0 and n - 1, output
            // "representative out of range" and stop.
            BigInteger n = K.getModulus();
            if (m.CompareTo(BigInteger.Zero) < 0 || m.CompareTo(n - BigInteger.One) > 0)
                throw new ArgumentException();
            // 2. The representative m is computed as follows.
            BigInteger result;
            // a. If the first form (n, d) of K is used, let m = c^d mod n.
            BigInteger d = K.getExponent();
            result = BigInteger.ModPow(m, d, n);

            // 3. Output m
            return result;
        }
예제 #4
0
 private static void PortableDigitCount(BigInteger bi)
 {
     int kb=0;
     if(!bi.IsZero){
       while(true){
     if(bi.CompareTo((BigInteger)Int32.MaxValue)<=0) {
       int tmp = (int)bi;
       while (tmp > 0) {
         kb++;
         tmp /= 10;
       }
       kb=(kb == 0 ? 1 : kb);
       return kb;
     }
     BigInteger q=bi/(BigInteger)bidivisor;
     if(q.IsZero){
       int b=(int)bi;
       while(b>0){
         kb++;
         b/=10;
       }
       break;
     } else {
       kb+=4;
       bi=q;
     }
       }
     } else {
       kb=1;
     }
     return kb;
 }
예제 #5
0
 public bool VerifySignature(byte[] message, BigInteger r, BigInteger s)
 {
     if (r.Sign < 1 || s.Sign < 1 || r.CompareTo(curve.N) >= 0 || s.CompareTo(curve.N) >= 0)
         return false;
     BigInteger e = CalculateE(curve.N, message);
     BigInteger c = s.ModInverse(curve.N);
     BigInteger u1 = (e * c).Mod(curve.N);
     BigInteger u2 = (r * c).Mod(curve.N);
     ECPoint point = SumOfTwoMultiplies(curve.G, u1, publicKey, u2);
     BigInteger v = point.X.Value.Mod(curve.N);
     return v.Equals(r);
 }
예제 #6
0
파일: JValue.cs 프로젝트: zha0/Cerberus
        // Token: 0x06001410 RID: 5136 RVA: 0x00069CE8 File Offset: 0x00067EE8
        private static int CompareBigInteger(System.Numerics.BigInteger i1, object i2)
        {
            int num = i1.CompareTo(ConvertUtils.ToBigInteger(i2));

            if (num != 0)
            {
                return(num);
            }
            if (i2 is decimal)
            {
                decimal num2 = (decimal)i2;
                return(0m.CompareTo(Math.Abs(num2 - Math.Truncate(num2))));
            }
            if (i2 is double || i2 is float)
            {
                double num3 = Convert.ToDouble(i2, CultureInfo.InvariantCulture);
                return(0.0.CompareTo(Math.Abs(num3 - Math.Truncate(num3))));
            }
            return(num);
        }
예제 #7
0
 public RSA()
 {
     r = new Random();
     List<int> primeP;
     List<int> primeQ;
     List<int> primeE;
     int Prandom = r.Next(200000);
     int Qrandom = r.Next(200000);
     int Erandom = r.Next(200000);
     primeP = GeneratePrimes(Prandom);
     primeQ = GeneratePrimes(Qrandom);
     primeE = GeneratePrimes(Erandom);
     p = primeP[primeP.Count-1];
     q = primeQ[primeQ.Count - 1];
     N = BigInteger.Multiply(p,q);
     phi =BigInteger.Multiply( BigInteger.Subtract(p,BigInteger.One),(BigInteger.Subtract(q,BigInteger.One)));
     e = primeE[primeE.Count - 1];
     while (BigInteger.GreatestCommonDivisor(phi, e).CompareTo(BigInteger.One) > 0 && e.CompareTo(phi) < 0)
     {
     BigInteger.Add(e, BigInteger.One);
     }
        // d = e.modInverse(phi);
     d= BigInteger.ModPow(1/e,1,phi);
 }
예제 #8
0
 public static BigInteger Pow(BigInteger x, BigInteger y)
 {
     if (y.CompareTo(BigInteger.Zero) < 0)
         throw new ArgumentException();
     BigInteger z = x; // z will successively become x^2, x^4, x^8, x^16, x^32...
     BigInteger result = BigInteger.One;
     byte[] bytes = y.ToByteArray();
     for (int i = bytes.Length - 1; i >= 0; i--)
     {
         byte bits = bytes[i];
         for (int j = 0; j < 8; j++)
         {
             if ((bits & 1) != 0)
                 result = BigInteger.Multiply(result, z);
             // short cut out if there are no more bits to handle:
             if ((bits >>= 1) == 0 && i == 0)
                 return result;
             z = BigInteger.Multiply(z, z);
         }
     }
     return result;
 }
예제 #9
0
 private static void WritePortable(BigInteger bigint, Stream s)
 {
     if((s)==null)throw new ArgumentNullException("s");
       if((object)bigint==(object)null){
     s.WriteByte(0xf6);
     return;
       }
       int datatype=0;
       if(bigint.Sign<0){
     datatype=1;
     bigint+=(BigInteger)BigInteger.One;
     bigint=-(BigInteger)bigint;
       }
       if(bigint.CompareTo(Int64MaxValue)<=0){
     // If the big integer is representable as a long and in
     // major type 0 or 1, write that major type
     // instead of as a bignum
     long ui=(long)(BigInteger)bigint;
     WritePositiveInt64(datatype,ui,s);
       } else {
     using(MemoryStream ms=new MemoryStream()){
       long tmp=0;
       byte[] buffer=new byte[10];
       while(bigint.Sign>0){
     // To reduce the number of big integer
     // operations, extract the big int 56 bits at a time
     // (not 64, to avoid negative numbers)
     BigInteger tmpbigint=bigint&(BigInteger)FiftySixBitMask;
     tmp=(long)(BigInteger)tmpbigint;
     bigint>>=56;
     bool isNowZero=(bigint.IsZero);
     int bufferindex=0;
     for(int i=0;i<7 && (!isNowZero || tmp>0);i++){
       buffer[bufferindex]=(byte)(tmp&0xFF);
       tmp>>=8;
       bufferindex++;
     }
     ms.Write(buffer,0,bufferindex);
       }
       byte[] bytes=ms.ToArray();
       switch(bytes.Length){
     case 1: // Fits in 1 byte (won't normally happen though)
       buffer[0]=(byte)((datatype<<5)|24);
       buffer[1]=bytes[0];
       s.Write(buffer,0,2);
       break;
     case 2: // Fits in 2 bytes (won't normally happen though)
       buffer[0]=(byte)((datatype<<5)|25);
       buffer[1]=bytes[1];
       buffer[2]=bytes[0];
       s.Write(buffer,0,3);
       break;
     case 3:
     case 4:
       buffer[0]=(byte)((datatype<<5)|26);
       buffer[1]=(bytes.Length>3) ? bytes[3] : (byte)0;
       buffer[2]=bytes[2];
       buffer[3]=bytes[1];
       buffer[4]=bytes[0];
       s.Write(buffer,0,5);
       break;
     case 5:
     case 6:
     case 7:
     case 8:
       buffer[0]=(byte)((datatype<<5)|27);
       buffer[1]=(bytes.Length>7) ? bytes[7] : (byte)0;
       buffer[2]=(bytes.Length>6) ? bytes[6] : (byte)0;
       buffer[3]=(bytes.Length>5) ? bytes[5] : (byte)0;
       buffer[4]=bytes[4];
       buffer[5]=bytes[3];
       buffer[6]=bytes[2];
       buffer[7]=bytes[1];
       buffer[8]=bytes[0];
       s.Write(buffer,0,9);
       break;
     default:
       s.WriteByte((datatype==0) ?
                   (byte)0xC2 :
                   (byte)0xC3);
       WritePositiveInt(2,bytes.Length,s);
       for(int i=bytes.Length-1;i>=0;i--){
         s.WriteByte(bytes[i]);
       }
       break;
       }
     }
       }
 }
예제 #10
0
	    /**
	     * Raise a BigInteger to a BigInteger power.
	     *
	     * @param k Number to raise.
	     * @param e Exponent (must be positive or zero).
	     * @return k<sup>e</sup>
	     * @throws NotPositiveException if {@code e < 0}.
	     */
		//TODO: Implement this with an efficient algorithm which doesn't rely on the missing BigInteger functions
	    public static BigInteger pow(BigInteger k, BigInteger e) {
	        if (e.CompareTo(BigInteger.Zero) < 0) {
	            throw new NotPositiveException<BigInteger>(LocalizedFormats.EXPONENT, e);
	        }
	
	        BigInteger result = BigInteger.One;
	        //BigInteger k2p    = k;
			
			BigInteger incrementer = e;
			while(!BigInteger.Zero.Equals(incrementer)) {
				result = BigInteger.Multiply(result,k);
				incrementer = BigInteger.Subtract(incrementer,1);
			}

//	        while (!BigInteger.Zero.Equals(e)) {
//	            if (e.testBit(0)) {
//	                result = result.multiply(k2p);
//	            }
//	            k2p = k2p.multiply(k2p);
//	            e = e.shiftRight(1);
//	        }
	
	        return result;
	    }
예제 #11
0
        // size is size in bits
        private BigInteger GenerateRandomLargePrime(BigInteger min, BigInteger max, uint size)
        {
            bool IsPrime = false;
            BigInteger p = new BigInteger();
            do
            {
                var rng = new RNGCryptoServiceProvider();
                byte[] bytes = new byte[size / 8];
                do
                {
                    rng.GetBytes(bytes);
                    p = new BigInteger(bytes);
                    if (p < 0)
                    {
                        p = BigInteger.Negate(p);
                    }
                }
                while (0 > p.CompareTo(min) || 0 < p.CompareTo(max));

                if (IsProbablePrime(p, 100))
                    IsPrime = true;
            } while (!IsPrime);

            return p;
        }
예제 #12
0
		public void IComparable () {
			var a = new BigInteger (99);
			Assert.AreEqual (-1, a.CompareTo (100), "#1");
			Assert.AreEqual (1, a.CompareTo (null), "#2");
		}
예제 #13
0
		public void CompareLong () {
			long[] values = new long [] { -100000000000L, -1000, -1, 0, 1, 1000, 9999999, 100000000000L, 0xAA00000000, long.MaxValue, long.MinValue };

			for (int i = 0; i < values.Length; ++i) {
				for (int j = 0; j < values.Length; ++j) {
					var a = new BigInteger (values [i]);
					var b = values [j];
					var c = new BigInteger (b);
					
					Assert.AreEqual (a.CompareTo (c), a.CompareTo (b), "#a_" + i + "_" + j);

					Assert.AreEqual (a > c, a > b, "#b_" + i + "_" + j);
					Assert.AreEqual (a < c, a < b, "#c_" + i + "_" + j);
					Assert.AreEqual (a <= c, a <= b, "#d_" + i + "_" + j);
					Assert.AreEqual (a == c, a == b, "#e_" + i + "_" + j);
					Assert.AreEqual (a != c, a != b, "#f_" + i + "_" + j);
					Assert.AreEqual (a >= c, a >= b, "#g_" + i + "_" + j);

					Assert.AreEqual (c > a, b > a, "#ib_" + i + "_" + j);
					Assert.AreEqual (c < a, b < a, "#ic_" + i + "_" + j);
					Assert.AreEqual (c <= a, b <= a, "#id_" + i + "_" + j);
					Assert.AreEqual (c == a, b == a, "#ie_" + i + "_" + j);
					Assert.AreEqual (c != a, b != a, "#if_" + i + "_" + j);
					Assert.AreEqual (c >= a, b >= a, "#ig_" + i + "_" + j);
				}
			}
		}
예제 #14
0
		public void CompareOps2 () {
			BigInteger a = new BigInteger (100000000000L);
			BigInteger b = new BigInteger (28282828282UL);

			Assert.IsTrue (a >= b, "#1");
			Assert.IsTrue (a >= b, "#2");
			Assert.IsFalse (a < b, "#3");
			Assert.IsFalse (a <= b, "#4");
			Assert.AreEqual (1, a.CompareTo (b), "#5");
		}
예제 #15
0
		public void CompareOps () {
			long[] values = new long [] { -100000000000L, -1000, -1, 0, 1, 1000, 100000000000L };
			for (int i = 0; i < values.Length; ++i) {
				for (int j = 0; j < values.Length; ++j) {
					var a = new BigInteger (values [i]);
					var b = new BigInteger (values [j]);
					
					Assert.AreEqual (values [i].CompareTo (values [j]), a.CompareTo (b), "#a_" + i + "_" + j);
					Assert.AreEqual (values [i].CompareTo (values [j]), BigInteger.Compare (a, b), "#b_" + i + "_" + j);

					Assert.AreEqual (values [i] < values [j], a < b, "#c_" + i + "_" + j);
					Assert.AreEqual (values [i] <= values [j], a <= b, "#d_" + i + "_" + j);
					Assert.AreEqual (values [i] == values [j], a == b, "#e_" + i + "_" + j);
					Assert.AreEqual (values [i] != values [j], a != b, "#f_" + i + "_" + j);
					Assert.AreEqual (values [i] >= values [j], a >= b, "#g_" + i + "_" + j);
					Assert.AreEqual (values [i] > values [j], a > b, "#h_" + i + "_" + j);
				}
			}
		}
 /**
  * An implementation of the RSAVP method: Assuming that the designated
  * RSA public key is a valid one, this method computes a message
  * representative for the designated signature representative
  * generated by an RSA private key, for a message intended for the holder of
  * the designated RSA public key.
  * 
  * @param K the RSA public key.
  * @param s the signature representative, an integer between
  *          0 and n - 1, where n is the RSA modulus.
  * @return a message representative: an integer between 0
  *         and n - 1, where n is the RSA modulus.
  */
 public static BigInteger RSAVP1(RSAKey K, BigInteger s)
 {
     // 1. If the representative m is not between 0 and n - 1, output
     // "representative out of range" and stop.
     BigInteger n = K.getModulus();
     if (s.CompareTo(BigInteger.Zero) < 0 || s.CompareTo(n - BigInteger.One) > 0)
         throw new ArgumentException();
     // 2. Let c = m^e mod n.
     BigInteger e = K.getExponent();
     BigInteger result = BigInteger.ModPow(s, e, n); ;
     // 3. Output c.
     return result;
 }
예제 #17
0
파일: PrimeNumber.cs 프로젝트: iSvB/Crypto
 /// <summary>
 /// Осуществляет поиск простого числа, путём перебора всех числел, начиная с <code>value</code> до 
 /// <code>border</code> с шагом равным 2 по модулю.
 /// </summary>
 /// <param name="value">Начальное значение.</param>
 /// <param name="border">Граница интервала, в сторону которой будем двигатся.</param>
 /// <returns>Простое число, либо -1, если на заданном интервале нет простых чисел.</returns>
 private static BigInteger MoveToPrime(BigInteger value, BigInteger border, double probability)
 {
     int summand = (border >= value) ? 2 : -2;
     int compareResult = (summand > 0) ? -1 : 1;
     while (value.CompareTo(border) == compareResult)
     {
         value += summand;
         if (IsPrime(value, probability))
             return value;
     }
     return BigInteger.MinusOne;
 }
예제 #18
0
 /// <summary>
 /// Check whether the integer represented is 0
 /// </summary>
 /// <returns> True is the integer represented is 0. False otherwise </returns>
 public override bool zero()
 {
     return(_value.CompareTo(System.Numerics.BigInteger.Zero) == 0);
 }