Internet security programming with Java 2 standard version (J2SE) 1.4

zhaozj2021-02-17  82

Internet security programming with Java 2 standard version (J2SE) 1.4

Part I: Server

Qusay H. mahmoud is in November 2002 madman translation in November 2002

Any message transmitted in a computer network or Internet may be intercepted, in which some are more sensitive, such as credit card numbers or other private data. In order to better use Internet in Enterprise Environment and E-Commerce, application software must use encryption, verification, and secure communication protocols to protect users' data security. Secure Hypertext Transfer Protocol, HTTPS is HTTP, which is built on secure sockets layer, ssl, which has been successfully applied to e-commerce.

Java Secure Socket Extension, JSSE enables Internet security communication into reality. It is a 100% pure Java implementation SSL framework. This package allows Java developers to develop secure network applications; to establish secure data channels based on TCP / IP-based application protocols such as HTTP, FTP, Telnet, or NTTP, establish a secure data channel between the client and the server.

JSSE has been integrated in Java 2 SDK standard version 1.4 (J2SE 1.4), this is a good news. This means that as long as you have J2SE 1.4, you don't need to download other packages, you can create an SSL-based Internet application. This series of articles have 2 articles, which is a manual on the development of safety interent applications for future markets. This article is primarily the server side, and the next article is the client. This article starts from an overview SSL and tells you how to do the following:

Using JSSE API combines a simple HTTP server in your C / S app to develop a simple HTTP server to process HTTPS requests to develop, configure and run a secure HTTP server using Keytool that contains keytool in J2SE.

Overview SSL

The SSL protocol is developed in 1994 to allow the server (typical, such as browser) and HTTP servers to communicate. It encrypts, source verification, data integrity, etc., to protect data exchanged on unsafe public networks. SSL has some versions: SSL 2.0 has security hazards, now there is a few unused; SSL 3.0 applications are relatively widely; finally, Transport Layer Security, TLS), which is improved by SSL 3.0, has become Internet standard And applied to almost all newly near software.

Prior to data propagation, encryption techniques protect data from illegal by transforming data into meaningless content. The process is: data is encrypted, transmitted, then decrypt at the other end (client or server).

Source certification is an approach to verifying the identity of the data sender. The browser or other client attempts to communicate with the web server for the first time, the server will presented a set of trust information in the form of a certificate.

The certificate is issued and verified by the authoritative certification body (CA) - a trustworthy authorized author. A certificate describes the public key of a person. A signature document will make a guarantee: I prove that this public key in the document belongs to the entity named in this document. Signature (authoritative certification body). Currently well-known authoritative certifications include VeriSign, Entrust and Thawte. Note that the SSL / TLS certificate now used is an X.509 certificate.

Data integrity is to ensure that data is not changed during transmission.

Sedents of SSL and TCP / IP protocol

SSL is a solid sleeve layer. Its connection action and TCP connection are similar, so you can imagine SSL connections just a secure TCP connection because the location of SSL is above the TCP in the Protocol Hierarchy, as shown in Figure 1. Note this is important. However, SSL does not support certain TCP characteristics, such as frequency band data. Figure 1: Levels of SSL and TCP / IP protocol

AC-lived encryption technology

One of the features of SSL is to provide a standard method for providing AC's transactions for e-commerce. SSL's developers recognize that not everyone will use the same client software, so that all clients will include any detailed encryption algorithm. The same is true for the server. Clients and servers located at both ends of the connection require AC encryption and decryption algorithm (cryptographic group) when initializing "handshake". If they do not have enough public algorithms, the connection attempt will fail.

Note When the SSL allows the client and the server to verify each other, the typical method is that only the server side is verified on the SSL layer. The client is typically verified by the application layer, password transmitted by the SSL protection channel. This mode is often used in banks, shares trading, and other secure network applications.

SSL is completely "handshake" protocol as shown in Figure 2. It shows the information exchange order in the SSL "handshake" process.

Figure 2: SSL "Handshake" protocol

The meaning of these news is as follows:

ClientHello: Send information to the client's client, such as SSL protocol versions, session ID, and password group information, such as encryption algorithms and supportable sizes. ServerHello: Select the server that best password group and sends this message to the client. The password group includes client and server support. CERTIFICATE: The server sends a certificate containing its public key to the client. This message is optional and will need it when the server requests verification. In other words, the certificate is used to confirm the identity of the server to the client. CERTIFICATE REQUEST: This message is only sent when it is asking itself only on the server. Most e-commerce applications do not require a client to do itself. Server Key Exchange: If the certificate contains the public key to the server is not sufficient to exchange, the message is sent. ServerHellodone: This message notifies the client, and the server has completed the initialization of the AC process. CERTIFICATE: Send only when the server requests the client to verify yourself. Client Key Exchage: The client generates a key to the server sharing. If you use the Rivest-Shamir-Adelman (RSA) encryption algorithm, the client will send the key encrypted to the server after using the public key of the server. The server decrypts the message with your own private key or key to get the shared key. Now, clients and servers share a secure-distributed key. Certificate Verify: If the server requests to verify the client, this message allows the server to complete the verification process. Change Cipher SPEC: The client requires the server to use the encryption mode. Finished: The client tells the server that it is ready to communicate. Change Cipher SPEC: The server requires the client to use the encryption mode. Finished: The server tells the client that it is ready to communicate. This is the sign of the SSL "handshake" result. Encrypted Data: The client and server can now develop communication on encrypted information on a secure communication channel.

JSS

Java Secure Conditioning (JSSE) provides an SSL and TLS protocol implemented by a framework and a 100% pure Java implementation. It provides mechanisms such as data encryption, server authentication, message completion, and optional client authentication. Outside of JSS, it will be complex, fundamentally encryption algorithm, which reduces the risk of sensitive or dangerous security attacks. In addition, since it can seamlessly combine SSL in the application, it is very simple to develop safe applications. The JSSE framework can support many different secure communication protocols, such as SSL 2.0 and 3.0 and TLS 1.0, but J2SE V1.4.1 only implements SSL 3.0 and TLS 1.0. JSSE programming

The JSSE API provides an extended network socket class, credit, and key management, and socket factory framework for simplifying socket creation, to expand two packages for java.security and java.net. These classes are included in the javax.net and javax.net.ssl ​​packages.

SSLSocket and SSLServersocket

Javax.net.ssl.sslsocket is a subclass of java.net.socket, so he supports all standard socket methods, and some methods for newly adding a security socket. The javax.net.ssl.sslServersocket class is similar to the SSLSocket class, just it is used to create a server socket, while SSLSocket is not.

Create a SSLSocket instance how two methods:

Use the SSLSocketFactory instance to execute the Createsocket method to create. It is obtained by the Accept method of SSLServersocket.

SSLSocketFactory and SSLServersocketFactory

The Javax.Net.ssl.SSLSocketFactory class is an object factory for creating a security socket. Javax.net.ssl.sslServersocketFactory is also such a factory, but it is used to create a secure server socket.

You can get the SSLSocketFactory instance by the following method:

Execute the SSLSocketFactory.getDefault method to get a default factory. Construct a new factory through a specific configuration behavior.

Note that the default factory configuration is only allowed to verify.

Safe existing Client / Server applications

Integrated SSL in existing C / S applications to make it secure, and you can do it. In order to make the server becomes safe, the black displayed content in the following example is required:

Import java.io. *;

Import javax.net.ssl. *;

Public class server {

INT port = portnumber;

SSLServersocket Server;

Try {

SSLSERVERSOCKETFAACTORY FACTORY =

SSLServersocketFactory) SSLServersocketFactory.getDefault ();

Server = (SSLServersocket)

Factory.createServersocket (portnumber);

SSLSocket Client = (SSLSocket)

Server.accept ();

// Create Input and Output Street STREAMS as Usual

// send Secure Messages to Client Through T

// output stream

// Receive Secure Messages from Clom Clom Cliant Through

// the input stream

} catch (exception e) {}

}

In order to make the client becomes safe, the following example is required to display the black display:

Import java.io. *;

Import javax.net.ssl. *;

Public class client {

...

Try {

SSLSocketFactory Factory = (SSLSocketFactory)

SSLSocketFactory.getDefault ();

Server = (SSLServersocket)

Factory.createServersocket (portnumber);

SSLSocket Client = (SSLSocket)

Factory.createsocket (ServerHost, Port);

// Create Input and Output Street STREAMS as Usual

// send Secure Messages to Server Through the

// Output Stream Receive Secure SECURE

// Messages from Server Through The Input Stream. INPUT STREAM

} catch (exception e) {

}

}

Sunjsse provider

J2SE V1.4.1 and a JSSE provider, SunJSS is released. Sunjsse is installed and pre-registered with Java encryption system. Please consider SunJsse as an implementation that provides SSL V3.0 and TLS V1.0 implementations, as well as ordinary SSL and TLS password groups. If you want to find your implementation (here is SunJsse), you can call the GetSupportedCiphersuites method for SSLSocket. However, not all of these password groups are available. In order to find out those who are available, call the GeTENABLEDCIPHERSUITES method. This list can be changed with the setENabledciphersuites method.

