EldoS | Feel safer!

Software components for data protection, secure storage and transfer

[JAVA] XAdES saving, choose encoding

Also by EldoS: CallbackFilter
A component to monitor and control disk activity, track file and directory operations (create, read, write, rename etc.), alter file data, encrypt files, create virtual files.
#30788
Posted: 09/22/2014 09:37:32
by Mickaël Bénès (Standard support level)
Joined: 02/26/2013
Posts: 74

Hello.

I need to save the signature I create into a new file (to leave the original unchanged) in ISO-8851-1. If not specified, UTF-8 is used.

I found this :
Code
TElXMLDOMDocument.SaveToStream(TElStream stream, short canonMethod, String charset).

How the argument charset must be set ? Does a simple "ISO-8851-1" works ?
Also, I already specified the canonicalization mehtod in my code (in the TElXMLReference and the TElXMLSigner). Do I need to specify it again ?
Finally, the file I save the XML in doesn't exist. Do I need to create it or my code will work has it is ?
Code
public static void saveToFile(TElXMLDOMDocument xml, String filePath) throws Exception {
   TElFileStream fs = null;
   
   try {
      fs = new TElFileStream( filePath, "rw", true );
      xml.SaveToStream(fs, SBXMLDefs.xcmExclCanon, "ISO-8851-1");
   }
   finally {
      if ( fs != null ) {
         fs.Free();
      }
   }
}


Thank you !
#30790
Posted: 09/22/2014 10:29:48
by Mickaël Bénès (Standard support level)
Joined: 02/26/2013
Posts: 74

Doesn't seem to work. I got this exception :
Quote
Exception : SecureBlackbox.XML.TElXMLDOMDocument cannot be cast to SecureBlackbox.XML.TElXMLDOMElement
#SecureBlackbox.XML.TElXMLDOMElement.$InternalSaveToStream$891$CheckParentNamespace(SBXMLCore.pas:6020)
#SecureBlackbox.XML.TElXMLDOMElement.InternalSaveToStream(SBXMLCore.pas:6120)
#SecureBlackbox.XML.TElXMLDOMNode.SafeSaveToStream(SBXMLCore.pas:3302)
#SecureBlackbox.XML.TElXMLDOMNode.SaveChildrenToStream(SBXMLCore.pas:3238)
#SecureBlackbox.XML.TElXMLDOMDocument.InternalSaveToStream(SBXMLCore.pas:8408)
#SecureBlackbox.XML.TElXMLDOMNode.SafeSaveToStream(SBXMLCore.pas:3302)
#SecureBlackbox.XML.TElXMLDOMDocument.SaveToStream(SBXMLCore.pas:8564)
#awsoutil.outil.signature.xades.XAdES.saveToFile(XAdES.java:231)
#awsoutil.outil.signature.xades.SignFile_SignThread.run(SignFile_SignThread.java:335)


