


Java keystore implements SSL two-way authentication [client is php and java]
Nov 09, 2016 pm 02:30 PM1. First build the server-side environment:
Preparation work: a tomcat6, jdk7, openssl, javawebservice test project
2. Construction process:
Reference http://blog.csdn.net/chow__zh/article/details/ 8998499
1.1 Generate server certificate
keytool -genkey -v -alias tomcat -keyalg RSA -keystore D:/SSL/server/tomcat.keystore -dname "CN=127.0.0.1,OU=zlj,O=zlj, L=Peking,ST=Peking,C=CN" -validity 3650 -storepass zljzlj -keypass zljzlj
Note:
keytool is the certificate generation tool provided by JDK. For the usage of all parameters, see keytool –help
-genkey Create new Certificate
-v details
-alias tomcat uses "tomcat" as the alias of this certificate. Here you can modify it as needed
-keyalg RSA specified algorithm
-keystore D:/SSL/server/tomcat.keystore save path and file name
-dname "CN=127.0.0.1,OU=zlj,O=zlj,L=Peking ,ST=Peking,C=CN" The identity of the certificate issuer. The CN here must be consistent with the access domain name after issuance. But since we issue the certificate ourselves, there will still be a warning if you access it in a browser.
-validity 3650 Certificate validity period, in days
-storepass zljzlj Certificate access password
-keypass zljzlj Certificate private key
1.2 Generate client certificate
Execute command:
keytool ‐genkey ‐v ‐alias client ‐keyalg RSA ‐ storetype PKCS12 ‐keystore D:/SSL/client/client.p12 ‐dname "CN=client,OU=zlj,O=zlj,L=bj,ST=bj,C=CN" ‐validity 3650 ‐storepass client ‐keypass client
Description:
Parameter description is the same as above. The -dname certificate issuer identity here can be different from the previous one. So far, these two certificates have no relationship. The next thing to do is to establish a trust relationship between the two.
1.3 Export client certificate
Execute command:
keytool ‐export ‐alias client ‐keystore D:/SSL/client/client.p12 ‐storetype PKCS12 ‐storepass client ‐rfc ‐file D:/SSL/client/client.cer
Description:
-export Execute export
-file File path of the exported file
1.4 Add the client certificate to the server certificate trust list
Execute command:
keytool ‐import ‐alias client ‐v ‐file D:/SSL/client/client .cer ‐keystore D:/SSL/server/tomcat.keystore ‐storepass zljzlj
Instructions:
The parameter description is the same as before. The password provided here is the access password for the server certificate.
1.5 Export server certificate
Execute command:
keytool -export -alias tomcat -keystore D:/SSL/server/tomcat.keystore -storepass zljzlj -rfc -file D:/SSL/server/tomcat.cer
Instructions:
Export the server certificate. The password provided here is also the password for the server certificate.
1.6 Generate client trust list
Execute command:
keytool -import -file D:/SSL/server/tomcat.cer -storepass zljzlj -keystore D:/SSL/client/client.truststore -alias tomcat –noprompt
Instructions:
Let the client trust the server certificate
2. Configure the server to only allow HTTPS connections
2.1 Configure /conf/server.xml in the Tomcat directory
Xml code Favorite code
sslProtocol="TLS" keystoreFile="D:/SSL/server/tomcat.keystore"
keystorePass ="zljzlj" truststoreFile="D:/SSL/server/tomcat.keystore"
truststorePass="zljzlj" />
Note:
This content in server.xml was originally commented out. If you want to use https The default port is 443, please modify the port parameter here. ClientAuth="true" specifies two-way certificate authentication.
2. Import client.p12 into the browser’s personal certificate item.
At this time, enter https://127.0.0.1:8443/ and a certificate selection will appear. Click OK and you will be prompted whether the https page is unsafe or not. Click Continue. The server is now set up.
3.java calls the server side to directly load the code:
package test; import javax.xml.namespace.QName; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType; /** * * @author gshen * */ public class TestEcVoteNotice { public static void main(String [] args) throws Exception { System.setProperty("javax.net.ssl.trustStorePassword","zljzlj"); System.setProperty("javax.net.ssl.keyStoreType","PKCS12") ; System.setProperty("javax.net.ssl.keyStore","D:/SSL/client/client.p12") ; System.setProperty("javax.net.ssl.keyStorePassword","client") ; System.setProperty("javax.net.debug", "all"); //wsdl地址 String endpoint = "https://192.168.1.146:8443/pro/ws/getInfoService?wsdl"; //http://jarfiles.pandaidea.com/ 搜索axis.jar并下載,Service類(lèi)在axis.jar Service service = new Service(); //http://jarfiles.pandaidea.com/ 搜索axis.jar并下載,Call類(lèi)在axis.jar Call call = null; try { call = (Call) service.createCall(); //設(shè)置Call的調(diào)用地址 call.setTargetEndpointAddress(new java.net.URL(endpoint)); //根據(jù)wsdl中 <wsdl:import location="https://192.168.10.24:8443/ShinService/HelloWorld?wsdl=HelloService.wsdl" //namespace="http://server.cxf.shinkong.cn/" /> , //<wsdl:operation name="findALL"> call.setOperationName(new QName("http://ws.task.xm.com/","sayHello")); //參數(shù)1對(duì)應(yīng)服務(wù)端的@WebParam(name = "tableName") 沒(méi)有設(shè)置名稱(chēng)為arg0 call.addParameter("id", XMLType.SOAP_STRING, javax.xml.rpc.ParameterMode.IN); //調(diào)用方法的返回值 call.setReturnType(org.apache.axis.Constants.XSD_STRING); //調(diào)用用Operation調(diào)用存儲(chǔ)過(guò)程(以服務(wù)端的方法為準(zhǔn)) String res = (String) call.invoke(new Object[] {"1"}); //調(diào)用存儲(chǔ)過(guò)程 System.out.println(res); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } }
Run directly from the command line or right-click run as. In the server-side project, I directly did log printing, and it will be printed as long as it is called. After execution
Please see the attachment.
Here comes the key point. Next, PHP calls the server. PHP's soapClient only recognizes certificates in DER, PEM or ENG format, so client.p12 must be converted into a pem file that PHP can recognize. At this time, openssl is used. First Enter the cmd command line and type the following code
Java code
openssl pkcs12 -in D:\SSL\client\client.p12 -out D:\SSL\client\client-cer.pem -clcerts
If it prompts that the openssl command is not recognized, it means you have not installed openssl. If the execution is successful, you will be prompted to enter the password of client.p12 first. After entering, you will be asked to enter the export After entering the password of cer.pe, you are done, client-cer.pem is generated successfully! .
Now upload the php code:
Php code
$params = array('id' => '2'); $local_cert = "./client-cer.pem"; set_time_limit(0); try{ //ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache $wsdl='https://192.168.1.146:8443/pro/ws/getInfoService?wsdl'; // echo file_get_contents($wsdl); $soap=new SoapClient($wsdl, array( 'trace'=>true, 'cache_wsdl'=>WSDL_CACHE_NONE, 'soap_version' => SOAP_1_1, 'local_cert' => $local_cert, //client證書(shū)信息 'passphrase'=> 'client', //密碼 // 'allow_self_signed'=> true ) ); $result=$soap->sayHello($params); $result_json= json_encode($result); $result= json_decode($result_json,true); echo '結(jié)果為:' . json_decode($result['return'],true); }catch(Exception $e) { $result['success'] = '0'; $result['msg'] = '請(qǐng)求超時(shí)'; echo $e->getMessage(); } echo '>>>>>>>>>>>';
?直接運(yùn)行,也會(huì)出現(xiàn)附件中的結(jié)果,打完收工,憋了我整整三天時(shí)間,終于搞定了。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac
