a and b: 10 20
Inside test(double) a: 88
Inside test(double) a: 123.2
更多精彩尽在139ya网址导航 www.139ya.com
Secure Socket Layer (SSL) technology allows web browsers and web servers to communicate over a secure connection. In this secure connection, the data that is being sent is encrypted before being sent and then is decrypted upon receipt and before processing. Both the browser and the server encrypt all traffic before sending any data. SSL addresses the following important security considerations.
To install and configure SSL support on your stand-alone web server, you need the following components. SSL support is already provided if you are using the Application Server. If you are using a different web server, consult the documentation for your product.
To verify that SSL support is enabled, see Verifying SSL Support.
Note: Digital certificates for the Application Server have already been generated and can be found in the directory <J2EE_HOME>/domains/domain1/config/. These digital certificates are self-signed and are intended for use in a development environment; they are not intended for production purposes. For production purposes, generate your own certificates and have them signed by a CA.
To use SSL, an application server must have an associated certificate for each external interface, or IP address, that accepts secure connections. The theory behind this design is that a server should provide some kind of reasonable assurance that its owner is who you think it is, particularly before receiving any sensitive information. It may be useful to think of a certificate as a "digital driver's license" for an Internet address. It states with which company the site is associated, along with some basic contact information about the site owner or administrator.
The digital certificate is cryptographically signed by its owner and is difficult for anyone else to forge. For sites involved in e-commerce or in any other business transaction in which authentication of identity is important, a certificate can be purchased from a well-known certificate authority (CA) such as VeriSign or Thawte.
Sometimes authentication is not really a concern--for example, an administrator may simply want to ensure that data being transmitted and received by the server is private and cannot be snooped by anyone eavesdropping on the connection. In such cases, you can save the time and expense involved in obtaining a CA certificate and simply use a self-signed certificate.
SSL uses public key cryptography, which is based on key pairs. Key pairs contain one public key and one private key. If data is encrypted with one key, it can be decrypted only with the other key of the pair. This property is fundamental to establishing trust and privacy in transactions. For example, using SSL, the server computes a value and encrypts the value using its private key. The encrypted value is called a digital signature. The client decrypts the encrypted value using the server's public key and compares the value to its own computed value. If the two values match, the client can trust that the signature is authentic, because only the private key could have been used to produce such a signature.
Digital certificates are used with the HTTPS protocol to authenticate web clients. The HTTPS service of most web servers will not run unless a digital certificate has been installed. Use the procedure outlined later to set up a digital certificate that can be used by your web server to enable SSL.
One tool that can be used to set up a digital certificate is keytool, a key and certificate management utility that ships with the J2SE SDK. It enables users to administer their own public/private key pairs and associated certificates for use in self-authentication (where the user authenticates himself or herself to other users or services) or data integrity and authentication services, using digital signatures. It also allows users to cache the public keys (in the form of certificates) of their communicating peers. For a better understanding of keytool and public key cryptography, read the keytool documentation at the following URL:
A server certificate has already been created for the Application Server. The certificate can be found in the <J2EE_HOME>/domains/domain1/config/ directory. The server certificate is in keystore.jks. The cacerts.jks file contains all the trusted certificates, including client certificates.
If necessary, you can use keytool to generate certificates. The keytool stores the keys and certificates in a file termed a keystore, a repository of certificates used for identifying a client or a server. Typically, a keystore contains one client or one server's identity. The default keystore implementation implements the keystore as a file. It protects private keys by using a password.
The keystores are created in the directory from which you run keytool. This can be the directory where the application resides, or it can be a directory common to many applications. If you don't specify the keystore file name, the keystores are created in the user's home directory.
To create a server certificate follow these steps:
Run keytool to generate the server keystore, which we will name keystore.jks. This step uses the alias server-alias to generate a new public/private key pair and wrap the public key into a self-signed certificate inside keystore.jks. The key pair is generated using an algorithm of type RSA, with a default password of changeit. For more information on keytool options, see its online help at http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/keytool.html.
Note: RSA is public-key encryption technology developed by RSA Data Security, Inc. The acronym stands for Rivest, Shamir, and Adelman, the inventors of the technology.
From the directory in which you want to create the keystore, run keytool with the following parameters.
<JAVA_HOME>\bin\keytool -genkey -alias server-alias
-keyalg RSA -keypass changeit -storepass changeit
-keystore keystore.jks
When you press Enter, keytool prompts you to enter the server name, organizational unit, organization, locality, state, and country code. Note that you must enter the server name in response to keytool's first prompt, in which it asks for first and last names. For testing purposes, this can be localhost. The host specified in the keystore must match the host identified in the host variable specified in the <INSTALL>/j2eetutorial14/examples/common/build.properties when running the example applications.
keystore.jks into the file server.cer. <JAVA_HOME>\bin\keytool -export -alias server-alias
-storepass changeit -file server.cer -keystore keystore.jks
cacerts.jks and add the server certificate to the trust-store, run keytool from the directory where you created the keystore and server certificate. Use the following parameters: <JAVA_HOME>\bin\keytool -import -v -trustcacerts
-alias server-alias -file server.cer
-keystore cacerts.jks -keypass changeit
-storepass changeit
Information on the certificate, such as that shown next, will display.
<INSTALL>/j2eetutorial14/examples/gs 60% keytool -import
-v -trustcacerts -alias server-alias -file server.cer
-keystore cacerts.jks -keypass changeit -storepass changeit
Owner: CN=localhost, OU=Sun Micro, O=Docs, L=Santa Clara, ST=CA, C=US
Issuer: CN=localhost, OU=Sun Micro, O=Docs, L=Santa Clara, ST=CA, C=US
Serial number: 3e932169
Valid from: Tue Apr 08
Certificate fingerprints:
MD5: 52:9F:49:68:ED:78:6F:39:87:F3:98:B3:6A:6B:0F:90
SHA1: EE:2E:2A:A6:9E:03:9A:3A:1C:17:4A:28:5E:97:20:78:3F:
Trust this certificate? [no]:
yes, and then press the Enter or Return key. The following information displays: Certificate was added to keystore
[Saving cacerts.jks]
After you've created a digital certificate, you will want to have it signed by its owner. After the digital certificate has been cryptographically signed by its owner, it is difficult for anyone else to forge. For sites involved in e-commerce or any other business transaction in which authentication of identity is important, a certificate can be purchased from a well-known certificate authority such as VeriSign or Thawte.
As mentioned earlier, if authentication is not really a concern, you can save the time and expense involved in obtaining a CA certificate and simply use the self-signed certificate.
Follow the steps in Creating a Server Certificate, to create your own server certificate, have it signed by a CA, and import the certificate into keystore.jks.
Make sure that when you create the certificate, you follow these rules:
keytool prompts you to enter your first and last name. In response to this prompt, you must enter the name of your server. For testing purposes, this can be localhost.host variable specified in the <INSTALL>/j2eetutorial14/examples/common/build.properties file for running the example applications.keystore.jks should match the password of your keystore, keystore.jks. This is a bug. If there is a mismatch, the Java SDK cannot read the certificate and you get a "tampered" message.keystore.jks, you must either change your keystore's password to the default password (changeit) or change the default password to your keystore's password: To specify that the Application Server should use the new keystore for authentication and authorization decisions, you must set the JVM options for the Application Server so that they recognize the new keystore. To use a different keystore than the one provided for development purposes, follow these steps.
-Djavax.net.ssl.keyStore=${com.sun.aas.instanceRoot}/config/keystore.jks
-Djavax.net.ssl.trustStore=${com.sun.aas.instanceRoot}/config/cacerts.jks
-Djavax.net.ssl.keyStorePassword=your_new_password This section discusses setting up client-side authentication. When both server-side and client-side authentication are enabled, it is called mutual, or two-way, authentication. In client authentication, clients are required to submit certificates that are issued by a certificate authority that you choose to accept. From the directory where you want to create the client certificate, run keytool as outlined here. When you press Enter, keytool prompts you to enter the server name, organizational unit, organization, locality, state, and country code.
Note: You must enter the server name in response to keytool's first prompt, in which it asks for first and last names. For testing purposes, this can be localhost. The host specified in the keystore must match the host identified in the host variable specified in the <INSTALL>/j2eetutorial14/examples/common/build.properties file. If this example is to verify mutual authentication and you receive a runtime error stating that the HTTPS host name is wrong, re-create the client certificate, being sure to use the same host name that you will use when running the example. For example, if your machine name is duke, then enter duke as the certificate CN or when prompted for first and last names. When accessing the application, enter a URL that points to the same location--for example, https://duke:8181/mutualauth/hello. This is necessary because during SSL handshake, the server verifies the client certificate by comparing the certificate name and the host name from which it originates.
To create a keystore named client-keystore.jks that contains a client certificate named client.cer, follow these steps:
<JAVA_HOME>\bin\keytool -genkey -alias client-alias -keyalg RSA -keypass changeit
-storepass changeit -keystore keystore.jks
client.cer. <JAVA_HOME>\bin\keytool -export -alias client-alias
-storepass changeit -file client.cer -keystore keystore.jks
<J2EE_HOME>/domains/domain1/config/cacerts.jks. Run keytool from the directory where you created the keystore and client certificate. Use the following parameters: <JAVA_HOME>\bin\keytool -import -v -trustcacerts
-alias client-alias -file client.cer
-keystore <J2EE_HOME>/domains/domain1/config/cacerts.jks
-keypass changeit -storepass changeit
The keytool utility returns this message:
Owner: CN=J2EE Client, OU=Java Web Services, O=Sun, L=Santa Clara, ST=CA, C=US
Issuer: CN=J2EE Client, OU=Java Web Services, O=Sun, L=Santa Clara, ST=CA, C=US
Serial number: 3e39e66a
Valid from: Thu Jan 30 18:58:50 PST 2003 until: Wed Apr 30
19:58:50 PDT 2003
Certificate fingerprints:
MD5: 5A:B0:4C:88:4E:F8:EF:E9:E5:8B:53:BD:D0:AA:8E:5A
SHA1:90:00:36:5B:E0:A7:A2:BD:67:DB:EA:37:B9:61:3E:26:B3:89:46:
32
Trust this certificate? [no]: yes
Certificate was added to keystore
For an example application that uses mutual authentication, see Example: Client-Certificate Authentication over HTTP/SSL with JAX-RPC. For information on verifying that mutual authentication is running, see Verifying That Mutual Authentication Is Running.
To check the contents of a keystore that contains a certificate with an alias server-alias, use this command:
keytool -list -keystore keystore.jks -alias server-alias -v
To check the contents of the cacerts file, use this command:
keytool -list -keystore cacerts.jks
An SSL connector is preconfigured for the Application Server. You do not have to configure anything. If you are working with another application server, see its documentation for setting up its SSL connector.
For testing purposes, and to verify that SSL support has been correctly installed, load the default introduction page with a URL that connects to the port defined in the server deployment descriptor:
The https in this URL indicates that the browser should be using the SSL protocol. The localhost in this example assumes that you are running the example on your local machine as part of the development process. The 8181 in this example is the secure port that was specified where the SSL connector was created in Using SSL. If you are using a different server or port, modify this value accordingly.
The first time a user loads this application, the New Site Certificate or Security Alert dialog box displays. Select Next to move through the series of dialog boxes, and select Finish when you reach the last dialog box. The certificates will display only the first time. When you accept the certificates, subsequent hits to this site assume that you still trust the content.
The SSL protocol is designed to be as efficient as securely possible. However, encryption and decryption are computationally expensive processes from a performance standpoint. It is not strictly necessary to run an entire web application over SSL, and it is customary for a developer to decide which pages require a secure connection and which do not. Pages that might require a secure connection include login pages, personal information pages, shopping cart checkouts, or any pages where credit card information could possibly be transmitted. Any page within an application can be requested over a secure socket by simply prefixing the address with https: instead of http:. Any pages that absolutely require a secure connection should check the protocol type associated with the page request and take the appropriate action if https: is not specified.
Using name-based virtual hosts on a secured connection can be problematic. This is a design limitation of the SSL protocol itself. The SSL handshake, where the client browser accepts the server certificate, must occur before the HTTP request is accessed. As a result, the request information containing the virtual host name cannot be determined before authentication, and it is therefore not possible to assign multiple certificates to a single IP address. If all virtual hosts on a single IP address need to authenticate against the same certificate, the addition of multiple virtual hosts should not interfere with normal SSL operations on the server. Be aware, however, that most client browsers will compare the server's domain name against the domain name listed in the certificate, if any (this is applicable primarily to official, CA-signed certificates). If the domain names do not match, these browsers will display a warning to the client. In general, only address-based virtual hosts are commonly used with SSL in a production environment.
This section discusses setting up client-side authentication. As mentioned earlier, when both server-side and client-side authentication are enabled, it is called mutual, or two-way, authentication. In client authentication, clients are required to submit certificates that are issued by a certificate authority that you choose to accept. If you regulate it through the application (via the Client-Certificate authentication requirement), the check is performed when the application requires client authentication. You must enter the keystore location and password in the web server configuration file to enable SSL, as discussed in Using SSL.
Here are two ways to enable mutual authentication over SSL:
Client-Certificate using deploytool. This enforces mutual authentication by modifying the deployment descriptor of the given application. By enabling client authentication in this way, client authentication is enabled only for a specific resource controlled by the security constraint. Setting client authentication in this way is discussed in Example: Client-Certificate Authentication over HTTP/SSL with JAX-RPC.clientAuth property in the certificate realm to true. To do this, follow these steps:certificate. The certificate realm is used for all transfers over HTTP with SSL.clientAuth to the server. Enter clientAuth in the Name field, and enter true in the Value field.When client authentication is enabled in both of these ways, client authentication will be performed twice.
You can verify that mutual authentication is working by obtaining debug messages. This should be done at the client end, and this example shows how to pass a system property in targets.xml so that targets.xml forks a client with javax.net.debug in its system properties, which could be added in a file such as <INSTALL>/j2eetutorial14/examples/security/common/targets.xml.
To enable debug messages for SSL mutual authentication, pass the system property javax.net.debug=ssl,handshake, which will provide information on whether or not mutual authentication is working. The following example modifies the run-mutualauth-client target from the <INSTALL>/j2eetutorial14/examples/security/common/targets.xml file by adding sysproperty as shown in bold:
import java.net.*;
import java.io.*;
public class testPost {
public static void main() {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL("http://localhost/projectname/servletname"); //构造好这个URL对象,参数就是你要通信的servlet地址,实际测试的时候,这个URL可以从Properties文件中取得,以增加灵活性
conn = (HttpURLConnection)url.openConnection(); //打开,创建Connection对象
conn.setRequestMethod("POST"); //设定请求方式为POST
conn.setDoOutput(true); //一定要设为true,因为要发送数据
//下面开始设定Http头
conn.setRequestProperty("Content-Type","multipart/form-data; boundary=Bounday---");
conn.setRequestProperty("Cache-Control","no-cache");
.......
// 传送送据
OutputStream buf = conn.getOutoutStream();
buf = new BufferedOutputStream(buf);
OutputStreamWriter out = new OutputStreamWriter (buf);
out.write("这里是要传送的数据");
//比方说如下的格式,当然这是自己规定的格式,这些都可以从配置文件中设定,然后读取
//Bounday---
//Content-Disposition: form-data; name="testRequestHeader"
// Data = aabbccddeeffgghh
//--Bounday---
out.flush(); //这个一定要
out.clost();
//接收数据
InputStream in = conn.getInputStream();
in = new BufferedOutputStream(buf);
Reader rData = new InputStreamReader(in);
int c;
System.out.println("=====================Result==========================");
while((c=rData.read()) != -1)
System.out.print((char)c);
System.out.println("===================================================");
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
1. import java.io.*;
2. import java.util.*;
3. import java.net.*;
4.
5. public class WebTest {
6.
7. public static void main(String[] args) {
8.
9. System.out.println("beging...");
10. DownLoadPages("http://login.xiaonei.com/Login.do", "d:/fileDown.txt");
11. // visit("http://www.xiaonei.com");
12. System.out.println("end.");
13. }
14.
15. public static void DownLoadPages(String urlStr, String outPath) {
16. int chByte = 0;
17.
18. URL url = null;
19.
20. HttpURLConnection httpConn = null;
21.
22. InputStream in = null;
23.
24. FileOutputStream out = null;
25.
26. try {
27. String post = "email=" + URLEncoder.encode("e-mail", "UTF-8")
28. + "&password=" + "password";
29. url = new URL(urlStr);
30.
31. httpConn = (HttpURLConnection) url.openConnection();
32.
33. //setInstanceFollowRedirects can then be used to set if
34. //redirects should be followed or not and this should be used before the
35. //connection is established (via getInputStream, getResponseCode, and other
36. //methods that result in the connection being established).
37.
38. httpConn.setFollowRedirects(false);
39.
40. //inorder to disable the redirects
41. httpConn.setInstanceFollowRedirects(false);
42.
43. httpConn.setDoOutput(true);
44. httpConn.setDoInput(true);
45. httpConn.setRequestProperty("User-Agent",
46. "Mozilla/5.0 (compatible; MSIE 6.0; Windows NT)");
47. httpConn.setRequestProperty("Content-Type",
48. "application/x-www-form-urlencoded");
49.
50. //ok now, we can post it
51. PrintStream send = new PrintStream(httpConn.getOutputStream());
52. send.print(post);
53. send.close();
54. URL newURL = new URL(httpConn.getHeaderField("Location"));
55. System.out.println("the URL has move to "
56. + httpConn.getHeaderField("Location"));
57. httpConn.disconnect();
58.
59. // OK, now we are ready to get the cookies out of the URLConnection
60. String cookies = getCookies(httpConn);
61. System.out.println(cookies);
62. httpConn = (HttpURLConnection) newURL.openConnection();
63. httpConn.setRequestProperty("User-Agent",
64. "Mozilla/5.0 (compatible; MSIE 6.0; Windows NT)");
65. httpConn.setRequestProperty("Content-Type",
66. "application/x-www-form-urlencoded");
67. httpConn.setRequestProperty("Cookie", cookies);
68.
69. httpConn.setDoInput(true);
70. in = httpConn.getInputStream();
71. out = new FileOutputStream(new File(outPath));
72.
73. chByte = in.read();
74. while (chByte != -1) {
75. out.write(chByte);
76. //System.out.println(chByte);
77. chByte = in.read();
78. }
79. } catch (Exception e) {
80. e.printStackTrace();
81. }
82. }
83.
84. public static String getCookies(HttpURLConnection conn) {
85. StringBuffer cookies = new StringBuffer();
86. String headName;
87. for (int i = 7; (headName = conn.getHeaderField(i)) != null; i++) {
88. StringTokenizer st = new StringTokenizer(headName, "; ");
89. while (st.hasMoreTokens()) {
90. cookies.append(st.nextToken() + "; ");
91. }
92. }
93. return cookies.toString();
94. }
95. }
The most commonly used type parameter names are: