How to produce XML signature with no whitespaces and line-breaks in Java?

前端 未结 8 1567
情话喂你
情话喂你 2020-12-17 00:51

I work with the brazilian \"Nota Fiscal Eletronica\" project, in which they define a standart way to sign XML documents.

Recently, they started to require that there

相关标签:
8条回答
  • 2020-12-17 01:43

    XML Signature signs part of an XML Document starting with a given element (i.e. a sub tree in DOM) after it is normalized with a C14N algorithm. The standard C14N algorithm you use preserves line breaks and white spaces (see http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent).

    So all line breaks in the signed part of the original document (including between last tag of data and the <Signature> tag, and between </Signature> and the next closing tag) *must be preserved so as not to alter the signature. The line breaks and spaces in the Signature element itself are not important and may be removed without altering the signature.

    Here an example:

    <root id="signedpart">
      <data>
         ...
      </data>
      <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
         <SignedInfo>
           <Reference URI="#signedpart">
              ...
           </Reference>
         </SignedInfo>
      </Signature>
    </root> 
    

    Here are your possible options:

    1. define your own C14N algorithm that will remove spaces and line breaks by it self. I would discourage this as the other side must also use this non standard C14N algorithm.

    2. remove line breaks an spaces from you XML before signing it (and potentially remove spaces in signature afterwards)

    with the example this will give you the following signed XML:

    <root id="signedpart"><data>...</data><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
        <SignedInfo>
           <Reference URI="#signedpart">
              ...
           </Reference>
         </SignedInfo>
      </Signature></root>
    

    and after removing spaces in signature

    <root id="signedpart"><data>...</data><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><Reference URI="#signedpart">...</Reference></SignedInfo></Signature></root>
    
    0 讨论(0)
  • 2020-12-17 01:45

    We just need to set the "true" value to the "ignoreLineBreaks" parameter, cause' the default value is false and this allows to the signature API to add LineBreaks

    here is the code to avoid or remove LineBreaks

    Field f = XMLUtils.class.getDeclaredField("ignoreLineBreaks");
    f.setAccessible(true);
    f.set(null, Boolean.TRUE);
    

    then, we'll can make sure that the new value is true with the next code line

    System.err.println(XMLUtils.ignoreLineBreaks());
    

    I had the same problem and this worked for me.

    0 讨论(0)
提交回复
热议问题