在Java中使用WSS4j签名肥皂消息

在Java中使用WSS4j签名肥皂消息

本文介绍了在Java中使用WSS4j签名肥皂消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Java客户端应用程序,该应用程序需要先对SOAP消息进行签名(其中包含2个部分),然后将其发送到远程服务器,然后再获取响应.我设法在SoapUI中成功拨打电话(请参见下面的请求和屏幕截图).

I am writing a Java client application that needs to sign a SOAP message (with 2 parts in it) and send it to a remote server before fetching the response. I managed to make successful calls in SoapUI (see request and screenshot below).

我已经准备好大多数代码,但是我不断从服务器收到一条错误消息,内容是:

I have most of the code ready, but I keep getting an error message from the server saying:

SECU3504: Digital signature verification failure.
Signature failed core validation

Signature validation status: true
ref[#id-32e3db92-b6fd-42a5-b032-a0dc2a15ae82] validity status: false
ref[#id-2b67ce75-e25f-4f66-b265-80a0e31911ec] validity status: false

这是我的Java代码:

Here is my Java code:

// Load KeyStore from .PFX certificate
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(new FileInputStream(certificateFileName), certificatePassword.toCharArray());

// Build XML Document from String
String data = "..."; // Same request as in SoapUI
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(new ByteArrayInputStream(data.getBytes()));

// Load certificate
String alias = store.aliases().nextElement(); // There's only one
PrivateKeyEntry keyEntry = (PrivateKeyEntry)store.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));
X509Certificate cert = (X509Certificate) keyEntry.getCertificate();

// Add <wsse:Security> tag.
WSSecHeader secHeader = new WSSecHeader();
secHeader.setMustUnderstand(false);
secHeader.insertSecurityHeader(doc);

// It is not added to the right place, so move it under the right header
Node n = doc.getFirstChild().getFirstChild().getFirstChild();
Element elemEnvelope = (Element)doc.getElementsByTagName("soapenv:Envelope").item(0);
Element elemNewHeader = (Element)doc.getElementsByTagName("Header").item(0);
Element elemSoapHeader = (Element)doc.getElementsByTagName("soapenv:Header").item(0);
Element elemBody = (Element)doc.getElementsByTagName("soapenv:Body").item(0);
Element elemHeader = (Element)doc.getElementsByTagName("ns1:CAISOWSHeader").item(0);
elemSoapHeader.insertBefore(n, elemHeader);
elemEnvelope.removeChild(elemNewHeader);

// Setup signing algorithm
WSSecSignature builder = new WSSecSignature();
builder.setX509Certificate(cert);
builder.setUserInfo(alias, password);
builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
builder.setSignatureAlgorithm(WSConstants.RSA_SHA1);
builder.setSigCanonicalization(WSConstants.C14N_EXCL_OMIT_COMMENTS);
builder.setDigestAlgo(WSConstants.SHA1);
builder.setUseSingleCertificate(true);

// Set message parts to sign
List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
WSEncryptionPart bodyPart1 = new WSEncryptionPart("Body", WSConstants.URI_SOAP11_ENV, "Content");
WSEncryptionPart bodyPart2 = new WSEncryptionPart("CAISOWSHeader", "http://www.caiso.com/soa/2006-09-30/CAISOWSHeader.xsd", "Content");
bodyPart1.setElement(elemBody);
bodyPart2.setElement(elemHeader);
parts.add(bodyPart1);
parts.add(bodyPart2);
builder.getParts().addAll(parts);

// Set keystore and sign the document
Properties properties = new Properties();
properties.setProperty("org.apache.ws.security.crypto.provider", "org.apache.wss4j.common.crypto.Merlin");

Merlin crypto = (Merlin)CryptoFactory.getInstance(properties);
crypto.setKeyStore(store);

doc = builder.build(doc, crypto, secHeader);
String docStr = this.toString(doc); // This method generates a string of the Document.

// Send SOAP message
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpPost httppost = new HttpPost(this.url);
HttpEntity entity = new ByteArrayEntity(docStr .getBytes("UTF-8"));
httppost.setEntity(entity); // Signed Body
httppost.addHeader("SOAPAction", "http://www.caiso.com/soa/retrieveConvergenceBidAwards_v2");

HttpResponse response = httpclient.execute(httppost);
String respStr = EntityUtils.toString(response.getEntity());

我成功通过以下安全设置在SoapUI中成功拨打电话:

I managed to make successful calls in SoapUI with the following security settings:

我在SoapUI中提出的请求如下(日期/MessageId/Nonce是当场生成的,但是出于可读性考虑,我将在此处对其进行硬编码):

