Beispiel #1
0
        public override void init(Session session,
                                  byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C)
        {
            this.session = session;
            this.V_S     = V_S;
            this.V_C     = V_C;
            this.I_S     = I_S;
            this.I_C     = I_C;

            //    sha=new SHA1();
            //    sha.init();
            try
            {
                Type t = Type.GetType(session.getConfig("sha-1"));
                sha = (HASH)(Activator.CreateInstance(t));
                sha.init();
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee);
            }

            buf    = new Buffer();
            packet = new Packet(buf);

            try
            {
                Type t = Type.GetType(session.getConfig("dh"));
                dh = (DH)(Activator.CreateInstance(t));
                dh.init();
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee);
            }

            dh.setP(p);
            dh.setG(g);

            // The client responds with:
            // byte  SSH_MSG_KEXDH_INIT(30)
            // mpint e <- g^x mod p
            //         x is a random number (1 < x < (p-1)/2)

            e = dh.getE();

            packet.reset();
            buf.putByte((byte)SSH_MSG_KEXDH_INIT);
            buf.putMPInt(e);
            session.write(packet);

            state = SSH_MSG_KEXDH_REPLY;
        }
Beispiel #2
0
        //private byte[] f;
        public override void init(Session session,
            byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C)
        {
            this.session = session;
            this.V_S = V_S;
            this.V_C = V_C;
            this.I_S = I_S;
            this.I_C = I_C;

            try
            {
                Type c = Type.GetType(session.getConfig("sha-1"));
                sha = (HASH)(c.newInstance());
                sha.init();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }

            buf = new Buffer();
            packet = new Packet(buf);

            try
            {
                Type c = Type.GetType(session.getConfig("dh"));
                dh = (DH)(c.newInstance());
                dh.init();
            }
            catch (Exception e)
            {
                //      Console.Error.WriteLine(e);
                throw e;
            }

            packet.reset();
            buf.putByte((byte)SSH_MSG_KEX_DH_GEX_REQUEST);
            buf.putInt(min);
            buf.putInt(preferred);
            buf.putInt(max);
            session.write(packet);

            if (JSch.getLogger().isEnabled(Logger.INFO))
            {
                JSch.getLogger().log(Logger.INFO,
                                     "SSH_MSG_KEX_DH_GEX_REQUEST(" + min + "<" + preferred + "<" + max + ") sent");
                JSch.getLogger().log(Logger.INFO,
                                     "expecting SSH_MSG_KEX_DH_GEX_GROUP");
            }

            state = SSH_MSG_KEX_DH_GEX_GROUP;
        }
Beispiel #3
0
        //private byte[] f;

        public override void init(Session session,
                                  byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C)
        {
            this.session = session;
            this.V_S     = V_S;
            this.V_C     = V_C;
            this.I_S     = I_S;
            this.I_C     = I_C;

            try
            {
                Type c = Type.GetType(session.getConfig("sha-1"));
                sha = (HASH)(c.newInstance());
                sha.init();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }

            buf    = new Buffer();
            packet = new Packet(buf);

            try
            {
                Type c = Type.GetType(session.getConfig("dh"));
                dh = (DH)(c.newInstance());
                dh.init();
            }
            catch (Exception e)
            {
                //      Console.Error.WriteLine(e);
                throw e;
            }

            packet.reset();
            buf.putByte((byte)SSH_MSG_KEX_DH_GEX_REQUEST);
            buf.putInt(min);
            buf.putInt(preferred);
            buf.putInt(max);
            session.write(packet);

            if (JSch.getLogger().isEnabled(Logger.INFO))
            {
                JSch.getLogger().log(Logger.INFO,
                                     "SSH_MSG_KEX_DH_GEX_REQUEST(" + min + "<" + preferred + "<" + max + ") sent");
                JSch.getLogger().log(Logger.INFO,
                                     "expecting SSH_MSG_KEX_DH_GEX_GROUP");
            }

            state = SSH_MSG_KEX_DH_GEX_GROUP;
        }
Beispiel #4
0
 private void Form3_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.KeyCode == Keys.D1)
     {
         S.PerformClick();
     }
     else if (e.KeyCode == Keys.D2)
     {
         E.PerformClick();
     }
     else if (e.KeyCode == Keys.D3)
     {
         DE.PerformClick();
     }
     else if (e.KeyCode == Keys.D4)
     {
         Q.PerformClick();
     }
     else if (e.KeyCode == Keys.D5)
     {
         DQ.PerformClick();
     }
     else if (e.KeyCode == Keys.D6)
     {
         H.PerformClick();
     }
     else if (e.KeyCode == Keys.D7)
     {
         DH.PerformClick();
     }
     else if (e.KeyCode == Keys.D8)
     {
         W.PerformClick();
     }
     else if (e.KeyCode == Keys.S)
     {
         if (button4.FlatStyle == FlatStyle.Standard)
         {
             button4.PerformClick();
         }
     }
     else if (e.KeyCode == Keys.A)
     {
         if (button1.FlatStyle == FlatStyle.Standard)
         {
             button1.PerformClick();
         }
     }
 }
