1

我必须创建一个具有 XML 数据的应用程序并创建用于签名的哈希并将哈希发送到 API 以获取 XML 的原始签名并在 Java 中附加 XML 的签名我怎样才能实现这一点。

同样的事情可以在.Net中通过覆盖这样的SignedXml类来完成

public class CustomSignedXml: SignedXml
{
    public CustomSignedXml(XmlDocument xmlDoc) : base(xmlDoc)
    {
    }
    public void ComputeSignature()
    {
        CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
        MethodInfo methodInfo = typeof(SignedXml).GetMethod("BuildDigestedReferences", BindingFlags.Instance | BindingFlags.NonPublic);
        methodInfo.Invoke(this, null);
        SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

        SignatureDescription signatureDescription = CryptoConfig.CreateFromName(SignedInfo.SignatureMethod) as SignatureDescription;
        if (signatureDescription == null)
            throw new CryptographicException("Cryptography_Xml_SignatureDescriptionNotCreated");

        HashAlgorithm hashAlg = signatureDescription.CreateDigest();
        if (hashAlg == null)
            throw new CryptographicException("Cryptography_Xml_CreateHashAlgorithmFailed");
        MethodInfo methodInfo2 = typeof(SignedXml).GetMethod("GetC14NDigest", BindingFlags.Instance | BindingFlags.NonPublic);
        byte[] hashvalue = (byte[])methodInfo2.Invoke(this, new object[] { hashAlg });
        var signature = GetSignatureFromServer(hashvalue);
        m_signature.SignatureValue = signature;
    }
}

并使用CustomSignedXml类使用以下肉类进行签名

public string GetSignedXml(string xmlDoc, X509Certificate2 PublicCertificate)
{
    try
    {
        XmlDocument xmlDocumentToSign = new XmlDocument();
        xmlDocumentToSign.LoadXml(xmlDoc);

        CustomSignedXml signedXml = new CustomSignedXml(xmlDocumentToSign);

        Reference reference = new Reference();
        reference.Uri = "";
        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
        reference.AddTransform(new XmlDsigExcC14NTransform());
        reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
        signedXml.AddReference(reference);

        signedXml.ComputeSignature();
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(GetKeyInfoData(PublicCertificate));
        signedXml.KeyInfo = keyInfo;
        var xmlDigitalSignature = signedXml.GetXml();
        xmlDocumentToSign.DocumentElement.AppendChild(xmlDocumentToSign.ImportNode(xmlDigitalSignature, true));
        return xmlDocumentToSign.OuterXml;
    }
    catch (Exception)
    {
        throw;
    }
}

我怎样才能在 JAVA 中做同样的事情

4

0 回答 0