如何使用javax.xml.crypto.dsig对XML文件进行签名时添加命名空间。*?

我正在尝试使用封装签名和javax.xml.crypto.dsig。*类来签署xml文件。 因此,我获得了具有正确签名内容但没有定义名称空间的文件。 如何添加xmlns:ds =“http://www.w3.org/2000/09/xmldsig#”命名空间和相应的ds前缀? 我没有看到任何可以定义它的地方。

示例代码:

XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); (...) XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo); // Marshal, generate, and sign the enveloped signature. signature.sign(domSignContext); 

给出了示例XML:

             base64_digest   some_base64   subject_data some_more_base64    another_base64 base64_as_well      

但我想要:

             base64_digest   some_base64   subject_data some_more_base64    another_base64 base64_as_well      

以下是Oracle用于生成封装签名的示例代码。 我想你要找的是dsc.setDefaultNamespacePrefix(“dsig”) ; 如下例所示。

  XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = fac.newReference ("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList (fac.newTransform (Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo SignedInfo si = fac.newSignedInfo (fac.newCanonicalizationMethod (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); // Create a DSA KeyPair KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(512); KeyPair kp = kpg.generateKeyPair(); // Create a KeyValue containing the DSA PublicKey that was generated KeyInfoFactory kif = fac.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(kp.getPublic()); // Create a KeyInfo and add the KeyValue to it KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); // Instantiate the document to be signed DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(sourceFile)); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); dsc.setDefaultNamespacePrefix("dsig"); // Create the XMLSignature (but don't sign it yet) XMLSignature signature = fac.newXMLSignature(si, ki); // Marshal, generate (and sign) the enveloped signature signature.sign(dsc); // output the resulting document OutputStream os; os = new FileOutputStream(DestinationFile); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(doc), new StreamResult(os)); 

String algoritmo = XMLSignature.ALGO_ID_SIGNATURE_RSA; XMLSignature sig = new XMLSignature(doc, algoritmo);

如果您希望以下面的格式签署XML

  ...  

然后请使用java 6版本31,您将获得所需的签名XML。