Beispiel #5
0
        public void Execute(string[] args)
        {
            try
            {
                options.ParseArguments(args);
            }
            catch (Exception)
            {
                Usage();
                return;
            }

            int g = DH.Generator2;

            if (this.options.IsSet("2"))
            {
                g = DH.Generator2;
            }

            if (this.options.IsSet("5"))
            {
                g = DH.Generator5;
            }

            int bits = 512;

            if (this.options.Arguments.Count == 1)
            {
                bits = Convert.ToInt32(this.options.Arguments[0]);
            }

            Console.Error.WriteLine("Generating DH parameters, {0} bit long safe prime, generator {1}", bits, g);
            Console.Error.WriteLine("This is going to take a long time");

            DH dh = new DH(bits, g, Program.OnGenerator, null);

            string outfile = this.options["out"] as string;

            if (string.IsNullOrEmpty(outfile))
            {
                Console.WriteLine(dh.PEM);
            }
            else
            {
                File.WriteAllText(outfile, dh.PEM);
            }
        }
Beispiel #6
0
        //private byte[] f;

        public override void init(Session session,
                                  byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C)
        {
            this.session = session;
            this.V_S     = V_S;
            this.V_C     = V_C;
            this.I_S     = I_S;
            this.I_C     = I_C;

            //    sha=new SHA1();
            //    sha.init();

            try
            {
                Type t = Type.GetType(session.getConfig("sha-1"));
                sha = (HASH)(Activator.CreateInstance(t));
                sha.init();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            buf    = new Buffer();
            packet = new Packet(buf);

            try
            {
                Type t = Type.GetType(session.getConfig("dh"));
                dh = (DH)(Activator.CreateInstance(t));
                dh.init();
            }
            catch (Exception e)
            {
                throw e;
            }

            packet.reset();
            buf.putByte((byte)0x22);
            buf.putInt(min);
            buf.putInt(preferred);
            buf.putInt(max);
            session.write(packet);

            state = SSH_MSG_KEX_DH_GEX_GROUP;
        }
 public void Dispose()
 {
     if (LocalPrivateKey != null)
     {
         LocalPrivateKey.Dispose();
         LocalPrivateKey = null;
     }
     if (DH != null)
     {
         DH.Dispose();
         DH = null;
     }
     if (LocalPublicKey != null)
     {
         LocalPublicKey.Dispose();
         LocalPublicKey = null;
     }
 }
Beispiel #8
0
        public static void test()
        {
            JSch jsch = new JSch();
            DH   dh1  = null;
            DH   dh2  = null;

            try
            {
                Type t = Type.GetType(jsch.getConfig("dh"));
                dh1 = (DH)(Activator.CreateInstance(t));
                dh1.init();
                dh2 = (DH)(Activator.CreateInstance(t));
                dh2.init();
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee);
            }

            dh1.setP(DHG1.p);
            dh1.setG(DHG1.g);
            dh2.setP(DHG1.p);
            dh2.setG(DHG1.g);

            // The client responds with:
            // byte  SSH_MSG_KEXDH_INIT(30)
            // mpint e <- g^x mod p
            //         x is a random number (1 < x < (p-1)/2)

            byte[] e = dh1.getE();
            byte[] f = dh2.getE();
            Console.WriteLine("Private1 = {0}", hex(e));
            Console.WriteLine();
            Console.WriteLine("Private2 = {0}", hex(f));
            Console.WriteLine();
            dh1.setF(f);
            dh2.setF(e);
            byte[] k1 = dh1.getK();
            byte[] k2 = dh2.getK();
            Console.WriteLine("Public1 = {0}", hex(k1));
            Console.WriteLine();
            Console.WriteLine("Public2 = {0}", hex(k2));
            Console.WriteLine();
        }
Beispiel #9
0
        private void Form1_Load(object sender, EventArgs e)
        {
            CS_DH   = new DH();                                                        //DH_new()
            CS_DH.P = BigNumber.FromArray(g_bytGSYCGAATDHKEParametersPrimeNumber2048); //(*pDH)->p = BN_bin2bn(g_bytGSYCGAATDHKEParametersPrimeNumber2048, sizeof(g_bytGSYCGAATDHKEParametersPrimeNumber2048), NULL);
            CS_DH.G = BigNumber.FromArray(g_bytGSYCGAATDHKEParametersBaseNumber2048);  //(*pDH)->g = BN_bin2bn(g_bytGSYCGAATDHKEParametersBaseNumber2048, sizeof(g_bytGSYCGAATDHKEParametersBaseNumber2048), NULL);

            String m_lpParametersString = CS_DH.PEM.Replace("-----BEGIN DH PARAMETERS-----", "");

            m_lpParametersString = m_lpParametersString.Replace("-----END DH PARAMETERS-----", "");
            m_lpParametersString = m_lpParametersString.Replace("\n", ""); //i2d_DHparams(pDH, lpParameters) + GSYCGAATBase64Encode(&lpParametersString, lpParameters, iLength)
            richTextBox1.Text    = m_lpParametersString;                   //Console.WriteLine("Parameters: {0}\n", m_lpParametersString);

            CS_DH.GenerateKeys();                                          //iResult = DH_generate_key(pDH)
            byte[] bybuf = new byte[256];
            CS_DH.PublicKey.ToBytes(bybuf);                                //iPublicKeyLength = BN_num_bytes(pDH->pub_key);
            String m_lpPublicKeyString = Base64_encode(bybuf);             //GSYCGAATBase64Encode(&lpPublicKeyString, lpPublicKey, iLength)

            richTextBox2.Text = m_lpPublicKeyString;                       //Console.WriteLine("Public Key: {0}\n", m_lpPublicKeyString);
        }