Here is the full code of my signing function :
Code
TElXMLDOMDocument xml            = new TElXMLDOMDocument();
      xml.LoadFromFile( this._fileToSign.getAbsolutePath() );
      TElMemoryCertStorage certStorage   = new TElMemoryCertStorage();
      TElXMLReferenceList xmlRefsList      = new TElXMLReferenceList();
      TElXMLReference xmlRef            = new TElXMLReference();
      TElStream fileStream            = null;
      TElXAdESSigner xadesSigner         = null;
      TElXMLSigner signer               = null;
      String documentId               = xml.GetDocumentElement().GetAttribute("Id");
      String sigId                  = documentId + "_SIG_1";
      
      try {
         fileStream = new TElFileStream(this._fileToSign.getAbsolutePath(), "r", true);
         
//         TElXMLDOMNodeList bordNodes   = this._getNodeByName( xml, "PES_RecetteAller" );
//         bordNodes               = bordNodes.GetItem(0).GetChildNodes();
//         TElXMLDOMNode nodeToSign   = bordNodes.GetItem(1);
//         String sigNodeID         = "#" + ((TElXMLDOMElement) nodeToSign).GetAttribute("Id");
         
         xmlRef.SetDigestMethod( SBXMLSec.xdmSHA1 );
//         xmlRef.SetURINode( (TElXMLDOMNode) nodeToSign );
//         xmlRef.SetURI( sigNodeID );
         xmlRef.SetURI( "#" + documentId );
         xmlRef.SetURINode( xml.GetDocumentElement() );
         xmlRef.SetURIStream( fileStream );
         xmlRef.SetURIStreamOffset( 0 );
         xmlRef.SetURIStreamCount( fileStream.GetLength() );
         xmlRef.GetTransformChain().Add( new TElXMLEnvelopedSignatureTransform() );
         xmlRef.GetTransformChain().Add( new TElXMLC14NTransform(SBXMLDefs.xcmExclCanon) );

         xmlRefsList.Add(xmlRef);
         
         TElWinCertStorage winCertStorage = new TElWinCertStorage();
         winCertStorage.Clear();
         winCertStorage.GetSystemStores().Add( "MY" );
         
         certStorage.Clear();
         certStorage.Add(this._telX509Cert, true);
         
         System.out.println("Certificats de signature :");
         for (int i = 0; i < certStorage.GetCount(); i++) {
            TElX509Certificate cert   = certStorage.GetCertificate(i);
            
            System.out.println("\t- " + cert.GetSubjectName().CommonName + " ( " + Divers.byte2String( cert.GetSerialNumber() ) + " )");
         }
         
         TElX509CertificateValidator certValidator = new TElX509CertificateValidator();
         
         // The following lines are required for HTTP retrieval of CRLs and OCSP in TElX509CertificateValidator to work
         SBHTTPCRL.RegisterHTTPCRLRetrieverFactory();
            SBLDAPCRL.RegisterLDAPCRLRetrieverFactory();
            SBHTTPOCSPClient.RegisterHTTPOCSPClientFactory();
         SBHTTPCertRetriever.RegisterHTTPCertificateRetrieverFactory();

         certValidator.InitializeWinStorages();
         certValidator.SetCheckOCSP(true);
         certValidator.SetMandatoryOCSPCheck(true);
         certValidator.SetOnBeforeCertificateValidation( new TSBBeforeCertificateValidationEvent(this._onBeforeCertificateValidation) );
         certValidator.SetOnCRLRetrieved( new TSBCRLRetrievedEvent(this._onCRLRetrieved) );
         certValidator.SetOnOCSPResponseSignerValid( new TSBOCSPResponseSignerValidEvent(this._onOCSPResponseSignerValid) );
         
         xadesSigner = new TElXAdESSigner();
         xadesSigner.SetXAdESVersion(SBXMLAdES.XAdES_v1_2_2);
         xadesSigner.SetXAdESForm(SBXMLAdES.XAdES_EPES);
         xadesSigner.SetSigningCertificates(certStorage);
         xadesSigner.SetCertificateValidator(certValidator);
         xadesSigner.SetSigningTime( DateUtil.getDateTimeUTCNow() );
//         xadesSigner.SetSigningTime( SBUtils.DateTimeUtcNow() );
         xadesSigner.SetTSPClient(null);
         xadesSigner.SetIgnoreTimestampFailure(true);
         xadesSigner.SetIgnoreChainValidationErrors(true);
         xadesSigner.SetIncluded(SBXMLAdESIntf.xipProductionPlace | SBXMLAdESIntf.xipSignerRole);
         xadesSigner.GetSignerRole().GetClaimedRoles().AddText(xadesSigner.GetXAdESVersion(), xml.GetOwnerDocument(), "");
         
         xadesSigner.SetOnBeforeCertificateValidate( new TSBXAdESBeforeCertificateValidateEvent(this._onBeforeCertificateValidate) );
         
         String policyURL      = AppletAWS.getConfig( "sig.xades.helios.policy.url" );
         String policyID         = AppletAWS.getConfig( "sig.xades.helios.policy.id" );
         String policyHash      = AppletAWS.getConfig( "sig.xades.helios.policy.hash" );
         
         TElXMLAnyType item = new TElXMLAnyType(xadesSigner.GetXAdESVersion());
         item.SetValue(xml.CreateElement("temp")); // use new node or cloned node, works as container for xml tree
         TElXMLDOMElement innerElement = xml.CreateElement("SPURI");
         item.GetValue().AppendChild(innerElement);
         innerElement.AppendChild(xml.CreateTextNode(policyURL));
         
         xadesSigner.GetPolicyId().GetSigPolicyId().SetIdentifier( policyID );
         xadesSigner.GetPolicyId().GetSigPolicyId().SetDescription( "Politique de signature Helios de la DGFiP" );
         xadesSigner.GetPolicyId().GetSigPolicyHash().SetDigestMethod( SBXMLSec.DigestMethodToURI(SBXMLSec.xdmSHA1) );
         xadesSigner.GetPolicyId().GetSigPolicyHash().SetDigestValue( SBUtils.BytesOfString(SBEncoding.Base64DecodeString(policyHash)) );   // Hash en cache.
//         xadesSigner.GetPolicyId().GetSigPolicyHash().SetDigestValue( SBXMLSec.CalculateDigest(bufPolicyHash, SBXMLSec.xdmSHA1) );         // Hash calculé.
         xadesSigner.GetPolicyId().GetSigPolicyQualifiers().Add(item);
         
            if (policyID.length() > 0) {
                if (policyID.substring(0, 4).toLowerCase().compareTo("urn:") == 0) {
                   xadesSigner.GetPolicyId().GetSigPolicyId().SetIdentifierQualifier(SBXMLAdES.xqtOIDAsURN);
                }
                else {
                   xadesSigner.GetPolicyId().GetSigPolicyId().SetIdentifierQualifier(SBXMLAdES.xqtOIDAsURI);
                }
            }
            else {
               xadesSigner.GetPolicyId().GetSigPolicyId().SetIdentifierQualifier(SBXMLAdES.xqtNone);
            }
         
         /*
          * MODIF Mickaël - 16 juin 2014
          * Suppression des infos de production (le lieu de production de la signature).
          */
         
         xadesSigner.GetProductionPlace().SetCity( "" );
         xadesSigner.GetProductionPlace().SetStateOrProvince( "");
         xadesSigner.GetProductionPlace().SetPostalCode( "" );
         xadesSigner.GetProductionPlace().SetCountryName( "" );
         
         /*
          * FIN MODIF Mickaël - 16 juin 2014
          */
         
         xadesSigner.Generate( SBXMLAdES.XAdES_EPES );
         
         /*
          * Setting Qualifying Properties.
          */
         xadesSigner.GetQualifyingProperties().SetXAdESPrefix("xad");
         xadesSigner.GetQualifyingProperties().SetTarget( sigId );
         xadesSigner.GetQualifyingProperties().GetSignedProperties().SetID( sigId + "_SP" );
         xadesSigner.GetQualifyingProperties().GetUnsignedProperties().GetUnsignedSignatureProperties().GetCertificateValues().GetEncapsulatedX509Certificates().AddCertificate(this._telX509Cert, xadesSigner.GetXAdESVersion());
         xadesSigner.GetQualifyingProperties().GetUnsignedProperties().GetUnsignedSignatureProperties().GetCompleteCertificateRefs().GetCertRefs().AddCertificate(this._telX509Cert, xadesSigner.GetXAdESVersion());

         signer = new TElXMLSigner();
         signer.SetReferences(xmlRefsList);
         signer.SetIncludeKey(true);
         signer.SetCanonicalizationMethod( SBXMLDefs.xcmExclCanon );
//         signer.SetEnvelopingObjectID( sigNodeID );
//         signer.SetSignatureType(SBXMLSec.xstDetached);
         signer.SetSignatureType(SBXMLSec.xstEnveloped);
//         signer.SetSignatureType(SBXMLSec.xstEnveloping);
         signer.SetSignatureMethodType(SBXMLSec.xmtSig);
         signer.SetSignatureMethod(SBXMLSec.xsmRSA_SHA1);
         signer.SetXAdESProcessor(xadesSigner);

         if ((signer.GetSignatureType() == SBXMLSec.xstEnveloping) && (xmlRef != null) && (xmlRef.GetURI().equals("")) && (xmlRef.GetURINode() instanceof TElXMLDOMElement)) {
            TElXMLDOMElement el = (TElXMLDOMElement) xmlRef.GetURINode();
            el.SetAttribute("Id", "id-" + SBStrUtils.IntToStr(SBRandom.SBRndGenerate(Integer.MAX_VALUE)));
            xmlRef.SetURI("#" + el.GetAttribute("Id"));
         }
         
         if (this._telX509Cert.GetPrivateKeyExists()) {
            TElXMLKeyInfoX509Data X509KeyData = new TElXMLKeyInfoX509Data(false);
            X509KeyData.SetCertificate(this._telX509Cert);
            signer.SetKeyData(X509KeyData);
         }

         signer.UpdateReferencesDigest();
         signer.GenerateSignature();
         
         TElXMLSignature sig   = signer.GetSignature();
         sig.SetID(sigId);
         sig.GetSignatureValue().SetID(sigId + "_SV");
         sig.GetKeyInfo().SetID(sigId + "_KI");
         
         TElXMLReference signedInfoRef = sig.GetSignedInfo().GetSigPropRef();
         signedInfoRef.SetURI( "#" + sigId + "_SP" );
         signedInfoRef.GetTransformChain().Add(new TElXMLEnvelopedSignatureTransform());
         signedInfoRef.GetTransformChain().Add( new TElXMLC14NTransform(SBXMLDefs.xcmExclCanon) );
         
         String sigFilePath = "";
         if (signer.GetSignatureType() == SBXMLSec.xstDetached) {
            xml.Destroy();
            
            try {
               TElXMLDOMNode nodeToSign      = null;
               TSBObject obj   = new TSBObject();
               signer.Save(obj);
               nodeToSign = (TElXMLDOMNode) obj.Value;
               
               xml         = nodeToSign.GetOwnerDocument();
               sigFilePath   = this._fileToSign.getParent() + System.getProperty("file.separator") + this._fileToSign.getName().substring(0, this._fileToSign.getName().length() - 4) + "_signed-detached.xml";
               
//               xml.SaveToFile(sigFilePath);
               XAdES.saveToFile(xml, sigFilePath);
            }
            catch (Exception e) {
               throw e;
            }
         }
         else {
            TElXMLDOMNode nodeToSign = (TElXMLDOMNode) xml.GetDocumentElement();
            if (nodeToSign instanceof TElXMLDOMDocument) {
               nodeToSign = ((TElXMLDOMDocument) nodeToSign).GetDocumentElement();
            }

            try {
               // If the signature type is enveloping, then the signature is placed into the passed node and the contents of the node are moved to inside of the signature.
               // If the signature type is enveloped, the signature is placed as a child of the passed node.
               TSBObject obj   = new TSBObject();
               obj.Value      = nodeToSign;
               signer.Save(obj);
               
               TSBXAdESValidity validityDataRefs   = xadesSigner.AddValidationDataRefs(this._telX509Cert, true, true, SBXMLSec.xdmSHA1, true, null);
               TSBXAdESValidity validityDataValues   = xadesSigner.AddValidationDataValues(this._telX509Cert, true, true, null);
               
               System.out.println("\n" + validityDataRefs.toString());
               System.out.println(validityDataValues.toString() + "\n");
               
               sigFilePath = this._fileToSign.getParent() + System.getProperty("file.separator") + this._fileToSign.getName().substring(0, this._fileToSign.getName().length() - 4);
               if (signer.GetSignatureType() == SBXMLSec.xstEnveloped) {
                  sigFilePath += "_signed-enveloped.xml";
               }
               else {
                  sigFilePath += "_signed-enveloping.xml";
               }
               
//               xml.SaveToFile(sigFilePath);
               XAdES.saveToFile(xml, sigFilePath);
            }
            catch (Exception e) {
               throw e;
            }
         }
#30791
Posted: 09/22/2014 13:17:49
by Dmytro Bogatskyy (EldoS Corp.)

Moved to helpdesk ( https://www.eldos.com/helpdesk/ ). You will see your (and only your) support tickets by following this URL. You will also get e-mail notifications about updates related to your support ticket.

Reply

Statistics

Topic viewed 852 times

Number of guests: 1, registered members: 0, in total hidden: 0




|

Back to top

As of July 15, 2016 EldoS Corporation will operate as a division of /n software inc. For more information, please read the announcement.

Got it!