Example #1
0
		public DSAPrivateKeySpec (BigInteger x, BigInteger p, BigInteger q, BigInteger g)
		{
			this.x = x;
			this.p = p;
			this.q = q;
			this.g = g;
		}
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.String) { return null; }
            var decrypted = (MCrypto)base.ReadJson(reader, objectType, existingValue, serializer);
            var rsa_privk = new BigInteger[4];
            var bytes = decrypted.Value;
            int startindex = 0;
            for (var i = 0; i < 4; i++)
            {
                var l = ((bytes[startindex + 0] * 256 + bytes[startindex + 1] + 7) >> 3) + 2;
                rsa_privk[i] = Converter.MpiToBigInt(bytes, startindex, l);
                startindex += l;
            }

            if (bytes.Length - startindex < 16)
            {
                return new RSAKey
                {
                    P = rsa_privk[0],
                    Q = rsa_privk[1],
                    D = rsa_privk[2],
                    U = rsa_privk[3],
                    N = BigInteger.Multiply(rsa_privk[0], rsa_privk[1])
                };
            }
            else return null;
        }
		public Bitwise_Base() 
		{
			N = new BigInteger(n);
			expectedNls = new BigInteger(ExpectedNLeftShift);
			expectedNrs = new BigInteger(ExpectedNRightShift);
			shiftAmount = ShiftAmount;
		}
Example #4
0
        /* get plaintext using biginteger class. This is required because default int cannot handle large modpow function */
        public byte[] getMyPlainText(int [] a, int d, int n)
        {
            int l = a.Length;

            byte [] r = new byte[l];

            for (int i = 0; i < a.Length; i++)
            {
                int temp = a[i];

                /* if temp=199 which represents blankspace, handle it differently */
                if (temp == 199 || temp == 200 || temp == 201)
                {
                    r[i] = (byte)temp;
                    continue;
                }

                Mono.Math.BigInteger bi = temp;
                bi = bi.ModPow(d, n);
                string tempString = bi.ToString();
                int    g          = Int32.Parse(tempString);
                r[i] = (byte)g;
            }

            return(r);
        }
Example #5
0
        public void Test()
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            byte[] blob = rsa.ExportCspBlob(false);
            RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider();

            rsa_pub.ImportCspBlob(blob);
            CertificateMaker cm = new CertificateMaker("United States", "UFL",
                                                       "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub,
                                                       "brunet:node:abcdefghijklmnopqrs");

            Assert.AreEqual("C=United States, O=UFL, OU=ACIS, CN=David Wolinsky, [email protected]", cm.Subject.DN, "DN test 1");
            cm = new CertificateMaker(cm.UnsignedData);
            Assert.AreEqual("C=United States, O=UFL, OU=ACIS, CN=David Wolinsky, [email protected]", cm.Subject.DN, "DN test 2");

            Certificate cert = cm.Sign(cm, rsa);

            Assert.IsTrue(cert.Signature != null, "Signature");
            Assert.AreEqual(cm.Subject.DN, cert.Issuer.DN, "Issuer = Subject");
            Assert.AreEqual("brunet:node:abcdefghijklmnopqrs", cert.NodeAddress, "Node address");

            Mono.Math.BigInteger rsa_pub_bi  = new Mono.Math.BigInteger(rsa_pub.ExportCspBlob(false));
            Mono.Math.BigInteger cert_pub_bi = new Mono.Math.BigInteger(cert.PublicKey.ExportCspBlob(false));
            Assert.AreEqual(rsa_pub_bi, cert_pub_bi, "Key");

            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            Assert.AreEqual(MemBlock.Reference(cert.SerialNumber),
                            MemBlock.Reference(sha1.ComputeHash(cert.UnsignedData)),
                            "SerialNumber == hash of unsigned data");
        }
Example #6
0
		public void ModPow_0_Even ()
		{
			BigInteger x = new BigInteger (1);
			BigInteger y = new BigInteger (0);
			BigInteger z = x.ModPow (y, 1024);
			Assert.AreEqual ("1", z.ToString (), "1 pow 0 == 1");
		}
Example #7
0
		public DSAPublicKeySpec (BigInteger y, BigInteger p, BigInteger q, BigInteger g)
		{
			this.y = y;
			this.p = p;
			this.q = q;
			this.g = g;
		}
