元数据中的签名引用URI变为null

时间:2016-08-29 13:15:49

标签: java xml metadata saml opensaml

我正在使用XML并在其中签名特定标记。 在检查签名标记下的引用uri后生成签名的XML后,我发现它为null,如:Reference URI="". 据我所知,签名引用URI将是签名的标记的id。是吗?

我用Java实现它,如果有人知道这个,请帮助我。

<SignedInfo>
  <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
  <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
  <Reference URI=""> //------> here is my problem.
    <Transforms>
      <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
      <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
        <InclusiveNamespaces xmlns="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="#default md saml ds xs xsi"/>
      </Transform>
    </Transforms>
    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
    <DigestValue>CN74nRredNo8Qlwu4TbW4YLbMEQ=</DigestValue>
  </Reference>
</SignedInfo>

我已实施的代码:

File fIDPMetaDataFile = new File(metadata_destination_path);

        System.out.println("Startin to generate Metadata Information..");
        String fn = keyfile_path;
        String pass = password;
        Certificate cc = null;
        X509Certificate certificate1 = null;
        Key key = null;

        KeyStore ks = KeyStore.getInstance("pkcs12", "SunJSSE");
        ks.load(new FileInputStream(fn), pass.toCharArray());

        String alias = ks.aliases().nextElement();
        System.out.println("Alias name........................................" + alias);
        key = ks.getKey(alias, pass.toCharArray());
        cc = ks.getCertificate(alias);

        certificate1 = (X509Certificate) cc;
        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

        EntityDescriptor idpEntityDescriptor = ((SAMLObjectBuilder<EntityDescriptor>) builderFactory.getBuilder(EntityDescriptor.DEFAULT_ELEMENT_NAME)).buildObject();

        idpEntityDescriptor.setEntityID(entity_id);


        AttributeAuthorityDescriptorBuilder aadBuilder = new AttributeAuthorityDescriptorBuilder();
        AttributeAuthorityDescriptor aad = aadBuilder.buildObject(); 
        idpEntityDescriptor.getRoleDescriptors().add(aad);


        //====================Adding IDPSSODescriptor Information==================================
        IDPSSODescriptor idpSSODescriptor = ((SAMLObjectBuilder<IDPSSODescriptor>) builderFactory.getBuilder(IDPSSODescriptor.DEFAULT_ELEMENT_NAME)).buildObject();
        idpSSODescriptor.setWantAuthnRequestsSigned(true);
        idpSSODescriptor.setID(new IDService().generateID());
        //idpSSODescriptor.getSupportedProtocols().clear();
        idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        //====================Adding KeyInfo Information==================================
        KeyDescriptor encKeyDescriptor = ((SAMLObjectBuilder<KeyDescriptor>) builderFactory.getBuilder(KeyDescriptor.DEFAULT_ELEMENT_NAME)).buildObject();
        KeyInfoBuilder keyInfoBuilder = (KeyInfoBuilder) builderFactory.getBuilder(KeyInfo.DEFAULT_ELEMENT_NAME);
        KeyInfo keyinfo = (KeyInfo) keyInfoBuilder.buildObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        KeyInfoHelper.addCertificate(keyinfo, certificate1);

        try {
            //encKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingCredential));
            encKeyDescriptor.setKeyInfo(keyinfo);
        } catch (Exception e) {
            System.out.println("Error #############" + e.getMessage());
        }
        idpSSODescriptor.getKeyDescriptors().add(encKeyDescriptor);


        //====================Adding Artifact Resolution Service Information==========================
        ArtifactResolutionService artifactResService = ((SAMLObjectBuilder<ArtifactResolutionService>) builderFactory.getBuilder(ArtifactResolutionService.DEFAULT_ELEMENT_NAME)).buildObject();
        artifactResService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
        artifactResService.setLocation(artifact_resolution_service_location);
        artifactResService.setIndex(1);
        artifactResService.setIsDefault(true);
        idpSSODescriptor.getArtifactResolutionServices().add(artifactResService);

        //====================Adding NameIDFormat Information==========================
        NameIDFormat nameIDFormat = ((SAMLObjectBuilder<NameIDFormat>) builderFactory.getBuilder(NameIDFormat.DEFAULT_ELEMENT_NAME)).buildObject();
        nameIDFormat.setFormat(NameIDType.TRANSIENT);
        idpSSODescriptor.getNameIDFormats().add(nameIDFormat);

        //====================Adding SSO Service Information==========================
        SingleSignOnService ssoService = ((SAMLObjectBuilder<SingleSignOnService>) builderFactory.getBuilder(SingleSignOnService.DEFAULT_ELEMENT_NAME)).buildObject();
        ssoService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
        //assertionConsumerService.setLocation(assertionConsumerServiceURL);
        ssoService.setLocation(sso_location);
        idpSSODescriptor.getSingleSignOnServices().add(ssoService);

        //====================Adding SLO Service Information==========================
        SingleLogoutService sloService = ((SAMLObjectBuilder<SingleLogoutService>) builderFactory.getBuilder(SingleLogoutService.DEFAULT_ELEMENT_NAME)).buildObject();
        sloService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
        //assertionConsumerService.setLocation(assertionConsumerServiceURL);
        sloService.setLocation(slo_location);
        idpSSODescriptor.getSingleLogoutServices().add(sloService);

        //====================Adding Attribute Information==========================
        Attribute attribute = ((SAMLObjectBuilder<Attribute>) builderFactory.getBuilder(Attribute.DEFAULT_ELEMENT_NAME)).buildObject();
        attribute.setName(attribute_username);
        //attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:assertion");
        idpSSODescriptor.getAttributes().add(attribute);

        idpEntityDescriptor.getRoleDescriptors().add(idpSSODescriptor);
        //idpEntityDescriptor.getAttributeAuthorityDescriptor(new IDService().generateID());

        //====================Adding Organization Information==========================
        Organization organization = ((SAMLObjectBuilder<Organization>) builderFactory.getBuilder(Organization.DEFAULT_ELEMENT_NAME)).buildObject();
        OrganizationName name = ((SAMLObjectBuilder<OrganizationName>) builderFactory.getBuilder(OrganizationName.DEFAULT_ELEMENT_NAME)).buildObject();
        OrganizationDisplayName displayName = ((SAMLObjectBuilder<OrganizationDisplayName>) builderFactory.getBuilder(OrganizationDisplayName.DEFAULT_ELEMENT_NAME)).buildObject();
        OrganizationURL orgURL = ((SAMLObjectBuilder<OrganizationURL>) builderFactory.getBuilder(OrganizationURL.DEFAULT_ELEMENT_NAME)).buildObject();

        LocalizedString orgName = new LocalizedString(organization_name, "");
        name.setName(orgName);
        organization.getOrganizationNames().add(name);

        LocalizedString orgDisplayName = new LocalizedString(organization_display_name, "");
        displayName.setName(orgDisplayName);
        organization.getDisplayNames().add(displayName);

        LocalizedString LocalOrgURL = new LocalizedString(organization_url, "");
        orgURL.setURL(LocalOrgURL);
        organization.getURLs().add(orgURL);

        idpEntityDescriptor.setOrganization(organization);

        //====================Adding ContactPerson Information==========================
        ContactPerson contactPerson = ((SAMLObjectBuilder<ContactPerson>) builderFactory.getBuilder(ContactPerson.DEFAULT_ELEMENT_NAME)).buildObject();

        GivenName givenName = ((SAMLObjectBuilder<GivenName>) builderFactory.getBuilder(GivenName.DEFAULT_ELEMENT_NAME)).buildObject();
        givenName.setName(given_name);
        contactPerson.setGivenName(givenName);

        SurName surName = ((SAMLObjectBuilder<SurName>) builderFactory.getBuilder(SurName.DEFAULT_ELEMENT_NAME)).buildObject();
        surName.setName(surname);
        contactPerson.setSurName(surName);

        EmailAddress emailAddress = ((SAMLObjectBuilder<EmailAddress>) builderFactory.getBuilder(EmailAddress.DEFAULT_ELEMENT_NAME)).buildObject();
        emailAddress.setAddress(email_address);
        contactPerson.getEmailAddresses().add(emailAddress);

        idpEntityDescriptor.getContactPersons().add(contactPerson);

        //====================Write Metadata.xml to file===============================
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Marshaller out = Configuration.getMarshallerFactory().getMarshaller(idpEntityDescriptor);
        out.marshall(idpEntityDescriptor, document);

        /*
        //====================Trasnsform the xml data===============================
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, streamResult);
        stringWriter.close();
         */

        //final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
    Init.init();
    ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, "");
    //final KeyStore keyStore = loadKeyStore(privateKeyFile);
    final XMLSignature sig = new XMLSignature(document, null, XMLSignature.ALGO_ID_SIGNATURE_RSA);
    final Transforms transforms = new Transforms(document);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    final Key privateKey = key;//keyStore.getKey(PRIVATE_KEY_ALIAS, PRIVATE_KEY_PASS.toCharArray());
    final X509Certificate cert = certificate1;


    sig.addKeyInfo(cert);

    //sig.addKeyInfo(cert.getPublicKey());
    sig.sign(privateKey);
    document.getDocumentElement().appendChild(sig.getElement());

    /*
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    outputStream.write(Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(document));
    return outputStream;
    */


        FileOutputStream outFile = new FileOutputStream(fIDPMetaDataFile);
        XMLUtils.outputDOMc14nWithComments(document, outFile);
        outFile.close();
        System.out.println("Metadata generated successfully...");

1 个答案:

答案 0 :(得分:0)

我发现了错误..在这里我将saml对象数据写入xml,然后我正在签署该xml。我更新了它..在签署saml对象后,我将其写入xml文件中..然后将设置URI。