A complete example

I found that the most complicated thing to develop JSS is related to system settings and management certificates and keys. In this example, I demonstrate how to develop, configure, and run a complete HTTP server application that supports the GET request method.

HTTP overview

Hypertext Transfer Protocol, HTTP is a "request-response" application protocol. This protocol supports a fixed method such as GET, POST, PUT, DELETE, and so on. The GET method is generally requested to request resources to the server. Here are two examples of GET requests:

Get / http / 1.0 get /names.html http / 1.0

Unsafe HTTP server

In order to develop an HTTP server, you have to understand how the HTTP protocol works. This server is a simple server that only supports the GET request method. Code Example 1 is the implementation of this example. This is a multi-threaded HTTP server, and the ProcessConnection class is used to perform new requests in different threads. When the server receives a request from the browser, it parses this request and finds the required document. If the requested document is available on the server, then the requested document will be sent to the server by the ShipDocument method. If the requested document is not open, the send to the server is an error message.

Code example 1: httpserver.java

Import java.io. *;

Import java.net. *;

Import java.util.StringTokenizer;

/ **

* This class imports a multithreaded Simple HTTP

* Server That Supports the get request method.

* IT Listens on Port 44, Waits Client Requests, And

* Serves Documents.

* /

Public clas httpserver {

// the port number Which The Server

// Will Be listening on

Public static final int http_port = 8080;

Public Serversocket GetServer () throws exception {

Return New Serversocket (http_port);

}

// Multi-Threading - Create a New Connection

// for Each Request

Public void run () {

Serversocket Listen;

Try {

Listen = Get Server ();

While (true) {

Socket client = listen.accept ();

ProcessConnection CC = New

ProcessConnection (Client);

}

} catch (exception e) {

System.out.println ("Exception:

E.getMessage ());

}

}

// main program

Public static void main (String Argv []) Throws

EXCEPTION {

Httpserver httpserver = new httpserver ();

httpserver.run ();

}

}

Class ProcessConnection Extends thread {

Socket client;

BufferedReader IS;

Dataoutputstream OS;

Public ProcessConnection (Socket S) {// Constructor

Client = S;

Try {

IS = New BufferedReader (New InputStreamReader)

Client.getInputStream ()));

OS = New DataOutputStream (Client.getOutputStream ());

} catch (ioexception e) {

System.out.println ("Exception:" E.getMessage ());

}

this.start (); // Thread Starts Here ... this start ()

Will Call Run ()

}