Example #8
0
        static void Main(string[] args)
        {
            Datacenter datacenterController = new Datacenter();

              var i = new BigInteger(8798782624624);
              Console.WriteLine(i);
              Console.ReadLine();
        }
            public void BarrettReduction(BigInteger x)
            {
                var n = mod;
                uint k = n.length,
                    kPlusOne = k + 1,
                    kMinusOne = k - 1;

                // x < mod, so nothing to do.
                if (x.length < k) return;

                BigInteger q3;

                //
                // Validate pointers
                //
                if (x.data.Length < x.length) throw new IndexOutOfRangeException("x out of range");

                // q1 = x / b^ (k-1)
                // q2 = q1 * constant
                // q3 = q2 / b^ (k+1), Needs to be accessed with an offset of kPlusOne

                // TODO: We should the method in HAC p 604 to do this (14.45)
                q3 = new BigInteger(Sign.Positive, x.length - kMinusOne + constant.length);
                Kernel.Multiply(x.data, kMinusOne, x.length - kMinusOne, constant.data, 0, constant.length, q3.data, 0);

                // r1 = x mod b^ (k+1)
                // i.e. keep the lowest (k+1) words

                var lengthToCopy = x.length > kPlusOne ? kPlusOne : x.length;

                x.length = lengthToCopy;
                x.Normalize();

                // r2 = (q3 * n) mod b^ (k+1)
                // partial multiplication of q3 and n

                var r2 = new BigInteger(Sign.Positive, kPlusOne);
                Kernel.MultiplyMod2p32pmod(q3.data, (int) kPlusOne, (int) q3.length - (int) kPlusOne, n.data, 0,
                    (int) n.length, r2.data, 0, (int) kPlusOne);

                r2.Normalize();

                if (r2 <= x)
                {
                    Kernel.MinusEq(x, r2);
                }
                else
                {
                    var val = new BigInteger(Sign.Positive, kPlusOne + 1);
                    val.data[kPlusOne] = 0x00000001;

                    Kernel.MinusEq(val, r2);
                    Kernel.PlusEq(x, val);
                }

                while (x >= n)
                    Kernel.MinusEq(x, n);
            }
 public void WikipediaSanityChecks()
 {
     // http://en.wikipedia.org/wiki/RSA on 25 May 2009
     var c = new BigInteger(855);
     var d = new BigInteger(2753);
     var n = new BigInteger(3233);
     var m = c.ModPow(d, n);
     Assert.AreEqual("123", m.ToString());           
 }
Example #11
0
 public SignedBigInteger(long a)
 {
     if (a < 0)
     {
         this.Negative = true;
         a *= -1;
     }
     this.Number = new BigInteger((ulong)a);
 }
Example #12
0
 public SignedBigInteger(int a)
 {
     if (a < 0)
     {
         this.Negative = true;
         a *= -1;
     }
     this.Number = new BigInteger(a);
 }
Example #13
0
        private void GenerateKeyPair()
        {
            // p and q values should have a length of half the strength in bits
            int pbitlength = ((KeySize + 1) >> 1);
            int qbitlength = (KeySize - pbitlength);
            const uint uint_e = 17;
            e = uint_e; // fixed

            // generate p, prime and (p-1) relatively prime to e
            for (; ; )
            {
                p = BigInteger.GeneratePseudoPrime(pbitlength);
                if (p % uint_e != 1)
                    break;
            }
            // generate a modulus of the required length
            for (; ; )
            {
                // generate q, prime and (q-1) relatively prime to e,
                // and not equal to p
                for (; ; )
                {
                    q = BigInteger.GeneratePseudoPrime(qbitlength);
                    if ((q % uint_e != 1) && (p != q))
                        break;
                }

                // calculate the modulus
                n = p * q;
                if (n.BitCount() == KeySize)
                    break;

                // if we get here our primes aren't big enough, make the largest
                // of the two p and try again
                if (p < q)
                    p = q;
            }

            BigInteger pSub1 = (p - 1);
            BigInteger qSub1 = (q - 1);
            BigInteger phi = pSub1 * qSub1;

            // calculate the private exponent
            d = e.ModInverse(phi);

            // calculate the CRT factors
            dp = d % pSub1;
            dq = d % qSub1;
            qInv = q.ModInverse(p);

            keypairGenerated = true;
            isCRTpossible = true;

            if (KeyGenerated != null)
                KeyGenerated(this, null);
        }
		public ModRing_Base() 
		{
			A = new BigInteger( a );
			B = new BigInteger( b );
			N = new BigInteger( n );
			abModN = new BigInteger( ExpectedABmodN );
			aPowBmodN = new BigInteger( ExpectedApowBmodN );

			mr = new BigInteger.ModulusRing(N);
		}
 /// <summary>
 /// Performs the RSA operation Result = <paramref name="message"/>^<paramref name="exponent"/> (mod <paramref name="modulus"/>).
 /// </summary>
 /// <param name="message">The message to perform the operation on.</param>
 /// <param name="exponent">The exponent value to raise the message by.</param>
 /// <param name="modulus">The modulus to divide the results by.</param>
 /// <returns>The value C, such that C = <paramref name="message"/>^<paramref name="exponent"/> (mod <paramref name="modulus"/>).</returns>
 public static byte[] PublicKeyOperation(byte[] message, byte[] exponent, byte[] modulus)
 {
     var m = new BigInteger(message);
     var e = new BigInteger(exponent);
     var n = new BigInteger(modulus);
     var c = m.ModPow(e, n);
     var resultBytes = c.GetBytes();
     
     return resultBytes;
 }