Beispiel #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dh"></param>
        /// <param name="enabledSslProtocols"></param>
        /// <param name="sslStrength"></param>
        /// <param name="asyncCallback"></param>
        /// <param name="asyncState"></param>
        /// <returns></returns>
        public virtual IAsyncResult BeginAuthenticateAsServer(
            DH dh,
            SslProtocols enabledSslProtocols,
            SslStrength sslStrength,
            AsyncCallback asyncCallback,
            Object asyncState)
        {
            if (IsAuthenticated)
            {
                throw new InvalidOperationException("SslStream is already authenticated");
            }
            // Initialize the server stream
            SslAnonStreamServer server_stream = new SslAnonStreamServer(InnerStream, false, dh, enabledSslProtocols, sslStrength);

            // Set the internal sslStream
            sslStream = server_stream;
            // Start the read operation
            return(BeginRead(new byte[0], 0, 0, asyncCallback, asyncState));
        }
Beispiel #11
0
        public void CanCreateFromDH()
        {
            using (var dh = new DH())
            {
                dh.GenerateKeys();

                using (var key = new CryptoKey(dh))
                {
                    Assert.AreEqual(CryptoKey.KeyType.DH, key.Type);
                    Assert.AreEqual(dh.Handle, key.GetDH().Handle);
                }

                using (var key = new CryptoKey())
                {
                    key.Assign(dh);
                    Assert.AreEqual(dh.Handle, key.GetDH().Handle);
                }
            }
        }
Beispiel #12
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var salty = ECDHAES256s.AES.GetSalt();
                var id    = context.Request.Path.TrimStart('/').Split(new string[] { ".key" }, StringSplitOptions.None)[0];

                var pk  = context.Request.QueryString["pk"];
                var cng = new CNG(HttpServerUtility.UrlTokenDecode(pk));
                cng = DH.B(cng); //MAKE KEY

                context.Application[id + "pass"] = Convert.ToBase64String(cng.Key);
                context.Response.ContentType     = "text/plain";
                context.Response.Write(HttpServerUtility.UrlTokenEncode(cng.PublicKey));
            }
            catch
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("error");
            }
        }
        public void ShowStartDialog(string message)
        {
            var card = new Card {
                Padding = new Thickness(32), Margin = new Thickness(16), Width = 350
            };
            var stackPanel = new StackPanel {
                HorizontalAlignment = HorizontalAlignment.Center
            };
            var textBlock = new TextBlock {
                Text = message, TextWrapping = TextWrapping.Wrap
            };

            var buttonStack = new StackPanel {
                Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Center
            };
            var yesButton = new Button {
                Content = "YES", Width = 100
            };
            var noButton = new Button {
                Content = "NO", Width = 100
            };

            var btnstyle = Application.Current.FindResource("MaterialDesignFlatButton") as Style;

            if (btnstyle != null)
            {
                yesButton.Style = btnstyle;
                noButton.Style  = btnstyle;
            }
            yesButton.Command = DialogYesPrompt;
            noButton.Command  = DialogNoPrompt;

            stackPanel.Children.Add(textBlock);
            buttonStack.Children.Add(yesButton);
            buttonStack.Children.Add(noButton);
            stackPanel.Children.Add(buttonStack);
            card.Content = stackPanel;

            DH?.ShowDialog(card);
        }
Beispiel #14
0
        public override void init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C)
        {
            m_session = session;
            m_V_S = V_S;
            m_V_C = V_C;
            m_I_S = I_S;
            m_I_C = I_C;

            try
            {
                Type t = Type.GetType(session.getConfig("sha-1"));
                m_sha = (HASH)(Activator.CreateInstance(t));
                m_sha.init();
            }
            catch (Exception) { }

            m_buf = new Buffer();
            m_packet = new Packet(m_buf);

            try
            {
                Type t = Type.GetType(session.getConfig("dh"));
                m_dh = (DH)(Activator.CreateInstance(t));
                m_dh.init();
            }
            catch (Exception e)
            {
                throw e;
            }

            m_packet.reset();
            m_buf.putByte((byte)0x22);
            m_buf.putInt(m_min);
            m_buf.putInt(m_preferred);
            m_buf.putInt(m_max);
            session.write(m_packet);

            m_state = SSH_MSG_KEX_DH_GEX_GROUP;
        }
Beispiel #15
0
        private void button1_Click(object sender, EventArgs e)
        {
            StreamWriter sw = new StreamWriter(Application.StartupPath + "\\GPS.txt");
            object       DX, DH, DY, mSpeed;
            int          ItemID = IInfoTree.FindItem("car");

            if (ItemID == 0)
            {
                //tempDynamicObject = IObjectManager.CreateDynamicObject(DynamicMotionStyle.MOTION_GROUND_VEHICLE, DynamicObjectType.DYNAMIC_3D_MODEL, Application.StartupPath + "\\car.xpc", 3, HeightStyleCode.HS_ON_TERRAIN, 0, this.textBox4.Text);
                tempDynamicObject = IObjectManager.CreateDynamicObject(DynamicMotionStyle.MOTION_GROUND_VEHICLE, DynamicObjectType.DYNAMIC_3D_MODEL, Application.StartupPath + "\\car.xpc", 1, HeightStyleCode.HS_ON_TERRAIN, 0, this.textBox4.Text);
                tempDynamicObject.SetPosition(Convert.ToDouble(this.textBox1.Text), Convert.ToDouble(this.textBox2.Text), -30, -30, 0, 0);
            }
            for (int i = 0; i < tempDynamicObject.NumberOfWaypoints; i++)
            {
                tempDynamicObject.GetWaypoint(i, out DX, out DH, out DY, out mSpeed);
                if (tempDynamicObject.CurrentWaypoint != 1)
                {
                    tempDynamicObject.ModifyWaypoint(i, Convert.ToDouble(this.textBox1.Text), 0, Convert.ToDouble(this.textBox2.Text), Convert.ToDouble(this.textBox3.Text));
                    sw.WriteLine(i.ToString() + "\t" + DX.ToString() + "\t" + DH.ToString() + "\t" + DY.ToString() + "\t" + mSpeed.ToString());
                }
                sw.Close();
            }
        }
        public SslAnonStreamServer(
            Stream stream,
            bool ownStream,
            DH dh,
            SslProtocols enabledSslProtocols,
            SslStrength sslStrength)
            : base(stream, ownStream)
        {
            // Initialize the SslContext object
            InitializeServerContext(dh, enabledSslProtocols, sslStrength);

            // Initalize the Ssl object
            ssl = new Ssl(sslContext);
            // Initialze the read/write bio
            read_bio  = BIO.MemoryBuffer(false);
            write_bio = BIO.MemoryBuffer(false);
            // Set the read/write bio's into the the Ssl object
            ssl.SetBIO(read_bio, write_bio);
            read_bio.SetClose(BIO.CloseOption.Close);
            write_bio.SetClose(BIO.CloseOption.Close);
            // Set the Ssl object into server mode
            ssl.SetAcceptState();
        }
Beispiel #17
0
        public Protocol Authenticate(string username, string password)
        {
            /* Number of authentication tries. */
            int tries = 3;

            /* Set username and password. */
            this._username = Encoding.UTF8.GetBytes(username);
            this._password = Encoding.UTF8.GetBytes(password);

            while (true)
            {
                /* Connect to a spotify server. */
                this._protocol.Connect();

                /* Send and receive initial packets. */
                try
                {
                    this._protocol.SendInitialPacket();
                    this._protocol.ReceiveInitialPacket();

                    break;
                }
                catch (ProtocolException e)
                {
                    if (tries-- > 0)
                    {
                        continue;
                    }

                    throw new AuthenticationException(e);
                }
            }

            /* Generate auth hash. */
            this.GenerateAuthHash();

            /* Compute shared key (Diffie Hellman key exchange). */
            this._dhSharedKey = DH.ComputeSharedKey(this._dhClientKeyPair.PrivateKey, this._dhServerPublicKey);

            /* Prepare a message to authenticate. */
            ByteBuffer buffer = ByteBuffer.Allocate(((this._authHash.Length + this._clientRandom.Length) + this._serverRandom.Length) + 1);

            /* Append auth hash, client and server random to message. */
            buffer.Put(this._authHash);
            buffer.Put(this._clientRandom);
            buffer.Put(this._serverRandom);
            buffer.Put((byte)0x00); /* Changed later */
            buffer.Flip();

            /* Get message bytes and allocate space for HMACs. */
            byte[] bytes  = new byte[buffer.Remaining];
            byte[] hmac   = new byte[5 * 20];
            int    offset = 0;

            buffer.Get(bytes);

            /* Run HMAC SHA-1 over message. 5 times. */
            for (int i = 1; i <= 5; i++)
            {
                /* Change last byte (53) of message. */
                bytes[bytes.Length - 1] = (byte)i;

                /* Compute HMAC SHA-1 using the shared key. */
                Hash.HmacSha1(bytes, this._dhSharedKey, hmac, offset);

                /* Overwrite first 20 bytes of message with output from this round. */
                for (int j = 0; j < 20; j++)
                {
                    bytes[j] = hmac[offset + j];
                }

                /* Advance to next position. */
                offset += 20;
            }
            /* Use field of HMACs to setup keys for Shannon stream cipher (key length: 32). */
            Array.Copy(hmac, 20, this._keySend, 0, 32);
            Array.Copy(hmac, 52, this._keyRecv, 0, 32);

            /* Set stream cipher keys. */
            this._shannonSend.key(this._keySend);
            this._shannonRecv.key(this._keyRecv);

            /*
             * First 20 bytes of HMAC output is used to key another HMAC computed
             * for the second authentication packet send by the client.
             */
            Array.Copy(hmac, 0, this._keyHmac, 0, 20);

            /* Solve puzzle */
            this.SolvePuzzle();

            /* Generate HMAC */
            this.GenerateAuthHmac();
            try
            {
                this._protocol.SendAuthenticationPacket();
                this._protocol.ReceiveAuthenticationPacket();
            }
            catch (ProtocolException e)
            {
                throw new AuthenticationException(e);
            }
            return(this._protocol);
        }