Public void run () {

Try {

// Get a Request and Parse IT.

String Request = is.readline ();

System.out.println ("Request: Request);

StringTokenizer ST = New StringTokenizer (Request);

IF ((st.countToKens ()> = 2) &&

St.NextToken (). Equals ("get")) {

IF ((Request =

St.NextToken ()). StartSwith ("/"))

Request = Request.substring (1);

IF (Request.Equals (")) Request = Request " INDEX.HTML ";

FILE F = New File (Request);

Shipdocument (OS, F);

} else {

Os.WriteBytes ("400 Bad Request");

}

Client.Close ();

} catch (exception e) {

System.out.println ("Exception:"

E.getMessage ());

}

}

/ **

* Read The Requested File and Ships IT

* to the browser if found.

* /

Public Static Void Shipdocument (DataOutputStream OUT,

FILE F) THROWS EXCEPTION {

Try {

DataInputStream in = New

DataInputStream (New FileInputStream (f));

INT LEN = (int) f.Length ();

BYTE [] BUF = New byte [LEN];

IN.Readfully (BUF);

In.Close ();

Out.WriteBytes ("HTTP / 1.0 200 OK / R / N");

Out.WriteBytes ("Content-Length:"

F.Length () "/ r / n");

Out.WriteBytes ("Content-Type:

TEXT / HTML / R / N / R / N ");

Out.write (buf);

Out.flush ();

} catch (exception e) {

Out.writebytes (" error </ title></p> <p></ hEAD> <body> / r / n / r / n ");</p> <p>Out.writebytes ("HTTP / 1.0 400" E.getMessage () "/ r / n");</p> <p>Out.WriteBytes ("Content-Type: Text / HTML / R / N / R / N");</p> <p>Out.WriteBytes ("</ body> </ html>");</p> <p>Out.flush ();</p> <p>} finally {</p> <p>Out.close ();</p> <p>}</p> <p>}</p> <p>}</p> <p>Experimental HTTPSERVER Class:</p> <p>Save the code of HTTPServer in the file httpserver.java and select a directory to store it there. Compiling HTTPServer.java with Javac to create some HTML files as an example, there is a "index.html" because it is the default HTML document in this example. Run httpserver. The server is running with 8080 ports when running. Open a web browser and issue a request: http: // localhost: 8080 or http://127.0.0.1:8080/index.html.</p> <p>Note: Can you think of HTTPSERVER may receive some malicious URLs? For example, like http: // serverdomainname: 8080 /../../ etc / passwd or http: // serverdomainname: 8080 // somefile.txt, etc. As an exercise, modify HTTPServer so that it does not allow access to these URLs. Tip: Write your own securityManager or use java.lang.securitymanager. You can add statements system.setSecurityManager (new java.lang.securitymanager) to the first row of the main method to install this secure manager. Try it!</p> <p>Extend httpserver to handle https: // URL</p> <p>Now, I want to modify the HTTPServer class so that it becomes safe. I hope that the HTTP server can handle https: // URL requests. I mentioned before, JSSe allows you to make it easy to integrate SSL to your application.</p> <p>Create a server certificate</p> <p>As I mentioned earlier, SSL uses a certificate to verify. Certificates must be created for clients and servers that need to use SSL to ensure communication security. The certificate used by JSS is created with Java KeyTool released with J2SE. Use the following command to create an RSA certificate for the HTTP server.</p> <p>Prompt> KeyTool -Genkey -Keystore ServerKeys -Keyalg RSA -Alaias Qusay</p> <p>This command generates a certificate referenced by alias Qusay and saves it in a file called ServerKeys. When you have a certificate, this tool will prompt us some information, as information below, where the black content is I wrote.</p> <p>ENTER KeyStore Password: HelloThere</p> <p>What is your first and last name?</p> <p>[Unknown]: Ultra.domain.com</p> <p>What is the name of your Organizational Unit?</p> <p>[Unknown]: training and consulting</p> <p>What is the name of your organization?</p> <p>[Unknown]: javacourses.com</p> <p>What is the name of your city orientation?</p> <p>[Unknown]: Toronto</p> <p>What is the name of your state or province?</p> <p>[Unknown]: Ontario</p> <p>What is the two-letter country code for this unit?</p> <p>[Unknown]: CA</p> <p>IS CN = Ultra, Ou = training and consulting,</p> <p>O = javacourses.com, L = Toronto, ST = ONTARIO, C = CA CORRECT?</p> <p>[no]: YES</p> <p>ENTER Key Password for</p> <p>(Return if Same As KeyStore Password):</p> <p>Hiagain</p> <p>As you can see, KeyTool prompts to enter a password for KeyStore, because letting the server can access the keystore must let it know. Tool also requires an alias to enter a password. If you like, these password information can be specified from the command line by KeyTool, using the parameters -storepass and -Keypass. Note I used "Ultra.domain.com" as a name, this name is a name for my machine. You should enter the host name or IP address of the server. When you run the keytool command, it may take a few seconds to generate your password, and you can see your machine's speed.</p> <p>Since I created a certificate for the server, I can now modify httpserver make it safe. If you check the httpserver class, you will notice the GetServer method to return a server socket. That is, you only need to modify the GetServer method to let it return a secure server socket. In the code example 2, the part of the black is the change. Please note that I change the port number to 443, this is the HTTPS default port number. It is also very worth noting that the port numbers between 0 and 1023 are reserved. If you run httpsserver at different ports, the URL should be: https: // localhost: portnumber. But if you run httpsserver at the 443 port, then the URL should be: https: // localhost.</p> <p>Sample Code 2: httpsserver.java</p> <p>Import java.io. *;</p> <p>Import java.net. *;</p> <p>Import javax.net. *;</p> <p>Import javax.net.ssl. *;</p> <p>Import java.security. *;</p> <p>Import java.util.StringTokenizer;</p> <p>/ **</p> <p>* This class imports a multithreaded Simple Https</p> <p>* Server That Supports the get request method.</p> <p>* IT Listens On Port 44, Waits Client Requests</p> <p>* And Serves Documents.</p> <p>* /</p> <p>Public class httpsserver {</p> <p>String KeyStore = "ServerKeys";</p> <p>Char keystorepass [] = "HelloThere" .tochararray ();</p> <p>Char keypassword [] = "hiagain" .tochararray ();</p> <p>// The port number Which The Server Will Be Listening On</p> <p>Public static final int https_port = 443;</p> <p>Public Serversocket GetServer () throws exception {</p> <p>KeyStore Ks = KeyStore.GetInstance ("jks");</p> <p>Ks.Load (New FileInputStream (KeyStore), KeyStorePass;</p> <p>KeyManagerFactory KMF =</p> <p>KeyManagerFactory.getInstance ("sunx509");</p> <p>Kmf.init (KS, Keypassword);</p> <p>SSLCONText SSLContext =</p> <p>SSLCONText.getInstance ("SSLV3");</p> <p>SSLContext.init (kmf.getKeyManagers (), null, null; serversocketfactory ssf =</p> <p>SSLContext.getServersocketFactory ();</p> <p>SSLSERVERSOCKET Serversocket = (SSLServersocket)</p> <p>SSF.CREATSERVERSOCKET (https_port);</p> <p>Return Serversocket;</p> <p>}</p> <p>// Multi-Threading - Create a New Connection</p> <p>// for Each Request</p> <p>Public void run () {</p> <p>Serversocket Listen;</p> <p>Try {</p> <p>Listen = Get Server ();</p> <p>While (true) {</p> <p>Socket client = listen.accept ();</p> <p>ProcessConnection CC = New</p> <p>ProcessConnection (Client);</p> <p>}</p> <p>} catch (exception e) {</p> <p>System.out.println ("Exception:" E.getMessage ());</p> <p>}</p> <p>}</p> <p>// main program</p> <p>Public static void main (string argv []) throws exception {</p> <p>HTTPSSERVER HTTPS = New httpsserver ();</p> <p>Https.run ();</p> <p>}</p> <p>}</p> <p>These lines:</p> <p>String KeyStore = "ServerKeys"; char keystorepass [] = "HelloThere" .tochararray (); char keypassword [] = "hiagain" .tocharRay ();</p> <p>Specifies the name, password, and key password of KeyStore. The password text directly in the code is a bad idea, but we can specify a password at the command line when running the server.</p> <p>Other JSSE code in the GetServer method:</p> <p>It visits ServerKeys KeyStore, JSK is Java KeyStore (a keystore generated by KeyTool). Create X.509 key management with KeyManagerFactory to KeyStore. SSLCONText is an environment that implements JSSE. Use it to create ServersocketFactory that can create SSLServersocket. Although we specify SSL 3.0, the implementation of returns often supports other protocol versions, such as TLS 1.0. Old browser uses SSL 3.0 more.</p> <p>Note that the client's authentication is not required. If you want the server to request the client to verify, use: ServerSocket.setNeedClientAuth (true).</p> <p>Now use the HTTPSSERVER class to do an experiment:</p> <p>Save the HTTPSSERVER and PROCESSCONNECTION (above the code) in the file httpsserver.java. Let httpsserver.java created with KeyTool's Serverkyes file in the same directory. Compile HTTPSSERVER with Javac. Run httpsserver. By default it should use 443 ports, but if you can't use it on this port, select another port number greater than 1024. Open a web browser and enter a request: https: // localhost or https://127.0.0.1. This is the case where the fake translation server uses 443 ports. If it is not this port, use: use: https: // localhost: Port You get a safe warning pop-up window when you enter https: // URL in your browser, just like Figure 3. This is because the HTTP server certificate is generated by himself. In other words, it is created by unknown CA, and this CA is found in the CA saved in your browser. There is an option to show your certificate (check it is the correct certificate and who is named) and install the certificate, reject the certificate or accept the certificate.</p> <p>Figure 3: Servers issued by unknown CA</p> <p>Note: It is a good idea to produce your own certificate in the private system internally. But in public systems, it is best to obtain certificates from well-known CA to avoid security warnings for your browser.</p> <p>If you accept the certificate, you can see the page after the secure connection. When you visit the same website, the browser will no longer pop up the security warning. Note that there are many websites use https, and the certificate is generated or produced by unknown CA. For example, https://www.jam.ca. If you have not visited this page, you will see a safety warning like Figure 3.</p> <p>Note: After you accept the certificate, it is only valid for the current session, that is, if you completely exit the browser, it is invalid. Netscape and Microsoft Internet Explorer (msie) allow you to be permanently guaranteed. The method in MSIE is: Select "View Certificate" shown in Figure 3 and select "Install Certificate" in the new window.</p> <p>to sum up</p> <p>This article talked about SSL and describes the JSSE framework and its implementation. The example in the article can explain that the SSL integrates into your C / S apps is a very easy thing. An example of a secure HTTP server is given, you can use it to perform experiments. The JSSE API also introduces the JSSE API and a web browser that can happen.</p> <p>Published in the computer world network knowledge center (http://www.ccw.com.cn/ceter)</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-31324.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="31324" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.041</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'ZPPjFZjoVZxQl2_2BzWQZBMutf7JVUToLQ0hdZaQH1C3y9kehCQMIirVCLyxP6lKY61VXHiNiJi53i658VCG_2F8FA_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>