Example #16
0
        public static BigInteger Power(this BigInteger a, BigInteger b)
        {
            BigInteger value = 1;

              for (BigInteger count = 0; count < b; count += 1)
              {
            value *= a;
              }

              return value;
        }
Example #17
0
		public void DefaultRandom () 
		{
			// based on bugzilla entry #68452
			BigInteger bi = new BigInteger ();
			Assert.AreEqual (0, bi.BitCount (), "before randomize");
			bi.Randomize ();
			// Randomize returns a random number of BitCount length
			// so in this case it will ALWAYS return 0
			Assert.AreEqual (0, bi.BitCount (), "after randomize");
			Assert.AreEqual (new BigInteger (0), bi, "Zero");
		}
            public ModulusRing(BigInteger modulus)
            {
                mod = modulus;

                // calculate constant = b^ (2k) / m
                var i = mod.length << 1;

                constant = new BigInteger(Sign.Positive, i + 1);
                constant.data[i] = 0x00000001;

                constant = constant/mod;
            }
Example #19
0
		public void ModPow_2 ()
		{
			// #70169
			BigInteger b = new BigInteger (10);
			BigInteger m = new BigInteger (32);
			// after 40 we start loosing double precision and result will differ
			for (int i=1; i < 40; i++) {
				BigInteger e = new BigInteger (i);
				BigInteger r = e.ModPow (b, m);
				long expected = (long) myalias.Math.Pow (i, 10) % 32;
				Assert.AreEqual (expected.ToString (), r.ToString (), i.ToString ());
			}
		}
Example #20
0
		//    myKeyAgree=KeyAgreement.getInstance("DiffieHellman");
		/// <exception cref="System.Exception"></exception>
		public virtual byte[] GetE()
		{
			if (e == null)
			{
				DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g);
				myKpairGen.Initialize(dhSkipParamSpec);
				Sharpen.KeyPair myKpair = myKpairGen.GenerateKeyPair();
				myKeyAgree.Init(myKpair.GetPrivate());
				//    BigInteger x=((javax.crypto.interfaces.DHPrivateKey)(myKpair.getPrivate())).getX();
				e = ((DHPublicKey)(myKpair.GetPublic())).GetY();
				e_array = e.GetBytes();
			}
			return e_array;
		}
 public void AppliedCryptographySanityChecks()
 {
     // Sanity checks from Applied Cryptography, 2nd Edition p467 - 468
     var p = new BigInteger(47);
     var q = new BigInteger(71);
     var n = p * q;
     var e = new BigInteger(79);
     var d = e.ModInverse((p - 1) * (q - 1));
     Func<int, string> encryptor = m => (new BigInteger(m).ModPow(e, n)).ToString();
     Assert.AreEqual("1570", encryptor(688));
     Assert.AreEqual("2756", encryptor(232));
     Assert.AreEqual("2091", encryptor(687));
     Assert.AreEqual("2276", encryptor(966));
     Assert.AreEqual("2423", encryptor(668));
     Assert.AreEqual("158", encryptor(3));            
 }
