Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java XML签名方法的C#等价物_Java_C#_Xml_Xmldocument_Xml Signature - Fatal编程技术网

Java XML签名方法的C#等价物

Java XML签名方法的C#等价物,java,c#,xml,xmldocument,xml-signature,Java,C#,Xml,Xmldocument,Xml Signature,尝试通过相反的问题()创建签名,但没有成功。有人能帮我用C#来签署XmlDocument吗?通过相反问题的解决方案,我得到了一个例外,即在确切的位置没有私钥:signedXml.ComputeSignature() 那么,我应该如何在C#中实现签名方法呢?通过我得到的示例: imports... @SuppressWarnings("restriction") public abstract class BaseAuthRequestGenerator { public static

尝试通过相反的问题()创建签名,但没有成功。有人能帮我用C#来签署XmlDocument吗?通过相反问题的解决方案,我得到了一个例外,即在确切的位置没有私钥:
signedXml.ComputeSignature()

那么,我应该如何在C#中实现签名方法呢?通过我得到的示例:

imports...

@SuppressWarnings("restriction")
public abstract class BaseAuthRequestGenerator {
    public static final String SIGNED_NODE_ID = "uniqueNodeId";
    private static final char[] PASSWORD = "testtest".toCharArray();
    private static final XMLSignatureFactory XML_SIGNATURE_FACTORY = XMLSignatureFactory.getInstance("DOM");

    protected PrivateKey privateKey = null;
    protected PublicKey publicKey = null;

    public BaseAuthRequestGenerator() {
        try {
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(FileUtils.openInputStream(FileUtils.toFile(AuthGenerator.class.getResource("/testKeystore.jks"))), PASSWORD);

            for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
                String alias = e.nextElement();
                if (keyStore.isKeyEntry(alias)) {
                    privateKey = (PrivateKey) keyStore.getKey(alias, PASSWORD);
                    X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                    publicKey = cert.getPublicKey();
                    break;
                }
            }
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    public Node marshal(Object data) throws JAXBException {
        String packageName = data.getClass().getPackage().getName();
        JAXBContext jc = JAXBContext.newInstance(packageName);

        DOMResult result = new DOMResult();
        Marshaller marshaller = jc.createMarshaller();
        marshaller.marshal(data, result);
        return result.getNode();
    }

    public String getSignedXml(Node node, String referenceUri) throws Exception {
        signNode(node, referenceUri);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        trans.transform(new DOMSource(node), new StreamResult(output));

        return new String(output.toByteArray(), Charset.forName("UTF-8"));
    }

    public void signNode(Node node, String uri) throws Exception {
        DOMSignContext dsc = new DOMSignContext(privateKey, node);
        XMLSignatureFactory fac = XML_SIGNATURE_FACTORY;

        List<String> prefixList = new ArrayList<String>();
        prefixList.add(node.getPrefix());
        C14NMethodParameterSpec spec = new ExcC14NParameterSpec(prefixList);
        List<Transform> transforms = new ArrayList<Transform>();
        transforms.add(fac.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null));
        transforms.add(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, spec));

        Reference ref = fac.newReference(uri, fac.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null);
        SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, spec), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                Collections.singletonList(ref));

        KeyInfoFactory kif = fac.getKeyInfoFactory();

        KeyValue kv = kif.newKeyValue(publicKey);
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature signature = fac.newXMLSignature(si, ki);
        signature.sign(dsc);
    }

    /**
     * Sets ID attribute (named "id") for given node.
     * <p>
     * Necessary for XML signing/validation when running on JDK 7
     *
     * @param node node to set ID attribute for
     * @see http://stackoverflow.com/questions/17331187/xml-dig-sig-error-after-upgrade-to-java7u25
     */
    public void setIdAttribute(Node node) {
        Node idAttribute = node.getAttributes().getNamedItem("id");
        if (idAttribute != null) {
            ((Element) node).setIdAttribute("id", true);
        }
    }

}


请学习如何使用堆栈溢出,并阅读如何提高问题的质量。然后,你的问题包括你的源代码作为一个,它可以被其他人编译和测试。如果您不将C#代码添加到问题中,我们将无法帮助您处理该代码。在链接中,密钥存储是由以下字符串生成的:new KeyStore.PasswordProtection(password.toCharArray())。因此,您可以在生成证书时使用任何字符串,然后用户可以使用相同的字符串来验证证书。
 private static XDocument SignXDocument(XDocument document)
        {
            XDocument returnDoc = new XDocument();
            XmlDocument convertedDoc = DocumentExtensions.ToXmlDocument(document);
            convertedDoc.PreserveWhitespace = true;

            X509Certificate2 certificate = GetX509Certificate2();
            RSACryptoServiceProvider privateKey = GetPrivateKey(KeyPath);

            SignedXml signedXml = new SignedXml(convertedDoc) { SigningKey = certificate.PrivateKey };
            Reference reference = new Reference { Uri = "#" + ID };

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);
            signedXml.AddReference(reference);

            // embed public key information for signature validation purposes
            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(certificate, X509IncludeOption.ExcludeRoot);
            keyInfo.AddClause(keyInfoX509Data);
            signedXml.KeyInfo = keyInfo;

            signedXml.ComputeSignature();
            XmlElement xmldsigXmlElement = signedXml.GetXml();

            var changed = xmldsigXmlElement.ToXElement();
            document.Add(changed);

            return document;
        }