首页 > 解决方案 > 签名与 java pfx 证书不匹配

问题描述

嗨,我正在尝试用 java 为 ssl 后面的 web 服务编写一个肥皂客户端,webservice 的公司给了我一个 pfx 证书;我已经设法在soapui中测试了网络服务;但我无法编写 java 客户端,我遇到了很多 ssl 错误,我遇到的最后一个错误是签名不匹配,请告诉我正确的方法来配置这个 ssl 的东西以使其正常工作

public class SoapSSLTest {
/***
 * path to the client keystore 
 * */
private static final String CLIENT_KEYSTORE_PATH="27384425attada_132707366942472887.pfx";

/***
 * Password for the the client keystore 
 */
private static final String CLIENT_KEYSTORE_PASSWORD="attada@123";

/***
 * The servers certificate's alias within the client key store 
 */
private static final String SERVER_CERTIFICATE_ALIAS="u6337-attadamoune";

/**
 * URL to THE QUANTIC SOAP UI service 
 */
private static final String SOAP_URI="https://www.test.quantikcb.com/testui/Services/LiveRequestService.svc";
private static final String URN ="urn:examples:helloservice";


private static final String REQUEST="<REQUEST REQUEST_ID=\"1\">\r\n"
        + "             <REQUEST_PARAMETERS>\r\n"
        + "                 <REPORT_PARAMETERS REPORT_ID=\"2657\" SUBJECT_TYPE=\"COMM\" RESPONSE_TYPE=\"1\"/>\r\n"
        + "                 <APPLICATION_DETAILS LOAN_TYPE=\"0113\"/>\r\n"
        + "             </REQUEST_PARAMETERS>\r\n"
        + "             <SEARCH_PARAMETERS SEARCH_TYPE=\"NMIDSRCH\">\r\n"
        + "                 <NAME>CALPAL GROUP</NAME>\r\n"
        + "                 <ID_TYPE>C</ID_TYPE>\r\n"
        + "                 <TRIBUNAL_CODE>85</TRIBUNAL_CODE>\r\n"
        + "                 <IDENTIFIER_NUMBER>81867</IDENTIFIER_NUMBER>\r\n"
        + "             </SEARCH_PARAMETERS>\r\n"
        + "              </REQUEST>";


/**
 * Loads the keystore using the default keystorle type (apks) with the given
 * file path and password 
 * @param filePath : the path to the keystore 
 * @param password : the keystore password 
 * @return : returns the keystore 
 * @throws IOException 
 * @throws KeyStoreException 
 * @throws CertificateException 
 * @throws NoSuchAlgorithmException 
 * @throws :NoSuchAlgorithmException
 * @see keystore#load(inputstream, char[])
 * @throws : IOException
 * @see FileInputSteam()
 * @throws keyStoreException
 * @see keystore#getInstance()
 */

private KeyStore loadKeystore(String filePath,char [] password) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    FileInputStream is = new FileInputStream(new File(filePath));

    final KeyStore keystore = KeyStore.getInstance(KeyStore
            .getDefaultType());

    keystore.load(is, password);

    return keystore;
}