Example #22
0
 public void AssignTest()
 {
     SignedBigInteger a, b, c, d;
     a = -3;
     b = new BigInteger(12341234);
     c = 12341513241234;
     d = new BigInteger(123123823);
     d *= -1;
     Assert.AreEqual(true, a.Negative);
     Assert.AreEqual(new BigInteger(3), a.Number);
     Assert.AreEqual(new BigInteger(12341234), b.Number);
     Assert.AreEqual(false, b.Negative);
     Assert.AreEqual(new BigInteger(12341513241234), c.Number);
     Assert.AreEqual(false, c.Negative);
     Assert.AreEqual(true, d.Negative);
     Assert.AreEqual(new BigInteger(123123823), d.Number);
 }
		// initializes the private variables (throws CryptographicException)
		private void Initialize(BigInteger p, BigInteger g, BigInteger x, int secretLen, bool checkInput) {
			if (!p.isProbablePrime() || g <= 0 || g >= p || (x != null && (x <= 0 || x > p - 2)))
				throw new CryptographicException();
			// default is to generate a number as large as the prime this
			// is usually overkill, but it's the most secure thing we can
			// do if the user doesn't specify a desired secret length ...
			if (secretLen == 0)
				secretLen = p.bitCount();
			m_P = p;
			m_G = g;
			if (x == null) {
				BigInteger pm1 = m_P - 1;
				for(m_X = BigInteger.genRandom(secretLen); m_X >= pm1 || m_X == 0; m_X = BigInteger.genRandom(secretLen)) {}
			} else {
				m_X = x;
			}
		}
Example #24
0
        public static byte[] GenerateSharedKey(byte[] publicKey, byte[] privateKey, byte[] prime)
        {
            byte[] publicKeyReversed = new byte[publicKey.Length];

            Array.Copy(publicKey, publicKeyReversed, publicKeyReversed.Length);
            Array.Reverse(publicKeyReversed);

            BigInteger a = new BigInteger(publicKeyReversed);
            BigInteger x = new BigInteger(privateKey);
            BigInteger p = new BigInteger(prime);
            BigInteger b = a.ModPow(x, p);

            byte[] sharedKey = b.GetBytes();
            Array.Reverse(sharedKey);

            return sharedKey;
        }
        public static byte[] Calculate(BigInteger a, BigInteger b)
        {
            byte[] bytes;
            lock (locker)
                bytes = a.ModPow(b, prime).GetBytes();

            if (bytes.Length < 96)
            {
                byte[] oldBytes = bytes;
                bytes = new byte[96];
                Array.Copy(oldBytes, 0, bytes, 96 - oldBytes.Length, oldBytes.Length);
                for (int i = 0; i < (96 - oldBytes.Length); i++)
                    bytes[i] = 0;
            }

            return bytes;
        }
Example #26
0
 public void MakeAESKey(string keyExchangeBytes)
 {
     BigInteger A = new BigInteger(keyExchangeBytes);
     byte[] R = A.modPow(privateKey, Module).getBytes();
     aesKey = new byte[16];
     Array.Copy(R, aesKey, 16);
     for (int i = 0; i < 16; i++)
     {
         byte tmp = (byte)(aesKey[i] >> 4);
         byte tmp2 = (byte)(aesKey[i] & 0xF);
         if (tmp > 9)
             tmp = (byte)(tmp - 9);
         if (tmp2 > 9)
             tmp2 = (byte)(tmp2 - 9);
         aesKey[i] = (byte)( tmp << 4 | tmp2);
     }
 }
        public static int GetTrailingZerosCount(BigInteger num)
        {
            int count = 0;
            string numAsString = num.ToString ();
            int len = numAsString.Length;

            for (int i = 0; i < len; i++)
            {
                int digit = int.Parse (numAsString[len - i - 1].ToString());
                if (digit != 0)
                {
                    break;
                }
                count += 1;
            }

            return count;
        }
Example #28
0
        public static byte[] GetCounterHexValue(BigInteger counter)
        {
            byte[] counterBytes = counter.GetBytes();
            counterBytes = PppConvert.SwapBits(counterBytes);
            int padNeeded = 16 - counterBytes.Length;
            List<byte> padedBytes;

            if (counterBytes.Length != 16)
            {
                padedBytes = new List<byte>(16);
                padedBytes.AddRange(counterBytes);
                padedBytes.AddRange(new byte[padNeeded]);
            }
            else
            {
                padedBytes = new List<byte>(counterBytes);
            }
            return padedBytes.ToArray();
        }
