getBytes() public method

public getBytes ( ) : byte[]
return byte[]
Ejemplo n.º 1
0
        private static byte[] Compute(byte[] data, RSAPublicKey publicKey, int blockSize)
        {
            //
            // 公钥加密/解密公式为:ci = mi^e ( mod n )
            //
            // 先将 m(二进制表示)分成数据块 m1, m2, ..., mi ,然后进行运算。
            //
            BigInteger e = new BigInteger(publicKey.Exponent);
            BigInteger n = new BigInteger(publicKey.Modulus);

            int blockOffset = 0;

            using (MemoryStream stream = new MemoryStream())
            {
                while (blockOffset < data.Length)
                {
                    int    blockLen  = Math.Min(blockSize, data.Length - blockOffset);
                    byte[] blockData = new byte[blockLen];
                    Buffer.BlockCopy(data, blockOffset, blockData, 0, blockLen);

                    BigInteger mi = new BigInteger(blockData);
                    BigInteger ci = mi.modPow(e, n);//ci = mi^e ( mod n )

                    byte[] block = ci.getBytes();
                    stream.Write(block, 0, block.Length);
                    blockOffset += blockLen;
                }

                return(stream.ToArray());
            }
        }
Ejemplo n.º 2
0
        private static byte[] Compute(byte[] data, RSAPrivateKey privateKey, int blockSize)
        {
            //
            // 私钥加密/解密公式为:mi = ci^d ( mod n )
            //
            // 先将 c(二进制表示)分成数据块 c1, c2, ..., ci ,然后进行运算。
            //
            BigInteger d = new BigInteger(privateKey.D);
            BigInteger n = new BigInteger(privateKey.Modulus);

            int blockOffset = 0;

            using (MemoryStream stream = new MemoryStream())
            {
                while (blockOffset < data.Length)
                {
                    int    blockLen  = Math.Min(blockSize, data.Length - blockOffset);
                    byte[] blockData = new byte[blockLen];
                    Buffer.BlockCopy(data, blockOffset, blockData, 0, blockLen);

                    BigInteger ci = new BigInteger(blockData);
                    BigInteger mi = ci.modPow(d, n);//mi = ci^d ( mod n )

                    byte[] block = mi.getBytes();
                    stream.Write(block, 0, block.Length);
                    blockOffset += blockLen;
                }

                return(stream.ToArray());
            }
        }
Ejemplo n.º 3
0
        public bool Validate()
        {
            BigInteger calculatedHash = new BigInteger(this.ToString(), _RADIX);
            bool       ret            = true;

            //Calculate the hash
            calculatedHash = calculatedHash.modPow(new BigInteger(17), _n);

            //Compare our real hash and the calculated hash
            byte[] ourHash = _hash.getBytes();
            byte[] myHash  = calculatedHash.getBytes();
            if (ourHash.Length == myHash.Length)
            {
                for (int i = 0; i <= ourHash.Length - 1; i++)
                {
                    if (ourHash[i] != myHash[i])
                    {
                        ret = false;

                        break; // TODO: might not be correct. Was : Exit For
                    }
                }
            }
            else
            {
                //Not even the right length, it's crap
                ret = false;
            }

            return(ret);
        }
Ejemplo n.º 4
0
        private byte[] DoEncrypt(DoCalculateionDelegate method, byte[] src, Pkcs1PadType type)
        {
            try
            {
                int bl = this.GetBlockSize();

                byte[]     paddedBytes = this.Pkcs1pad(src, bl, type);
                BigInteger m           = new BigInteger(paddedBytes);
                if (m == 0)
                {
                    return(null);
                }

                BigInteger c = method(m);
                if (c == 0)
                {
                    return(null);
                }

                return(c.getBytes());
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 5
0
        //PROCESS_DATA_METHOD
        protected override byte[] ProcessDataBlock(byte[] plaintext_data_block)
        {
            // the random number, K
            BigInteger K;

            // create K, which is the random number
            do
            {
                K = new BigInteger();
                K.genRandomBits(current_key.P.bitCount() - 1, random_number);
            }while

            (K.gcd(current_key.P - 1) != 1);

            // compute the values  A = G exp K mod P
            // and B = ((Y exp K mod P) * plain_data_block) / P
            //Y is Alice's encrypted result (public key)
            BigInteger A = current_key.G.modPow(K, current_key.P);
            BigInteger B = (current_key.Y.modPow(K, current_key.P) * new BigInteger(plaintext_data_block)) % (current_key.P);

            // ciphertext
            byte[] cipher_result = new byte[ciphertext_blocksize];

            // copy the bytes from A and B into the result array which is cipher_result
            byte[] a_bytes = A.getBytes();
            Array.Copy(a_bytes, 0, cipher_result, ciphertext_blocksize / 2 - a_bytes.Length, a_bytes.Length); //96bit

            byte[] b_bytes = B.getBytes();
            Array.Copy(b_bytes, 0, cipher_result, ciphertext_blocksize - b_bytes.Length, b_bytes.Length); //96bit

            // return the result array after merging A and B
            return(cipher_result);
        }
        public void TestZero()
        {
            Paillier algorithm = new PaillierManaged();

            algorithm.Padding = PaillierPaddingMode.LeadingZeros;

            for (int keySize = 384; keySize <= 1088; keySize += 8)
            {
                algorithm.KeySize = keySize;

                Paillier encryptAlgorithm = new PaillierManaged();
                encryptAlgorithm.FromXmlString(algorithm.ToXmlString(false));

                Paillier decryptAlgorithm = new PaillierManaged();
                decryptAlgorithm.FromXmlString(algorithm.ToXmlString(true));

                var z = new BigInteger(0);

                var z_enc = encryptAlgorithm.EncryptData(z.getBytes());
                var z_dec = decryptAlgorithm.DecryptData(z_enc);

                var zero_array = new byte[z_dec.Length];
                Array.Clear(zero_array, 0, zero_array.Length - 1);

                CollectionAssert.AreEqual(zero_array, z_dec);
            }
        }
Ejemplo n.º 7
0
    private static long ProfileEncryptedADD(int iterations, int keyl)
    {
        // clean up
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        var rnd = new Random();

        // prepare and warm up 
        Paillier algorithm = new PaillierManaged();
        algorithm.KeySize = keyl;
        algorithm.Padding = PaillierPaddingMode.LeadingZeros;
        //string parametersXML = algorithm.ToXmlString(true);

        Paillier encryptAlgorithm = new PaillierManaged();
        encryptAlgorithm.FromXmlString(algorithm.ToXmlString(false));

        var a = new BigInteger(rnd.Next(65536));
        var a_bytes = encryptAlgorithm.EncryptData(a.getBytes());

        var b = new BigInteger(rnd.Next(65536));
        var b_bytes = encryptAlgorithm.EncryptData(b.getBytes());

        var c_bytes = encryptAlgorithm.Addition(a_bytes, b_bytes);

        var watch = Stopwatch.StartNew();
        for (int i = 0; i < iterations; i++)
        {
            c_bytes = encryptAlgorithm.Addition(a_bytes, b_bytes);
        }
        watch.Stop();

        return watch.Elapsed.Ticks;
    }
Ejemplo n.º 8
0
        public static BigInteger StripPKCS1Pad(BigInteger input, int type)
        {
            byte[] strip = input.getBytes();
            int    i;

            if (strip[0] != type)
            {
                throw new Exception(String.Format("Invalid PKCS1 padding {0}", type));
            }

            for (i = 1; i < strip.Length; i++)
            {
                if (strip[i] == 0)
                {
                    break;
                }

                if (type == 0x01 && strip[i] != (byte)0xff)
                {
                    throw new Exception("Invalid PKCS1 padding, corrupt data");
                }
            }

            if (i == strip.Length)
            {
                throw new Exception("Invalid PKCS1 padding, corrupt data");
            }

            byte[] val = new byte[strip.Length - i];
            Array.Copy(strip, i, val, 0, val.Length);
            return(new BigInteger(val));
        }
Ejemplo n.º 9
0
    private static void TestZero()
    {
        Paillier algorithm = new PaillierManaged();
        algorithm.KeySize = 384;
        algorithm.Padding = PaillierPaddingMode.LeadingZeros;

        Paillier encryptAlgorithm = new PaillierManaged();
        encryptAlgorithm.FromXmlString(algorithm.ToXmlString(false));

        Paillier decryptAlgorithm = new PaillierManaged();
        decryptAlgorithm.FromXmlString(algorithm.ToXmlString(true));

        var z = new BigInteger(0);

        var z_enc = encryptAlgorithm.EncryptData(z.getBytes());

        for (int i = 0; i < z_enc.Length; i++)
        {
            Console.Write(z_enc[i]);
        }
        Console.WriteLine();

        var z_dec = decryptAlgorithm.DecryptData(z_enc);

        for (int i = 0; i < z_dec.Length; i++)
        {
            Console.Write(z_dec[i]);
        }
        Console.WriteLine();
    }
Ejemplo n.º 10
0
        // private helper methods

        private static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }

            //using (var hmac = new System.Security.Cryptography.HMACSHA512())
            //{
            //	passwordSalt = hmac.Key;
            //	passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            //}

            BigInteger b = new BigInteger();

            b.genRandomBits(512, new Random());

            passwordSalt = b.getBytes();

            GostCrypto.Gost34102012Signer signer = new GostCrypto.Gost34102012Signer(new BigInteger(passwordSalt));
            passwordHash = Encoding.UTF8.GetBytes(signer.Sign(password));
        }
Ejemplo n.º 11
0
        /**
         * Return a byte[] of length MemSize, which holds the integer % Full
         * as a buffer which is a binary representation of an Address
         */
        static public byte[] ConvertToAddressBuffer(BigInteger num)
        {
            byte[] bi_buf;

            BigInteger val = num % Full;

            if (val < 0)
            {
                val = val + Full;
            }
            bi_buf = val.getBytes();
            int missing = (MemSize - bi_buf.Length);

            if (missing > 0)
            {
                //Missing some bytes at the beginning, pad with zero :
                byte[] tmp_bi = new byte[Address.MemSize];
                for (int i = 0; i < missing; i++)
                {
                    tmp_bi[i] = (byte)0;
                }
                System.Array.Copy(bi_buf, 0, tmp_bi, missing,
                                  bi_buf.Length);
                bi_buf = tmp_bi;
            }
            else if (missing < 0)
            {
                throw new System.ArgumentException(
                          "Integer too large to fit in 160 bits: " + num.ToString());
            }
            return(bi_buf);
        }
Ejemplo n.º 12
0
        protected override byte[] ProcessDataBlock(byte[] p_block)
        {
            // set random K
            BigInteger K;

            do
            {
                K = new BigInteger();
                K.genRandomBits(o_key_struct.P.bitCount() - 1, o_random);
            } while (K.gcd(o_key_struct.P - 1) != 1);

            // compute the values A and B
            BigInteger A = o_key_struct.G.modPow(K, o_key_struct.P);
            BigInteger B = (o_key_struct.Y.modPow(K, o_key_struct.P) * new BigInteger(p_block)) % (o_key_struct.P);

            // create an array to contain the ciphertext
            byte[] x_result = new byte[o_ciphertext_blocksize];
            // copy the bytes from A and B into the result array
            byte[] x_a_bytes = A.getBytes();
            Array.Copy(x_a_bytes, 0, x_result, o_ciphertext_blocksize / 2
                       - x_a_bytes.Length, x_a_bytes.Length);
            byte[] x_b_bytes = B.getBytes();
            Array.Copy(x_b_bytes, 0, x_result, o_ciphertext_blocksize
                       - x_b_bytes.Length, x_b_bytes.Length);
            // return the result array
            return(x_result);
        }
Ejemplo n.º 13
0
        private byte[] pkcs1unpad2(BigInteger m, int b)
        {
            byte[] bytes = m.getBytes();

            int i = 0;

            while (i < bytes.Length && bytes[i] == 0)
            {
                ++i;
            }

            if (bytes.Length - i != (b - 1) || bytes[i] != 0x2)
            {
                return(null);
            }

            while (bytes[i] != 0)
            {
                if (++i >= bytes.Length)
                {
                    return(null);
                }
            }

            byte[] result = new byte[bytes.Length - i + 1];
            int    p      = 0;

            while (++i < bytes.Length)
            {
                result[p++] = bytes[i];
            }

            return(result);
        }
Ejemplo n.º 14
0
        public bool Validate()
        {
            BigInteger calculatedHash = new BigInteger(this.ToString(), _RADIX);
            bool ret = true;

            //Calculate the hash
            calculatedHash = calculatedHash.modPow(new BigInteger(17), _n);

            //Compare our real hash and the calculated hash
            byte[] ourHash = _hash.getBytes();
            byte[] myHash = calculatedHash.getBytes();
            if (ourHash.Length == myHash.Length)
            {
                for (int i = 0; i <= ourHash.Length - 1; i++)
                {
                    if (ourHash[i] != myHash[i])
                    {
                        ret = false;

                        break; // TODO: might not be correct. Was : Exit For
                    }
                }
            }
            else
            {
                //Not even the right length, it's crap
                ret = false;
            }

            return ret;
        }
Ejemplo n.º 15
0
        protected override byte[] ProcessDataBlock(byte[] p_block)
        {
            // extract the byte arrays that represent A and B
            byte[] x_a_bytes = new byte[o_ciphertext_blocksize / 2];
            Array.Copy(p_block, 0, x_a_bytes, 0, x_a_bytes.Length);
            byte[] x_b_bytes = new byte[o_ciphertext_blocksize / 2];
            Array.Copy(p_block, x_a_bytes.Length, x_b_bytes, 0, x_b_bytes.Length);

            // create big integers from the byte arrays
            BigInteger A = new BigInteger(x_a_bytes);
            BigInteger B = new BigInteger(x_b_bytes);

            // calculate the value M
            BigInteger M = (B * A.modPow(o_key_struct.X, o_key_struct.P).modInverse(o_key_struct.P)) % o_key_struct.P;

            // return the result - take care to ensure that we create
            // a result which is the correct length
            byte[] x_m_bytes = M.getBytes();

            // we may end up with results which are short some leading
            // bytes - add these are required
            if (x_m_bytes.Length < o_plaintext_blocksize)
            {
                byte[] x_full_result = new byte[o_plaintext_blocksize];
                Array.Copy(x_m_bytes, 0, x_full_result,
                           o_plaintext_blocksize - x_m_bytes.Length, x_m_bytes.Length);
                x_m_bytes = x_full_result;
            }
            return(x_m_bytes);
        }
Ejemplo n.º 16
0
        public void encryptPacketWithKeys(BigInteger key, BigInteger modulus)
        {
            /* // Java Version, IKVM required
             * var key1 = new java.math.BigInteger("1370158896620336158431733257575682136836100155721926632321599369132092701295540721504104229217666225601026879393318399391095704223500673696914052239029335");
             * var modulus1 = new java.math.BigInteger("1549611057746979844352781944553705273443228154042066840514290174539588436243191882510185738846985723357723362764835928526260868977814405651690121789896823");
             *
             * int i1 = offset;
             * offset = 0;
             * byte[] dummyPacket1 = new byte[i1];
             * getBytes(dummyPacket1, 0, i1);
             * java.math.BigInteger biginteger31 = new java.math.BigInteger(dummyPacket1).modPow(key1, modulus1);
             * byte[] encryptedPacket1 = biginteger31.toByteArray();
             * offset = 0;
             * var output1 = string.Join(Environment.NewLine, encryptedPacket1);
             * addByte(encryptedPacket1.Length);
             * addBytes(encryptedPacket1, 0, encryptedPacket1.Length);
             */

            int i = offset;

            offset = 0;
            byte[] dummyPacket = new byte[i];
            getBytes(dummyPacket, 0, i);
            BigInteger biginteger3 = new BigInteger(dummyPacket).modPow(key, modulus);

            byte[] encryptedPacket = biginteger3.getBytes();
            offset = 0;
            addByte(encryptedPacket.Length);
            addBytes(encryptedPacket, 0, encryptedPacket.Length);
        }