public void run() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException, SOAPException {
    /*
     * Load the keystore
     */
    char[] password = CLIENT_KEYSTORE_PASSWORD.toCharArray();
    KeyStore keystore = loadKeystore(CLIENT_KEYSTORE_PATH, password);

    /*
     * Get the servers trusted certificate.
     */
    
    
    final Certificate trusted = keystore
            .getCertificate(SERVER_CERTIFICATE_ALIAS);

    /*
     * Create a trust manager that validates the servers certificate
     */
    TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs,
                String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs,
                String authType) throws CertificateException {

            if (certs == null || certs.length == 0) {
                throw new IllegalArgumentException(
                        "null or zero-length certificate chain");
            }

            if (authType == null || authType.length() == 0) {
                throw new IllegalArgumentException(
                        "null or zero-length authentication type");
            }

            // check if certificate sent is your CA's

            if (!certs[0].equals(trusted)) {

                // check if its been signed by the CA

                try {
                    certs[0].verify(trusted.getPublicKey());
                } catch (InvalidKeyException | NoSuchAlgorithmException
                        | NoSuchProviderException | SignatureException e) {
                    throw new CertificateException(e);
                }
            }

            certs[0].checkValidity();
        }
    } };

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
            .getDefaultAlgorithm());

    kmf.init(keystore, password);

    // set the trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(kmf.getKeyManagers(), trustManager,
            new java.security.SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // create an all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    
    MessageFactory messageFactory =MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.removeNamespaceDeclaration("SOAP-ENV");
    envelope.addNamespaceDeclaration("soap", "http://www.w3.org/2003/05/soap-envelope");
    envelope.addNamespaceDeclaration("sbw","http://dnbsilverbladeproduct.com/SBWebsite");
    envelope.addNamespaceDeclaration("dnb", "http://schemas.datacontract.org/2004/07/Dnb.SB.Web.WebClient.Services");
    envelope.setPrefix("soap");
    /**
    *   <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:sbw="http://dnbsilverbladeproduct.com/SBWebsite" xmlns:dnb="http://schemas.datacontract.org/2004/07/Dnb.SB.Web.WebClient.Services">
    *      <soap:Header/>
    *      <soap:Body>
    *         <sbw:GetLiveCIR>
    *            <!--Optional:-->
    *            <sbw:ReqLiveReport>
    *               <dnb:UserName><![CDATA[userFinal1]]> </dnb:UserName>
    *               <dnb:Password><![CDATA[soapclient@123]]> </dnb:Password>
    *               <dnb:RequestXML><![CDATA[<REQUEST REQUEST_ID="1">
    *                       <REQUEST_PARAMETERS>
    *                       <REPORT_PARAMETERS REPORT_ID="2657" SUBJECT_TYPE="COMM" RESPONSE_TYPE="1"/>
    *                            <APPLICATION_DETAILS LOAN_TYPE="0113"/>
    *                       </REQUEST_PARAMETERS>
    *                       <SEARCH_PARAMETERS SEARCH_TYPE="NMIDSRCH">
    *                           <NAME>CALPAL GROUP</NAME>
    *                           <ID_TYPE>C</ID_TYPE>
    *                           <TRIBUNAL_CODE>85</TRIBUNAL_CODE>
    *                           <IDENTIFIER_NUMBER>81867</IDENTIFIER_NUMBER>
    *                       </SEARCH_PARAMETERS>
    *                       </REQUEST>]]> 
    *               </dnb:RequestXML>
    *            </sbw:ReqLiveReport>
    *         </sbw:GetLiveCIR>
    *      </soap:Body>
    *   </soap:Envelope>
    **/
    
    SOAPHeader soapHeader = envelope.getHeader();
    soapHeader.setPrefix("soap");
    
    SOAPBody soapBody = envelope.getBody();
    soapBody.setPrefix("soap");
    
    SOAPElement getLiveCIRElement=soapBody.addChildElement("GetLiveCIR","sbw");
    SOAPElement getLiveReportElement = getLiveCIRElement.addChildElement("ReqLiveReport","sbw");
    SOAPElement userNameElement=getLiveReportElement.addChildElement("UserName","dnb");
    SOAPElement passwordElement=getLiveReportElement.addChildElement("Password","dnb");
    SOAPElement requestXMLElement=getLiveReportElement.addChildElement("RequestXML","dnb");
    
    
    CDATASection usernameCDATA = userNameElement.getOwnerDocument().createCDATASection("27384425attada");
    userNameElement.appendChild(usernameCDATA);
    
    CDATASection passwordCDATA = passwordElement.getOwnerDocument().createCDATASection("attada@123");
    userNameElement.appendChild(passwordCDATA);
     
    CDATASection requestXMLCDATA = requestXMLElement.getOwnerDocument().createCDATASection(REQUEST);
    requestXMLElement.appendChild(requestXMLCDATA);
    
    //soapBodyElem2.addTextNode("EXample First Name");
    
    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", SOAP_URI+"verifyEmail");
    soapMessage.saveChanges();
    
    
    //send request to the server 
    URL url = new URL(SOAP_URI);
    URLConnection con = url.openConnection();
    con.setDoOutput(true);
    soapMessage.writeTo(con.getOutputStream());
    
    //read in response and print it to screen 
    Reader reader = new InputStreamReader(con.getInputStream());
    
    while (true) {
        int ch = reader.read();
        if(ch==-1) {
            break;
        }
        System.out.println((char) ch);
    }
    
}

public static void main(String [] args)
        throws UnrecoverableKeyException, KeyManagementException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, SOAPException {
    SoapSSLTest test = new SoapSSLTest();
    test.run();
}

堆栈跟踪:

Exception in thread "main" javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: java.security.SignatureException: Signature does not match.
    at sun.security.ssl.Alert.createSSLException(Unknown Source)
    at sun.security.ssl.TransportContext.fatal(Unknown Source)
    at sun.security.ssl.TransportContext.fatal(Unknown Source)
    at sun.security.ssl.TransportContext.fatal(Unknown Source)
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(Unknown Source)
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.onCertificate(Unknown Source)
    at sun.security.ssl.CertificateMessage$T12CertificateConsumer.consume(Unknown Source)
    at sun.security.ssl.SSLHandshake.consume(Unknown Source)
    at sun.security.ssl.HandshakeContext.dispatch(Unknown Source)
    at sun.security.ssl.HandshakeContext.dispatch(Unknown Source)
    at sun.security.ssl.TransportContext.dispatch(Unknown Source)
    at sun.security.ssl.SSLTransport.decode(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.decode(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readHandshakeRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
    at applications.SoapSSLTest.run(SoapSSLTest.java:261)
    at applications.SoapSSLTest.main(SoapSSLTest.java:280)
Caused by: java.security.cert.CertificateException: java.security.SignatureException: Signature does not match.
    at applications.SoapSSLTest$1.checkServerTrusted(SoapSSLTest.java:160)
    at sun.security.ssl.AbstractTrustManagerWrapper.checkServerTrusted(Unknown Source)
    ... 19 more
Caused by: java.security.SignatureException: Signature does not match.
    at sun.security.x509.X509CertImpl.verify(Unknown Source)
    at sun.security.x509.X509CertImpl.verify(Unknown Source)
    at applications.SoapSSLTest$1.checkServerTrusted(SoapSSLTest.java:157)
    ... 20 more

标签: javasslsoap-clientwebservice-clientpfx

解决方案


推荐阅读