Example #29
0
        public static string Convert(string source, int sourceRadix, int targetRadix)
        {
            /* Check if radix arguments are within the allowed range. */
            if (sourceRadix < MIN_RADIX || sourceRadix > MAX_RADIX)
                throw new ArgumentOutOfRangeException("sourceRadix", "Source radix needs to be in a range from " + MIN_RADIX + " to " + MAX_RADIX);
            if (targetRadix < MIN_RADIX || targetRadix > MAX_RADIX)
                throw new ArgumentOutOfRangeException("targetRadix", "Target radix needs to be in a range from " + MIN_RADIX + " to " + MAX_RADIX);

            BigInteger radixFrom = new BigInteger((UInt32)sourceRadix);
            BigInteger value = new BigInteger(0);
            BigInteger multiplier = new BigInteger(1);

            for (int i = source.Length - 1; i >= 0; i--)
            {
                int digit = Digit(source[i], sourceRadix);
                if (digit == -1)
                    throw new ArgumentException("The character '" + source[i] + "' is not defined for the source radix.", "sourceRadix");
                value += multiplier * digit;
                multiplier = multiplier * radixFrom;
            }

            return value.ToString((UInt32)targetRadix, CHARACTERS.Substring(0, targetRadix));
        }
		static string ToDecimalString (string hexString)
		{
#if TARGET_DOTNET
			throw new NotImplementedException ();
#else			
            // http://tools.ietf.org/html/rfc5280#section-4.1.2.2
            // We SHOULD support negative numbers
            var bytes = FromBinHex (hexString);
			
            var negative = bytes.Length > 0 && bytes [0] >= 0x80;
            if (negative) {
                for (int i = 0; i < bytes.Length; i++)
                    bytes [i] = (byte) ~ bytes [i];
            }
        	
			var big = new BigInteger (bytes);
			if (negative) { 
				big = big + 1;
				return "-" + big.ToString ();
			} else 
				return big.ToString ();
#endif
        }
    public void Test() {
      RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
      byte[] blob = rsa.ExportCspBlob(false);
      RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider();
      rsa_pub.ImportCspBlob(blob);
      CertificateMaker cm = new CertificateMaker("United States", "UFL", 
          "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub,
          "brunet:node:abcdefghijklmnopqrs");
      Assert.AreEqual("C=United States, O=UFL, OU=ACIS, CN=David Wolinsky, [email protected]", cm.Subject.DN, "DN test 1");
      cm = new CertificateMaker(cm.UnsignedData);
      Assert.AreEqual("C=United States, O=UFL, OU=ACIS, CN=David Wolinsky, [email protected]", cm.Subject.DN, "DN test 2");

      Certificate cert = cm.Sign(cm, rsa);

      Assert.IsTrue(cert.Signature != null, "Signature");
      Assert.AreEqual(cm.Subject.DN, cert.Issuer.DN, "Issuer = Subject");
      Assert.AreEqual("brunet:node:abcdefghijklmnopqrs", cert.NodeAddress , "Node address");

      Mono.Math.BigInteger rsa_pub_bi = new Mono.Math.BigInteger(rsa_pub.ExportCspBlob(false));
      Mono.Math.BigInteger cert_pub_bi = new Mono.Math.BigInteger(cert.PublicKey.ExportCspBlob(false));
      Assert.AreEqual(rsa_pub_bi, cert_pub_bi, "Key");

      SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
      Assert.AreEqual(MemBlock.Reference(cert.SerialNumber),
          MemBlock.Reference(sha1.ComputeHash(cert.UnsignedData)),
          "SerialNumber == hash of unsigned data");

    }
Example #32
0
		/// <summary>
		/// Generates the smallest prime >= bi
		/// </summary>
		/// <param name="bi">A BigInteger</param>
		/// <returns>The smallest prime >= bi. More mathematically, if bi is prime: bi, else Prime [PrimePi [bi] + 1].</returns>
		public static BigInteger NextHighestPrime (BigInteger bi)
		{
			NextPrimeFinder npf = new NextPrimeFinder ();
			return npf.GenerateNewPrime (0, bi);
		}