Ejemplo n.º 17
0
        public override byte[] CreateKeyExchange()
        {
            BigInteger bigInteger = this.m_G.modPow(this.m_X, this.m_P);

            byte[] bytes = bigInteger.getBytes();
            bigInteger.Clear();
            return(bytes);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Creates the key exchange data.
        /// </summary>
        /// <returns>The key exchange data to be sent to the intended recipient.</returns>
        public override byte[] CreateKeyExchange()
        {
            BigInteger y = m_G.modPow(m_X, m_P);

            byte[] ret = y.getBytes();
            y.Clear();
            return(ret);
        }
Ejemplo n.º 19
0
        public override MazeErrorCode onReceiveData(byte[] Data, ref byte[] ResponseData)
        {
            ResponseData = new byte[0];
            switch (base.Step)
            {
            case 1:
            {
                if (Data.Length != 32)
                {
                    SysLogger.Log("[MazeHandShake][Server] Receive Length missmatch", SysLogType.Debug);
                    return(MazeErrorCode.Error);
                }

                wopEx = base.GetWopEncryption();
                wopEx.Decrypt(Data, 0, Data.Length);

                BigInteger server_prime = new BigInteger(Data);
                if (server_prime.isProbablePrime())
                {
                    //verify the prime from the server
                    BigInteger server_Prime_test = BigInteger.genPseudoPrime(256, 50, new Random(BitConverter.ToInt32(wopEx.Key, 0)));

                    if (server_prime != server_Prime_test)
                    {
                        //Attacker detected ?
                        SysLogger.Log("[MazeHandShake][Server] Man-In-The-Middle detected", SysLogType.Debug);
                        return(MazeErrorCode.Error);
                    }

                    //successful
                    //generate another prime and send it back
                    BigInteger client_Prime = BigInteger.genPseudoPrime(256, 50, new Random(server_prime.IntValue()));

                    byte[] primeData = client_Prime.getBytes();
                    wopEx.Encrypt(primeData, 0, primeData.Length);
                    ResponseData = primeData;

                    BigInteger key = base.ModKey(server_prime, client_Prime);
                    //apply key to encryption
                    ApplyKey(wopEx, key);

                    base.FinalKey  = wopEx.Key;
                    base.FinalSalt = wopEx.Salt;

                    Step++;
                    return(MazeErrorCode.Finished);
                }
                else
                {
                    //connection failed, using old keys ?
                    SysLogger.Log("[MazeHandShake][Server] Invalid received data", SysLogType.Debug);
                    return(MazeErrorCode.Error);
                }
            }
            }

            return(MazeErrorCode.Success);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Extracts secret information from the key exchange data.
        /// </summary>
        /// <param name="keyEx">The key exchange data within which the shared key is hidden.</param>
        /// <returns>The shared key derived from the key exchange data.</returns>
        public override byte[] DecryptKeyExchange(byte[] keyEx)
        {
            BigInteger pvr = new BigInteger(keyEx);
            BigInteger z   = pvr.modPow(m_X, m_P);

            byte[] ret = z.getBytes();
            z.Clear();
            return(ret);
        }
Ejemplo n.º 21
0
        public override byte[] DecryptKeyExchange(byte[] keyEx)
        {
            BigInteger bigInteger  = new BigInteger(keyEx);
            BigInteger bigInteger2 = bigInteger.modPow(this.m_X, this.m_P);

            byte[] bytes = bigInteger2.getBytes();
            bigInteger2.Clear();
            return(bytes);
        }
Ejemplo n.º 22
0
        public byte[] Sign(byte[] data)
        {
            BigInteger pe = PrimeExponent(_d, _p);
            BigInteger qe = PrimeExponent(_d, _q);

            BigInteger result = SignCore(new BigInteger(data), pe, qe);

            return(result.getBytes());
        }
Ejemplo n.º 23
0
        public byte[][] GenerateKeyServer(BigInteger exchangeKey)
        {
            BigInteger hash1 = SHA256Hash2ArrayInverse(exchangeKey.getBytes(), GetKeyExchangeServer().getBytes());

            BigInteger hash2 = SHA256Hash2ArrayInverse(session.getBytes(), passwordHash);

            BigInteger v27 = new BigInteger(exchangeKey.getBytes());

            BigInteger v21 = (GetKeyExchange().modPow((hash1 * hash2), N) * v27.modPow(privateKey, N)) % N;

            key = GenerateEncryptionKeyRoot(v21.getBytes());

            byte[] chash1 = sha.ComputeHash(CombineBuffers(staticKey, usernameHash, session.getBytes(), exchangeKey.getBytes(), GetKeyExchangeServer().getBytes(), key));
            byte[] chash2 = sha.ComputeHash(CombineBuffers(exchangeKey.getBytes(), chash1, key));
            key = Generate256BytesKey(key);

            return(new byte[][] { chash1, chash2 });
        }
Ejemplo n.º 24
0
 public static byte[] BigInt2Key(BigInteger privatekey)
 {
     byte[] prv = privatekey.getBytes();
     if (prv.Length != 32)
     {
         Resize(ref prv, 32);
     }
     return(prv);
 }
Ejemplo n.º 25
0
        /**
         * 根据传入的参数做解密
         * @param srcMsgData 解密用源串
         * @param publicKey 公钥串
         */

        public static String RSADecrypt(String srcMsgData, String publicKey)
        {
            byte[]        pubKeyBytes = Convert.FromBase64String(publicKey);
            RSAParameters paraPub     = ConvertFromPublicKey(publicKey);
            BigInteger    biN         = new BigInteger(paraPub.Modulus);
            BigInteger    biE         = new BigInteger(paraPub.Exponent);

            byte[] dataBytes = Convert.FromBase64String(srcMsgData);
            int    kLen      = 128;
            int    len       = dataBytes.Length;
            int    cycle     = 0;

            if ((len % kLen) == 0)
            {
                cycle = len / kLen;
            }
            else
            {
                cycle = len / kLen + 1;
            }

            MemoryStream output   = new MemoryStream();
            ArrayList    temp     = new ArrayList();
            int          blockLen = 0;

            for (int i = 0; i < cycle; i++)
            {
                if (len >= kLen)
                {
                    blockLen = kLen;
                }
                else
                {
                    blockLen = len;
                }

                byte[] context = new byte[blockLen];
                int    po      = i * kLen;
                Array.Copy(dataBytes, po, context, 0, blockLen);

                BigInteger biText   = new BigInteger(context);
                BigInteger biEnText = biText.modPow(biE, biN);

                byte[] buffer = biEnText.getBytes();
                int    k      = 2;
                while (buffer[k++] != 0)
                {
                    ;
                }
                output.Write(buffer, k, buffer.Length - k);
                len -= blockLen;
            }
            byte[] result = output.ToArray(); //得到加密结果
            output.Close();
            return(System.Text.Encoding.UTF8.GetString(result));
        }
Ejemplo n.º 26
0
        //公钥解密
        private byte[] _PubDecrypt(byte[] block, RSACryptoServiceProvider key)
        {
            RSAParameters param    = key.ExportParameters(false);
            BigInteger    e        = new BigInteger(param.Exponent);
            BigInteger    n        = new BigInteger(param.Modulus);
            BigInteger    biText   = new BigInteger(block);
            BigInteger    biEnText = biText.modPow(e, n);

            return(biEnText.getBytes());
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Generates the key after a response is received.
 /// </summary>
 /// <param name="response">The string representation of the response.</param>
 public void HandleResponse(PayloadReader pr)
 {
     // Get the response and modpow it with the stored prime.
     using (BigInteger given = pr.ReadBigInteger())
         using (BigInteger key = given.modPow(mine, prime))
         {
             this.key = key.getBytes();
         }
     Dispose();
 }
Ejemplo n.º 28
0
        //私钥加密
        private byte[] _PriEncrypt(byte[] block, RSACryptoServiceProvider key)
        {
            RSAParameters param    = key.ExportParameters(true);
            BigInteger    d        = new BigInteger(param.D);
            BigInteger    n        = new BigInteger(param.Modulus);
            BigInteger    biText   = new BigInteger(block);
            BigInteger    biEnText = biText.modPow(d, n);

            return(biEnText.getBytes());
        }
        public string EncryptSymmetricKey(string symmKey, BigInteger e, BigInteger n)
        {
            BigInteger cryptoSymmKey = new BigInteger(Convert.FromBase64String(symmKey));

            cryptoSymmKey = cryptoSymmKey.modPow(e,n);

            string symmKeyString = Convert.ToBase64String(cryptoSymmKey.getBytes());

            return symmKeyString;
        }
Ejemplo n.º 30
0
        public byte[] GenerateKeyServer(BigInteger key1, BigInteger exchangeKey)
        {
            BigInteger hash1 = SHA256Hash2ArrayInverse(exchangeKey.getBytes(), this.GetKeyExchangeServer().getBytes());

            BigInteger hash2 = SHA256Hash2ArrayInverse(key1.getBytes(), passwordHash);

            BigInteger v27 = new BigInteger(exchangeKey);

            BigInteger v21 = (this.GetKeyExchange().modPow((hash1 * hash2), N) * v27.modPow(privateKey, N)) % N;

            encKey = GenerateEncryptionKeyRoot(v21.getBytes());
            encKey = Generate256BytesKey(encKey);
            decKey = new byte[encKey.Length];
            encKey.CopyTo(decKey, 0);
            encCounter = 0;
            decCounter = 0;

            return(sha.ComputeHash(CombineBuffers(staticKey, usernameHash, key1.getBytes(), exchangeKey.getBytes(), GetKeyExchangeServer().getBytes(), encKey)));
        }
Ejemplo n.º 31
0
    public static void Rerun_SameNumbers(BigInteger A, BigInteger B)
    {
        Paillier algorithm = new PaillierManaged();

        algorithm.KeySize = 384;
        algorithm.Padding = PaillierPaddingMode.LeadingZeros;

        string parametersXML = algorithm.ToXmlString(true);
        //Console.WriteLine("\n{0}\n", PrettifyXML(parametersXML));

        Paillier encryptAlgorithm = new PaillierManaged();

        encryptAlgorithm.FromXmlString(algorithm.ToXmlString(false));

        Paillier decryptAlgorithm = new PaillierManaged();

        decryptAlgorithm.FromXmlString(algorithm.ToXmlString(true));

        byte[] A_bytes = A.getBytes();
        byte[] B_bytes = B.getBytes();

        //encrypt A and B
        byte[] A_enc_bytes = encryptAlgorithm.EncryptData(A.getBytes());
        byte[] B_enc_bytes = encryptAlgorithm.EncryptData(B.getBytes());

        // decrypt A and B
        byte[] A_dec_bytes = decryptAlgorithm.DecryptData(A_enc_bytes);
        byte[] B_dec_bytes = decryptAlgorithm.DecryptData(B_enc_bytes);

        //getting homomorphic addition result
        byte[] C_enc_bytes = encryptAlgorithm.Addition(A_enc_bytes, B_enc_bytes);
        byte[] C_dec_bytes = decryptAlgorithm.DecryptData(C_enc_bytes);

        // convert to BigInteger
        BigInteger A_dec = new BigInteger(A_dec_bytes);
        BigInteger B_dec = new BigInteger(B_dec_bytes);
        BigInteger C_dec = new BigInteger(C_dec_bytes);

        // printing out
        Console.WriteLine("Plaintext: {0} + {1} = {2}", A.ToString(), B.ToString(), (A + B).ToString());
        Console.WriteLine("Encrypted: {0} + {1} = {2}", A_dec.ToString(), B_dec.ToString(), C_dec.ToString());
    }
Ejemplo n.º 32
0
    public static void TestMultiplication_Batch()
    {
        Console.WriteLine();
        Console.WriteLine("-- Testing multiplication in batch ------");

        var rnd = new Random();

        for (int i = 0; i < 3; i++)
        // testing for 3 sets of keys
        {
            Console.WriteLine("- Testing for key No.{0} -", i + 1);
            ElGamal algorithm = new ElGamalManaged();
            algorithm.KeySize = 384;
            algorithm.Padding = ElGamalPaddingMode.LeadingZeros;
            string parametersXML = algorithm.ToXmlString(true);

            ElGamal encryptAlgorithm = new ElGamalManaged();
            encryptAlgorithm.FromXmlString(algorithm.ToXmlString(false));

            ElGamal decryptAlgorithm = new ElGamalManaged();
            decryptAlgorithm.FromXmlString(algorithm.ToXmlString(true));

            int error_counter = 0;
            for (int j = 0; j < 50; j++)
            // testing for 50 pairs of random numbers
            {
                var a = new BigInteger(rnd.Next());
                var b = new BigInteger(rnd.Next());

                var a_bytes = encryptAlgorithm.EncryptData(a.getBytes());
                var b_bytes = encryptAlgorithm.EncryptData(b.getBytes());

                var c_bytes = encryptAlgorithm.Multiply(a_bytes, b_bytes);

                var dec_c = new BigInteger(decryptAlgorithm.DecryptData(c_bytes));
                var dec_a = new BigInteger(decryptAlgorithm.DecryptData(a_bytes));
                var dec_b = new BigInteger(decryptAlgorithm.DecryptData(b_bytes));

                var ab_result = a * b;
                if (dec_c != ab_result)
                {
                    error_counter++;
                    Console.WriteLine("Failure #{0}", error_counter);
                    Console.WriteLine("Key = {0}", PrettifyXML(parametersXML));
                    Console.WriteLine("Encrypted: {0} * {1} = {2}", dec_a.ToString(), dec_b.ToString(), dec_c.ToString());
                    Console.WriteLine("Plaintext: {0} * {1} = {2}", a.ToString(), b.ToString(), ab_result.ToString());
                    Console.WriteLine();
                }
            }

            Console.WriteLine("There are {0}/50 cases that do not pass the test", error_counter);
            Console.WriteLine();
        }
    }
Ejemplo n.º 33
0
        public byte[] SignWithSHA1(byte[] data) {
            byte[] hash = new SHA1CryptoServiceProvider().ComputeHash(data);

            byte[] buf = new byte[hash.Length + PKIUtil.SHA1_ASN_ID.Length];
            Array.Copy(PKIUtil.SHA1_ASN_ID, 0, buf, 0, PKIUtil.SHA1_ASN_ID.Length);
            Array.Copy(hash, 0, buf, PKIUtil.SHA1_ASN_ID.Length, hash.Length);

            BigInteger x = new BigInteger(buf);
            //Debug.WriteLine(x.ToHexString());
            int padLen = (_publickey._n.bitCount() + 7) / 8;

            x = RSAUtil.PKCS1PadType1(x, padLen);
            byte[] result = Sign(x.getBytes());
            return result;
        }
Ejemplo n.º 34
0
        public static BigInteger StripPKCS1Pad(BigInteger input, int type) {
            byte[] strip = input.getBytes();
            int i;

            if (strip[0] != type)
                throw new Exception(String.Format("Invalid PKCS1 padding {0}", type));

            for (i = 1; i < strip.Length; i++) {
                if (strip[i] == 0)
                    break;

                if (type == 0x01 && strip[i] != (byte)0xff)
                    throw new Exception("Invalid PKCS1 padding, corrupt data");
            }

            if (i == strip.Length)
                throw new Exception("Invalid PKCS1 padding, corrupt data");

            byte[] val = new byte[strip.Length - i];
            Array.Copy(strip, i, val, 0, val.Length);
            return new BigInteger(val);
        }
Ejemplo n.º 35
0
        public override byte[] ProcessDataReceived( byte []data, int length )
        {
            //	Console.WriteLine("Rec {0}", data[ 0 ] );
            //	HexViewer.View( data, 0, length );
            int t;
            switch( data[ 0 ] )
            {
                case 0x00://	Logon challenge
                    /*foreach( Account acc in World.allAccounts )
                        if ( acc.Ip != null &&
                            ch.IP.Address == acc.Ip.Address &&
                            //ch.Port == acc.Port &&
                            (bool)tryLoggin[ ch.IP.Address.ToString() ] )
                        {
                            Console.WriteLine("wait!!!");
                            return new byte[] { 0, 3, 0xEE, 0x1, 0x19 };
                        }*/
                //	Console.WriteLine( "Logon challenge" );
                    int clientVersion = ( ( (int)data[ 11 ] ) * 256  )+ data[ 12 ];
                    byte len = data[ 33 ];
                    userName = new byte[ len ];
                    //Console.Write( "User : "******"";
                    for( t = 0;t < len;t++ )
                    {
                        userName[ t ] = data[ 34 + t ];
                        usern+= "" + (char)data[ 34 + t ];
                    //	Console.Write( "{0}", "" + ((char)userName[ t ] ).ToString() );
                    }
                //	Console.WriteLine( "" );

                    myAccount = World.allAccounts.FindByUserName( usern );
                    if ( World.FreeForAll )
                    {
                        if ( myAccount == null )
                        {
                            World.allAccounts.Add( myAccount = new Account( usern, usern ) );
                        }
                    }
                    if ( myAccount == null )
                        return new byte[] { 0x1, 0x4 };

                    if ( myAccount.SelectedChar != null )
                    {
                    //	Console.WriteLine("Already loggin");
                        return new byte[] { 1, 0x6 };
                         // Already logged in
                    }

                    SHA1 sha = new SHA1CryptoServiceProvider();

                    string pass = "******" + myAccount.Password.ToUpper();
                    char []passc = pass.ToCharArray();
                    byte []passb = new byte[ passc.Length ];
                    int ti = 0;
                    foreach( char c in passc )
                        passb[ ti++ ] = (byte)c;
                    byte []user = Concat( userName, passb );
                    byte []hash = sha.ComputeHash( user, 0 , user.Length );
                    byte []res = new Byte[ hash.Length + salt.Length ];
                    t = 0;
                    rand.NextBytes( salt );
                    foreach( byte s in salt )
                        res[ t++ ] = s;
                    foreach( byte s in hash )
                        res[ t++ ] = s;
                    byte []hash2 = sha.ComputeHash( res, 0, res.Length );
                    byte []x = Reverse( hash2 );

                    rN = Reverse( N );
                    rand.NextBytes( b );
                    rb = Reverse( b );

                    BigInteger bi = new BigInteger( x );
                    BigInteger bi2 = new BigInteger( rN );
                    BigInteger g = new BigInteger( new byte[] { 7 } );
                    v = g.modPow( bi, bi2 );

                    K = new BigInteger( new Byte[] { 3 } );
                    BigInteger temp1 = K * v;
                    BigInteger temp2 = g.modPow( new BigInteger( rb ), new BigInteger( rN ) );
                    BigInteger temp3 = temp1 + temp2;
                    B = temp3 % new BigInteger( rN );

                /*	byte []ezfd= B.getBytes();
                    Console.WriteLine("B");
                    HexViewer.View( ezfd, 0, ezfd.Length );
                    BigInteger C = new BigInteger();

                    Console.WriteLine("C/Rn {0}", temp3/new BigInteger( rN ) );*/
                    //Console.WriteLine("temp1 {0}",temp1.ToHexString());
                    //Console.WriteLine("temp2 {0}",temp2.ToHexString());
                    //Console.WriteLine("temp3 {0}",temp3.ToHexString());
            /*		for(int ll = 0;ll < 6;ll++)
                    {
                        C = B;
                        C += new BigInteger( rN ) * ll;
                        C -= temp1;
                        Console.WriteLine("temp3 {0}",C.ToHexString());
                    }*/

                    byte []pack = new byte[ 118 ];
                    //byte[] pack = new byte[119];
                    pack[ 0 ] = pack[ 1 ] = 0;
                    byte []tB = Reverse( B.getBytes() );
                    for( t = 0;t < tB.Length ;t++ )
                        pack[ 3 + t ] = tB[ t ];
                    pack[ 35 ] = 1;// g_length
                    pack[ 36 ] = 7;// g
                    pack[ 37 ] = 32;// n_len
                    for( t = 0;t < N.Length;t++ )
                        pack[ 38 + t ] = N[ t ];
                    for( t = 0;t < salt.Length ;t++ )
                        pack[ 70 + t ] = salt[ t ];
                    for( t = 0;t < 16;t++ )
                    //for (t = 0; t < 17; t++)
                        pack[ 102 + t ] = 0;

                    return pack;

                case 0x01://	Logon proof
                {
                    //Console.WriteLine("Logon proof" );
                    byte []A = new byte[ 32 ];
                    for( t = 0;t < 32;t++ )
                    {
                        A[ t ] = data[ t + 1 ];
                    }
                    byte []kM1 = new byte[ 20 ];
                    for( t = 0;t < 20;t++ )
                    {
                        kM1[ t ] = data[ t + 1 + 32 ];
                    }

                    //A = new byte[] { 0x23, 0x2f, 0xb1, 0xb8, 0x85, 0x29, 0x64, 0x3d, 0x95, 0xb8, 0xdc, 0xe7, 0x8f, 0x27, 0x50, 0xc7, 0x5b, 0x2d, 0xf3, 0x7a, 0xcb, 0xa8, 0x73, 0xeb, 0x31, 0x07, 0x38, 0x39, 0xed, 0xa0, 0x73, 0x8d };
                    byte []rA = Reverse( A );
                    //	B = new BigInteger( new byte[] { 0x64, 0x5d, 0x1f, 0x78, 0x97, 0x30, 0x73, 0x70, 0x1e, 0x12, 0xbc, 0x98, 0xaa, 0x38, 0xea, 0x99, 0xb4, 0xbc, 0x43, 0x5c, 0x32, 0xe8, 0x44, 0x7c, 0x73, 0xab, 0x07, 0x7a, 0xe4, 0xd7, 0x59, 0x64 } );
                    byte []AB = Concat( A, Reverse( B.getBytes() ) );

                    SHA1 shaM1 = new SHA1CryptoServiceProvider();
                    byte []U = shaM1.ComputeHash( AB );
                    //	U = new byte[] { 0x2f, 0x49, 0x69, 0xac, 0x9f, 0x38, 0x7f, 0xd6, 0x72, 0x23, 0x6f, 0x94, 0x91, 0xa5, 0x16, 0x77, 0x7c, 0xdd, 0xe1, 0xc1 };
                    byte []rU = Reverse( U );

                    temp1 = v.modPow( new BigInteger( rU ), new BigInteger( rN ) );
                    temp2 = temp1 * new BigInteger( rA );
                    temp3 = temp2.modPow( new BigInteger( rb ), new BigInteger( rN ) );

                    byte []S1 = new byte[ 16 ];
                    byte []S2 = new byte[ 16 ];
                    byte []S = new byte[ 32 ];
                    byte []temp = temp3.getBytes();
                /*	Console.WriteLine("temp");
                    HexViewer.View( temp, 0, temp.Length );
                    Console.WriteLine("temp1 {0}", temp1.ToHexString());
                    Console.WriteLine("temp2 {0}", temp2.ToHexString());
                    Console.WriteLine("temp3 {0}", temp3.ToHexString());*/
                    Buffer.BlockCopy( temp, 0, S, 0, temp.Length );
                    byte []rS = Reverse( S );

                    for( t = 0;t < 16;t++)
                    {
                        S1[ t ] = rS[ t * 2 ];
                        S2[ t ] = rS[ ( t * 2 ) + 1 ];
                    }
                    byte []hashS1 = shaM1.ComputeHash( S1 );
                    byte []hashS2 = shaM1.ComputeHash( S2 );
                    myAccount.SS_Hash = new byte[ hashS1.Length + hashS2.Length ];
                    for( t = 0;t < hashS1.Length ;t++ )
                    {
                        myAccount.SS_Hash[ t * 2 ] = hashS1[ t ];
                        myAccount.SS_Hash[ ( t * 2 ) + 1 ] = hashS2[ t ];
                    }

                    //	SS_Hash = new byte[] { 0x02, 0x61, 0xf4, 0xeb, 0x48, 0x91, 0xb6, 0x6a, 0x1a, 0x82, 0x6e, 0xb7, 0x79, 0x28, 0xd8, 0x64, 0xb7, 0xea, 0x14, 0x54, 0x38, 0xdb, 0x7c, 0xfd, 0x0d, 0x3d, 0x2f, 0xc0, 0x22, 0xce, 0xcc, 0x46, 0x83, 0x79, 0xf2, 0xc0, 0x87, 0x78, 0x7f, 0x14 };

                    byte []NHash = shaM1.ComputeHash( N );
                    byte []GHash = shaM1.ComputeHash( new byte[]{ 7 } );
                    byte []userHash = shaM1.ComputeHash( userName );
                    byte []NG_Hash = new byte[ 20 ];
                    for( t = 0;t < 20;t++ )
                    {
                        NG_Hash[ t ] = (byte)( NHash[ t ] ^ GHash[ t ] );
                    }
                    byte []Temp = Concat( NG_Hash, userHash );
                    Temp = Concat( Temp, salt );
                    Temp = Concat( Temp, A );
                    Temp = Concat( Temp, B.getBytes() );
                    Temp = Concat( Temp, K.getBytes() );//SS_Hash );

                    byte []M1 = shaM1.ComputeHash( Temp );

                    Temp = Concat( A, kM1 );
                    Temp = Concat( Temp, myAccount.SS_Hash );

                    byte []M2 = shaM1.ComputeHash( Temp );

                    byte []retur = new byte[ M2.Length + 4/*NG_Hash.Length */+ 2 ];
                    //	byte []retur = new byte[ M2.Length + NG_Hash.Length + 2 ];
                    retur[ 0 ] = 0x1;
                    retur[ 1 ] = 0x0;
                    for(t = 0;t < M2.Length;t++ )
                        retur[ t + 2 ] = M2[ t ];

                    //for(t = 0;t < NG_Hash.Length;t++ )
                    //	retur[ t + 2 + 20 ] = NG_Hash[ t ];

                    //	set the account properties
                    Console.WriteLine("Logon proof for {0},{1}", IP.ToString(), myAccount.Username );
                    myAccount.Ip = this.IP;
                    myAccount.Port = 0;
                    myAccount.K = myAccount.SS_Hash;

                    return retur;
                }
                case 0x02://	Reconnect challenge
                {
                //	Console.WriteLine( "Reconnect challenge" );
                    byte []packRecoChallenge = new byte[ 34 ];
                    packRecoChallenge[ 0 ] = 0x02;
                    packRecoChallenge[ 1 ] = 0x00;
                    for( t = 0;t < 16 ;t++ )
                        packRecoChallenge[ 18 + t ] = 0;
                    return packRecoChallenge;
                }
                case 0x03://	Reconnect proof
                //	Console.WriteLine( "Reconnect proof" );
                    return new byte[] { 0x03, 0x00 };
                case 0x04://	Update server
                //	Console.WriteLine( "Update server" );
                    break;
                case 0x10://	Realm List
                //	Console.WriteLine( "Realm lList request" );
                    string ip = World.ServerIP;
                /*	if ( base.theClientHandler.IP.ToString().StartsWith( "192.168.0" ) )
                    {
                        ip = "192.168.0.2";
                    }
                    else*/
                    if ( IP.ToString() == "127.0.0.1" )
                    {
                        ip = "127.0.0.1";
                    }
                    byte []retData = new byte[ 25 + ip.Length + World.ServerName.Length + World.ServerPort.ToString().Length ];
                /*
                byte []retData = new byte[ ]{   0x10, 45,
                                          0x00, 0x00, 0x00, 0x00,
                                          0x00,
                                          0x01, 0x00, 0x00, 0x00,
                                          0x00, 0x00,
                                          (byte)'D', (byte)'r', (byte)' ', (byte)'N', (byte)'e',
                                          (byte)'x', (byte)'u', (byte)'s',
                                          0x00, (byte)'1', (byte)'9', (byte)'2', (byte)'.',
                                          (byte)'1', (byte)'6', (byte)'8', (byte)'.',
                                          (byte)'0', (byte)'.',
                                          (byte)'2',
                                          0x3a, 0x38, 0x30, 0x38, 0x35,
                                          0x00, 0x00, 0x00, 0x00,
                                          0x00, 0x00,
                                          0x01, 0x00,
                                          0x02, 0x00 };*/
                    int offset = 0;
                    Converter.ToBytes( (byte)0x10, retData, ref offset );
                    Converter.ToBytes( (byte)43, retData, ref offset );
                    Converter.ToBytes( 1/*World.allConnectedChars.Count*/, retData, ref offset );
                    Converter.ToBytes( (byte)0, retData, ref offset );
                    Converter.ToBytes( 1, retData, ref offset );
                    Converter.ToBytes( (short)0, retData, ref offset );
                    Converter.ToBytes( World.ServerName, retData, ref offset );
                    Converter.ToBytes( (byte)0, retData, ref offset );
                    Converter.ToBytes( ip, retData, ref offset );
                    Converter.ToBytes( (byte)':', retData, ref offset );
                    Converter.ToBytes( World.ServerPort.ToString(), retData, ref offset );
                    Converter.ToBytes( (byte)0, retData, ref offset );
                    Converter.ToBytes( 0, retData, ref offset );
                //	Converter.ToBytes( (short)0, retData, ref offset );//	cr erreir
                    //Converter.ToBytes( (short)1, retData, ref offset );
                    //Converter.ToBytes( (short)2, retData, ref offset );

                    Converter.ToBytes( (short)World.allConnectedChars.Count, retData, ref offset );
                    Converter.ToBytes( (byte)0, retData, ref offset );
                    Converter.ToBytes( (short)1, retData, ref offset );
                    int atlen = 1;
                    offset -= 3;
                    Converter.ToBytes( offset, retData, ref atlen );
                    Console.WriteLine("Connected player(s) {0}", World.allConnectedChars.Count );
                /*	if ( World.allConnectedChars.Count < 3 )*/
                        //Thread.Sleep( 500 );
                    return retData;

                default:
                    Console.WriteLine( "Receive unknown command {0}", data[ 0 ] );
                    break;

            }
            byte []ret = { 0, 0, 0, 0 };
            return ret;
        }
Ejemplo n.º 36
0
        public byte[] SignWithSHA1([ReadOnlyArray()] byte[] data)
        {
            byte[] hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1).HashData(data.AsBuffer()).ToArray();

            byte[] buf = new byte[hash.Length + PKIUtil.SHA1_ASN_ID.Length];
            Array.Copy(PKIUtil.SHA1_ASN_ID, 0, buf, 0, PKIUtil.SHA1_ASN_ID.Length);
            Array.Copy(hash,        0, buf, PKIUtil.SHA1_ASN_ID.Length, hash.Length);

            BigInteger x = new BigInteger(buf);
            //Debug.WriteLine(x.ToHexString());
            int padLen = (_publickey._n.bitCount() + 7) / 8;

            x = RSAUtil.PKCS1PadType1(x, padLen);
            byte[] result = Sign(x.getBytes());
            return result;
        }
Ejemplo n.º 37
0
            /// <summary>
            /// Adds padding to the input data and returns the padded data.
            /// </summary>
            /// <param name="dataBytes">Data to be padded prior to encryption</param>
            /// <param name="parameters">RSA Parameters used for padding computation</param>
            /// <returns>Padded message</returns>
            public byte[] EncodeMessage( byte[] dataBytes, RSAParameters parameters )
            {
                //Determine if we can add padding.
                if( dataBytes.Length > GetMaxMessageLength( parameters ) ) {
                    throw new Exception( "Data length is too long. Increase your key size or consider encrypting less data." );
                }

                int padLength = parameters.N.Length - dataBytes.Length - 3;
                BigInteger biRnd = new BigInteger();
                biRnd.genRandomBits( padLength * 8, new Random( DateTime.Now.Millisecond ) );

                byte[] bytRandom = null;
                bytRandom = biRnd.getBytes();

                int z1 = bytRandom.Length;

                //Make sure the bytes are all > 0.
                for( int i = 0; i <= bytRandom.Length - 1; i++ ) {
                    if( bytRandom[i] == 0x00 ) {
                        bytRandom[i] = 0x01;
                    }
                }

                byte[] result = new byte[parameters.N.Length];

                //Add the starting 0x00 byte
                result[0] = 0x00;

                //Add the version code 0x02 byte
                result[1] = 0x02;

                for( int i = 0; i <= bytRandom.Length - 1; i++ ) {
                    z1 = i + 2;
                    result[z1] = bytRandom[i];
                }

                //Add the trailing 0 byte after the padding.
                result[bytRandom.Length + 2] = 0x00;

                //This starting index for the unpadded data.
                int idx = bytRandom.Length + 3;

                //Copy the unpadded data to the padded byte array.
                dataBytes.CopyTo( result, idx );

                return result;
            }
Ejemplo n.º 38
0
// Perform an RSA private key operation on input
public byte [] DoPrivate (byte [] input)
{
    if (input.Length != this.keylen)
        throw new ArgumentException ("input.Length does not match keylen");

    if (ReferenceEquals (this.D, null))
        throw new ArgumentException ("no private key set!");

    BigInteger T = new BigInteger (input);
    if (T >= this.N)
        throw new ArgumentException ("input exceeds modulus");

    T = T.modPow (this.D, this.N);

    byte [] b = T.getBytes ();
    return pad_bytes (b, this.keylen);
}
Ejemplo n.º 39
0
// Convert a big integer to a base 64 string
private string bigint_to_b64 (BigInteger bi)
{
    byte [] b = bi.getBytes ();
    return Convert.ToBase64String (b);
}
Ejemplo n.º 40
0
 //writes mpint in SSH2 format
 public override void WriteBigInteger(BigInteger data)
 {
     byte[] t = data.getBytes();
     int len = t.Length;
     if (t[0] >= 0x80) {
         WriteInt32(++len);
         WriteByte((byte)0);
     }
     else
         WriteInt32(len);
     Write(t);
 }
Ejemplo n.º 41
0
        public override void WriteBigInteger(BigInteger data)
        {
            byte[] image = data.getBytes();
            int off = (image[0] == 0 ? 1 : 0);
            int len = (image.Length - off) * 8;

            int a = len & 0x0000FF00;
            a >>= 8;
            _strm.WriteByte((byte)a);

            a = len & 0x000000FF;
            _strm.WriteByte((byte)a);

            _strm.Write(image, off, image.Length - off);
        }
Ejemplo n.º 42
0
        private void HandleLogonProof(IPacket packet)
        {
            BinaryReader gr = packet.CreateReader();

            var bi_A = new BigInteger(gr.ReadBytes(32).Reverse());
            var bi_M1 = new BigInteger(gr.ReadBytes(20).Reverse());

            byte[] u = H(bi_A.getBytes().Reverse().Concat(bi_B.getBytes().Reverse()));
            var bi_u = new BigInteger(u.Reverse());

            BigInteger bi_Temp2 = (bi_A * bi_v.modPow(bi_u, bi_N)) % bi_N; // v^u
            BigInteger bi_S = bi_Temp2.modPow(bi_b, bi_N); // (Av^u)^b

            byte[] S = bi_S.getBytes().Reverse();
            var S1 = new byte[16];
            var S2 = new byte[16];

            for(int i = 0; i < 16; i++) {
                S1[i] = S[i * 2];
                S2[i] = S[i * 2 + 1];
            }

            var SS_Hash = new byte[40];
            byte[] S1_Hash = H(S1);
            byte[] S2_Hash = H(S2);
            for(int i = 0; i < 20; i++) {
                SS_Hash[i * 2] = S1_Hash[i];
                SS_Hash[i * 2 + 1] = S2_Hash[i];
            }

            _account.SessionKey = (byte[])SS_Hash.Clone();

            var accountRepository = IoC.Resolve<IAccountRepository>();
            accountRepository.Save(_account);
            accountRepository.SubmitChanges();

            byte[] N_Hash = H(bi_N.getBytes().Reverse());
            byte[] G_Hash = H(bi_g.getBytes().Reverse());
            for(int i = 0; (i < 20); i++) {
                N_Hash[i] ^= G_Hash[i];
            }

            byte[] userHash = H(Encoding.UTF8.GetBytes(ClientInfo.AccountName));

            IEnumerable<byte> temp = N_Hash
                .Concat(userHash)
                .Concat(bi_s.getBytes().Reverse())
                .Concat(bi_A.getBytes().Reverse())
                .Concat(bi_B.getBytes().Reverse())
                .Concat(SS_Hash);

            var biM1Temp = new BigInteger(H(temp).Reverse());
            if(biM1Temp != bi_M1) {
                _client.Send(GetLogonProof());
                return;
            }

            temp = bi_A.getBytes().Reverse()
                .Concat(biM1Temp.getBytes().Reverse());
            temp = temp.Concat(SS_Hash);
            byte[] M2 = H(temp);

            _client.Send(GetLogonProof(M2));
        }
Ejemplo n.º 43
0
 public void WriteBigIntWithBits(BigInteger bi)
 {
     WriteInt32(bi.bitCount());
     Write(bi.getBytes());
 }
Ejemplo n.º 44
0
        private byte[] pkcs1unpad2(BigInteger m, int b)
        {
            byte[] bytes = m.getBytes();

            int i = 0;
            while (i < bytes.Length && bytes[i] == 0) ++i;

            if (bytes.Length - i != (b - 1) || bytes[i] != 0x2)
            {
                return null;
            }

            while (bytes[i] != 0)
            {
                if (++i >= bytes.Length)
                {
                    return null;
                }
            }

            byte[] result = new byte[bytes.Length - i + 1];
            int p = 0;
            while (++i < bytes.Length)
            {
                result[p++] = bytes[i];
            }

            return result;
        }