Beispiel #18
0
        public unsafe void GenerateKeys(byte[] privateKey, byte[] publicKey)
        {
            if (_localKey.IsAllocated)
            {
                return;
            }
            byte[] q, p;
            byte   g;

            switch (_namedGroup)
            {
            case NamedGroup.ffdhe2048:
                _keyExchangeSize = 256;
                g = Rfc7919Ffdhe.G2048;
                q = Rfc7919Ffdhe.Q2048;
                p = Rfc7919Ffdhe.P2048;
                break;

            case NamedGroup.ffdhe3072:
                _keyExchangeSize = 384;
                g = Rfc7919Ffdhe.G3072;
                q = Rfc7919Ffdhe.Q3072;
                p = Rfc7919Ffdhe.P3072;
                break;

            case NamedGroup.ffdhe4096:
                _keyExchangeSize = 512;
                g = Rfc7919Ffdhe.G4096;
                q = Rfc7919Ffdhe.Q4096;
                p = Rfc7919Ffdhe.P4096;
                break;

            case NamedGroup.ffdhe6144:
                _keyExchangeSize = 768;
                g = Rfc7919Ffdhe.G6144;
                q = Rfc7919Ffdhe.Q6144;
                p = Rfc7919Ffdhe.P6144;
                break;

            case NamedGroup.ffdhe8192:
                _keyExchangeSize = 1024;
                g = Rfc7919Ffdhe.G8192;
                q = Rfc7919Ffdhe.Q8192;
                p = Rfc7919Ffdhe.P8192;
                break;

            default:
                ExceptionHelper.ThrowException(new ArgumentOutOfRangeException());
                return;
            }

            fixed(byte *qPtr = q)
            fixed(byte *pPtr = p)
            {
                var qBN = BN_bin2bn(qPtr, q.Length, IntPtr.Zero);
                var gBN = BN_bin2bn(&g, 1, IntPtr.Zero);
                var pBN = BN_bin2bn(pPtr, p.Length, IntPtr.Zero);

                _localKey = DH_new();
                ThrowOnError(DH_set0_pqg(_localKey, pBN, qBN, gBN));
            }
            if (privateKey != null)
            {
                fixed(byte *pPtr = privateKey)
                fixed(byte *pubPtr = publicKey)
                {
                    var privBN = BN_bin2bn(pPtr, privateKey.Length, IntPtr.Zero);
                    var pubBN  = BN_bin2bn(pubPtr, publicKey.Length, IntPtr.Zero);

                    ThrowOnError(DH_set0_key(_localKey, pubBN, privBN));
                }
            }
            else
            {
                ThrowOnError(DH_generate_key(_localKey));
            }
        }
Beispiel #19
0
 public void SetTmpDhCallback(DH dh)
 {
     DHCallBack_delegate = new Native.DHCallBack(() => { return(dh.Handle); });
     Native.SSL_CTX_set_tmp_dh_callback(this.ptr, DHCallBack_delegate);
 }