The request I put in SoapUI is the following (Dates/MessageId/Nonce are generated on the spot, but for the sake of readability, I will hardcode them here):

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:stan="http://www.caiso.com/soa/2006-06-13/StandardAttachmentInfor.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header>
      <ns1:CAISOWSHeader xmlns:ns1="http://www.caiso.com/soa/2006-09-30/CAISOWSHeader.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soapenv:actor="" soapenv:mustUnderstand="0">
         <ns1:CAISOUsernameToken>
            <ns1:Username>CN=XXXX, OU=people, O=XXXX, C=US</ns1:Username>
            <Nonce xmlns:ns2="http://schemas.xmlsoap.org/ws/2002/07/secext" EncodingType="http://docs.oasisopen.org/wss/2004/01/oasis-200401wss-soap-message-security-1.0#Base64Binary">MGNkNmU5ODMtZjcyZC00YTAyLWE5NWMtM2Q5Y2RjMTEyNDA1</Nonce>
            <Created xmlns:ns3="http://schemas.xmlsoap.org/ws/2002/07/utility">2018-03-02T21:13:45.932Z</Created>
         </ns1:CAISOUsernameToken>
         <CAISOMessageInfo>
            <MessageID>06c3379d-f10e-45f2-84eb-9262acce277e</MessageID>
            <Timestamp>
               <Created xmlns:ns4="http://schemas.xmlsoap.org/ws/2002/07/utility">2018-03-02T21:13:45.932Z</Created>
               <Expires xmlns:ns5="http://schemas.xmlsoap.org/ws/2002/07/utility">2018-03-02T23:13:45.932Z</Expires>
            </Timestamp>
         </CAISOMessageInfo>
      </ns1:CAISOWSHeader>
      <attachmentHash xmlns:ns7="http://www.caiso.com/mrtu/soa/schemas/2005/09/attachmenthash" actor="http://schemas.xmlsoap.org/soap/actor/next" mustUnderstand="0">
         <hashValue />
      </attachmentHash>
      <standardAttachmentInfor xmlns:ns1="http://www.caiso.com/soa/2006-06-13/StandardAttachmentInfor.xsd">
         <Attachment>
            <id>1</id>
            <compressFlag>yes</compressFlag>
            <compressMethod>gzip</compressMethod>
         </Attachment>
      </standardAttachmentInfor>
   </soapenv:Header>
   <soapenv:Body>
      <retrieveConvergenceBidAwards_v2>
         <RequestConvergenceBidAwards>
            <MessagePayload>
               <RequestConvergenceBidAwardRecord>
                  <dateTimeEnd>2018-02-02T08:00:00Z</dateTimeEnd>
                  <dateTimeStart>2018-02-01T08:00:00Z</dateTimeStart>
                  <SchedulingCoordinatorList>
                     <schedulingCoordinator>XXXX</schedulingCoordinator>
                  </SchedulingCoordinatorList>
               </RequestConvergenceBidAwardRecord>
            </MessagePayload>
         </RequestConvergenceBidAwards>
      </retrieveConvergenceBidAwards_v2>
   </soapenv:Body>
</soapenv:Envelope>

我不知道问题出在哪里.是在签名过程中,从文档到字符串的转换过程中还是在执行HTTP请求的过程中?

I have no idea where the issue is. Is it during the signing process, during the conversion from Document to String or in the way I perform the HTTP request?

非常感谢您的帮助:)

推荐答案

我知道这是一个老问题,但是我为此感到挣扎,最后我找到了一种生成签名的方法,例如Soap UI,这就是我的代码:

I know this is an old question but I was struggling with this and I finally found a way to generate the signature like Soap UI does this is my code:

public String handleMessage(SOAPMessage message) {
        String ret;
        try {
            Document doc = message.getSOAPBody().getOwnerDocument();
            Crypto crypto = CryptoFactory.getInstance(properties); //File

            WSSecSignature sign = new WSSecSignature();
            sign.setUserInfo(properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.alias"), properties.getProperty("privatekeypassword"));
            sign.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE); // Binary Security Token - SecurityTokenReference
            sign.setUseSingleCertificate(true);
            sign.setDigestAlgo(DigestMethod.SHA256);

            WSSecHeader secHeader = new WSSecHeader();
            secHeader.insertSecurityHeader(doc);
            Document signedDoc = sign.build(doc, crypto, secHeader);

            ret = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc);

        } catch (SOAPException e) {
            e.printStackTrace();
            return null;
        } catch (WSSecurityException e) {
            e.printStackTrace();
            throw new RuntimeException("Error: " + e.getMessage());
        }
        return ret;
    }

此代码来自:"> https://sourceforge.net/p/signsoaprequest/code/HEAD/tree/SignSOAPRequest/trunk/src/main/java/br/gov/dataprev/soaptools/sign/

这篇关于在Java中使用WSS4j签名肥皂消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:29