Beispiel #20
0
        public Session(int clientOS, int clientRevision)
        {
            /* Initialize protocol with this session. */
            this._protocol = new Protocol(this);

            /* Set client properties. */
            this._clientId       = CLIENT_ID;
            this._clientOs       = clientOS;
            this._clientRevision = clientRevision;

            /* Client and server generate 16 random bytes each. */
            this._clientRandom = new byte[16];
            this._serverRandom = new byte[16];

            RandomBytes.GetRandomBytes(ref this._clientRandom);

            /* Allocate buffer for server RSA key. */
            this._serverBlob = new byte[256];

            /* Allocate buffer for salt and auth hash. */
            this._username = null;
            this._password = null;
            this._salt     = new byte[10];
            this._authHash = new byte[20];

            /*
             * Create a private and public DH key and allocate buffer
             * for shared key. This, along with key signing, is used
             * to securely agree on a session key for the Shannon stream
             * cipher.
             */
            this._dhClientKeyPair = DH.GenerateKeyPair(768);
            this._dhSharedKey     = new byte[96];

            /* Generate RSA key pair. */
            this._rsaClientKeyPair = Sharpotify.Crypto.RSA.GenerateKeyPair(1024);

            /* Allocate buffers for HMAC and Shannon stream cipher keys. */
            this._keyHmac   = new byte[20];
            this._authHmac  = new byte[20];
            this._keyRecv   = new byte[32];
            this._keySend   = new byte[32];
            this._keyRecvIv = 0;
            this._keySendIv = 0;

            /* Stream cipher instances. */
            this._shannonRecv = new Shannon();
            this._shannonSend = new Shannon();

            /* Allocate buffer for puzzle solution. */
            this._puzzleDenominator = 0;
            this._puzzleMagic       = 0;
            this._puzzleSolution    = new byte[8];

            /* Found in Storage.dat (cache) at offset 16. Modify first byte of cache hash. */
            this._cacheHash = new byte[] {
                (byte)0xf4, (byte)0xc2, (byte)0xaa, (byte)0x05,
                (byte)0xe8, (byte)0x25, (byte)0xa7, (byte)0xb5,
                (byte)0xe4, (byte)0xe6, (byte)0x59, (byte)0x0f,
                (byte)0x3d, (byte)0xd0, (byte)0xbe, (byte)0x0a,
                (byte)0xef, (byte)0x20, (byte)0x51, (byte)0x95
            };
            this._cacheHash[0] = (byte)new Random().Next();

            /* Not initialized. */
            this._initialClientPacket = null;
            this._initialServerPacket = null;
        }
Beispiel #21
0
 private static extern int Internal_DH_set0_pqg(DH dh, BIGNUM p, BIGNUM q, BIGNUM g);
Beispiel #22
0
 internal static extern unsafe int DH_compute_key(byte *key, BIGNUM pub_key, DH dh);
Beispiel #23
0
 internal static extern void DH_get0_key(DH dh, out BIGNUM pub_key, out BIGNUM priv_key);
Beispiel #24
0
        public override void init(Session session,
                                  byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C)
        {
            this.session = session;
            this.V_S     = V_S;
            this.V_C     = V_C;
            this.I_S     = I_S;
            this.I_C     = I_C;

            //    sha=new SHA1();
            //    sha.init();
            try
            {
                Type c = Type.GetType(session.getConfig("sha-1"));
                sha = (HASH)(c.newInstance());
                sha.init();
            }
            catch (Exception ee)
            {
                Console.Error.WriteLine(ee);
            }

            buf    = new Buffer();
            packet = new Packet(buf);

            try
            {
                Type c = Type.GetType(session.getConfig("dh"));
                dh = (DH)(c.newInstance());
                dh.init();
            }
            catch (Exception ee)
            {
                //Console.Error.WriteLine(e);
                throw ee;
            }

            dh.setP(p);
            dh.setG(g);

            // The client responds with:
            // byte  SSH_MSG_KEXDH_INIT(30)
            // mpint e <- g^x mod p
            //         x is a random number (1 < x < (p-1)/2)

            e = dh.getE();

            packet.reset();
            buf.putByte((byte)SSH_MSG_KEXDH_INIT);
            buf.putMPInt(e);
            session.write(packet);

            if (JSch.getLogger().isEnabled(Logger.INFO))
            {
                JSch.getLogger().log(Logger.INFO,
                                     "SSH_MSG_KEXDH_INIT sent");
                JSch.getLogger().log(Logger.INFO,
                                     "expecting SSH_MSG_KEXDH_REPLY");
            }

            state = SSH_MSG_KEXDH_REPLY;
        }
Beispiel #25
0
        public void Execute(string[] args)
        {
            try
            {
                options.ParseArguments(args);
            }
            catch (Exception)
            {
                Usage();
                return;
            }

            string infile = this.options.GetString("infile");
            BIO    bin    = Program.GetInFile(options.GetString("infile"));

            DH     dh;
            string inform = this.options["inform"] as string;

            if (inform == "PEM")
            {
                dh = DH.FromParametersPEM(bin);
            }
            else if (inform == "DER")
            {
                dh = DH.FromParametersDER(bin);
            }
            else
            {
                Usage();
                return;
            }

            if (this.options.IsSet("text"))
            {
                Console.WriteLine(dh);
            }

            if (this.options.IsSet("check"))
            {
                DH.CheckCode check = dh.Check();
                if ((check & DH.CheckCode.NotSuitableGenerator) != 0)
                {
                    Console.WriteLine("the g value is not a generator");
                }
                if ((check & DH.CheckCode.CheckP_NotPrime) != 0)
                {
                    Console.WriteLine("p value is not prime");
                }
                if ((check & DH.CheckCode.CheckP_NotSafePrime) != 0)
                {
                    Console.WriteLine("p value is not a safe prime");
                }
                if ((check & DH.CheckCode.UnableToCheckGenerator) != 0)
                {
                    Console.WriteLine("unable to check the generator value");
                }
                if (check == 0)
                {
                    Console.WriteLine("DH parameters appear to be ok");
                }
            }

            if (this.options.IsSet("code"))
            {
                Console.WriteLine("-code is currently not implemented.");
            }

            if (!this.options.IsSet("noout"))
            {
                string outfile = this.options["outfile"] as string;
                BIO    bout;
                bool   outmem = false;
                if (string.IsNullOrEmpty(outfile))
                {
                    bout   = BIO.MemoryBuffer();
                    outmem = true;
                }
                else
                {
                    bout = BIO.File(outfile, "w");
                }

                string outform = this.options["outform"] as string;
                if (outform == "DER")
                {
                    dh.WriteParametersDER(bout);
                }
                else if (outform == "PEM")
                {
                    dh.WriteParametersPEM(bout);
                }
                else
                {
                    Usage();
                    return;
                }

                if (outmem)
                {
                    Stream cout = Console.OpenStandardOutput();
                    ArraySegment <byte> segment = bout.ReadBytes((int)bout.NumberWritten);
                    cout.Write(segment.Array, segment.Offset, segment.Count);
                }
            }
        }
Beispiel #26
0
 private static extern int Internal_DH_set0_key(DH dh, BIGNUM pub_key, BIGNUM priv_key);
Beispiel #27
0
 internal static extern int DH_set0_pqg(DH dh, BIGNUM p, BIGNUM q, BIGNUM g);
Beispiel #28
0
        public override void init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C)
        {
            m_session = session;
            m_V_S = V_S;
            m_V_C = V_C;
            m_I_S = I_S;
            m_I_C = I_C;
            try
            {
                Type t = Type.GetType(session.getConfig("sha-1"));
                m_sha = (HASH)(Activator.CreateInstance(t));
                m_sha.init();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            m_buf = new Buffer();
            m_packet = new Packet(m_buf);

            try
            {
                Type t = Type.GetType(session.getConfig("dh"));
                m_dh = (DH)(Activator.CreateInstance(t));
                m_dh.init();
            }
            catch (Exception ee)
            {
                throw ee;
            }

            m_dh.P = m_p;
            m_dh.G = m_g;

            // The client responds with:
            // byte  SSH_MSG_KEXDH_INIT(30)
            // mpint e <- g^x mod p
            //         x is a random number (1 < x < (p-1)/2)

            m_e = m_dh.E;

            m_packet.reset();
            m_buf.putByte((byte)SSH_MSG_KEXDH_INIT);
            m_buf.putMPInt(m_e);
            session.write(m_packet);

            m_state = SSH_MSG_KEXDH_REPLY;
        }
Beispiel #29
0
 internal static extern int DH_set0_key(DH dh, BIGNUM pub_key, BIGNUM priv_key);
Beispiel #30
0
 internal static extern int DH_size(DH dh);
 internal static extern int DH_generate_key(DH dh);
Beispiel #32
0
        public static void DH_set0_key(DH dh, BIGNUM pub_key, BIGNUM priv_key)
        {
            var result = Internal_DH_set0_key(dh, pub_key, priv_key);

            ThrowOnErrorReturnCode(result);
        }
Beispiel #33
0
        public static void DH_set0_pqg(DH dh, BIGNUM p, BIGNUM q, BIGNUM g)
        {
            var result = Internal_DH_set0_pqg(dh, p, q, g);

            ThrowOnErrorReturnCode(result);
        }
Beispiel #34
0
        //private byte[] f;
        public override void init(Session session,
            byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C)
        {
            this.session = session;
            this.V_S = V_S;
            this.V_C = V_C;
            this.I_S = I_S;
            this.I_C = I_C;

            //    sha=new SHA1();
            //    sha.init();

            try
            {
                Type t = Type.GetType(session.getConfig("sha-1"));
                sha = (HASH) (Activator.CreateInstance(t));
                sha.init();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            buf = new Buffer();
            packet = new Packet(buf);

            try
            {
                Type t = Type.GetType(session.getConfig("dh"));
                dh = (DH) (Activator.CreateInstance(t));
                dh.init();
            }
            catch (Exception e)
            {
                throw e;
            }

            packet.reset();
            buf.putByte(0x22);
            buf.putInt(min);
            buf.putInt(preferred);
            buf.putInt(max);
            session.write(packet);

            state = SSH_MSG_KEX_DH_GEX_GROUP;
        }
Beispiel #35
0
        public override void init(Session session,
            byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C)
        {
            this.session = session;
            this.V_S = V_S;
            this.V_C = V_C;
            this.I_S = I_S;
            this.I_C = I_C;

            //    sha=new SHA1();
            //    sha.init();
            try
            {
                Type c = Type.GetType(session.getConfig("sha-1"));
                sha = (HASH)(c.newInstance());
                sha.init();
            }
            catch (Exception ee)
            {
                Console.Error.WriteLine(ee);
            }

            buf = new Buffer();
            packet = new Packet(buf);

            try
            {
                Type c = Type.GetType(session.getConfig("dh"));
                dh = (DH)(c.newInstance());
                dh.init();
            }
            catch (Exception ee)
            {
                //Console.Error.WriteLine(e);
                throw ee;
            }

            dh.setP(p);
            dh.setG(g);

            // The client responds with:
            // byte  SSH_MSG_KEXDH_INIT(30)
            // mpint e <- g^x mod p
            //         x is a random number (1 < x < (p-1)/2)

            e = dh.getE();

            packet.reset();
            buf.putByte((byte)SSH_MSG_KEXDH_INIT);
            buf.putMPInt(e);
            session.write(packet);

            if (JSch.getLogger().isEnabled(Logger.INFO))
            {
                JSch.getLogger().log(Logger.INFO,
                                     "SSH_MSG_KEXDH_INIT sent");
                JSch.getLogger().log(Logger.INFO,
                                     "expecting SSH_MSG_KEXDH_REPLY");
            }

            state = SSH_MSG_KEXDH_REPLY;
        }
Beispiel #36
0
		public override void init(Session session,
			byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C) 
		{
			this.session=session;
			this.V_S=V_S;      
			this.V_C=V_C;      
			this.I_S=I_S;      
			this.I_C=I_C;      

			//    sha=new SHA1();
			//    sha.init();
			try
			{
				Type t=Type.GetType(session.getConfig("sha-1"));
				sha=(HASH)(Activator.CreateInstance(t));
				sha.init();
			}
			catch(Exception ee)
			{
				Console.WriteLine(ee);
			}

			buf=new Buffer();
			packet=new Packet(buf);

			try
			{
				Type t=Type.GetType(session.getConfig("dh"));
				dh=(DH)(Activator.CreateInstance(t));
				dh.init();
			}
			catch(Exception ee)
			{
				throw ee;
			}

			dh.setP(p);
			dh.setG(g);

			// The client responds with:
			// byte  SSH_MSG_KEXDH_INIT(30)
			// mpint e <- g^x mod p
			//         x is a random number (1 < x < (p-1)/2)

			e=dh.getE();

			packet.reset();
			buf.putByte((byte)SSH_MSG_KEXDH_INIT);
			buf.putMPInt(e);
			session.write(packet);

			state=SSH_MSG_KEXDH_REPLY;
		}
Beispiel #37
0
		static void Main(string[] args)
		{
			Authorities();
			return;

			SimpleSerialNumber seq = new SimpleSerialNumber();
			X509CertificateAuthority ca = X509CertificateAuthority.SelfSigned(
				seq,
				new X509Name("CN=."),
				TimeSpan.FromDays(10)
			);

			Console.WriteLine(ca.Certificate);

			DSA dsa = new DSA(new DSAParameters(512));
			CryptoKey key = new CryptoKey(dsa);
			X509Request req = new X509Request(0, new X509Name("CN=com."), key);
			req.Sign(key, MessageDigest.DSS1);

			X509Certificate cert = ca.ProcessRequest(req, TimeSpan.FromDays(10));
			Console.WriteLine(cert);
			Console.WriteLine("CA Verified: " + cert.Verify(ca.Key));
			Console.WriteLine("Self Verified: " + cert.Verify(key));

			SimpleSerialNumber serial2 = new SimpleSerialNumber();
			X509CertificateAuthority caSelf = new X509CertificateAuthority(
				cert,
				key,
				serial2);

			X509Request req2 = cert.CreateRequest(key, MessageDigest.DSS1);
			X509Name subject = req2.Subject;
			Console.WriteLine("Request1: " + req);
			Console.WriteLine("Request2: " + req2);

			X509Certificate cert2 = caSelf.ProcessRequest(req2, TimeSpan.FromDays(10));
			Console.WriteLine("Cert2: " + cert2);

			DH dh = new DH(128, 5);

			MessageDigestContext mdc = new MessageDigestContext(MessageDigest.DSS1);
			byte[] msg = dh.PublicKey;
			byte[] sig = mdc.Sign(msg, key);

			Console.WriteLine(dh);
			Console.WriteLine("DH P         : " + BitConverter.ToString(dh.P));
			Console.WriteLine("DH G         : " + BitConverter.ToString(dh.G));
			Console.WriteLine("DH Secret Key: " + BitConverter.ToString(dh.PrivateKey));
			Console.WriteLine("DH Public Key: " + BitConverter.ToString(msg));
			Console.WriteLine("DH Signature : " + BitConverter.ToString(sig));

			Console.WriteLine(mdc.Verify(msg, sig, key));
		}