如何添加KeyInfo&使用Java在SAML 2.0中的签名下的X509Data

时间:2015-07-14 09:41:39

标签: java saml opensaml

我是SAML的新手,我只是构建了saml但是根据要求我还需要添加KeyInfo和x509证书节点,包括客户端的公共证书,我使用下面的代码生成签名元素,但不知道如何添加 KeyInfo&签名内的X509Data。需要帮助吗?

BasicX509Credential signingCredential = new BasicX509Credential();
    //Namespace nameSpaceSAML = new Namespace("http://www.w3.org/2000/09/xmldsig#","ds");
    KeyStore keyStore = getKeyStore( signingKeyStorePath,signingKeyStorePassword);
    PrivateKey privateKey = getPrivateKey(keyStore,signingKeyalias,signingKeyStorePassword );
    signingCredential.setPrivateKey(privateKey);
    signature = (Signature) Configuration.getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME).buildObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(signingCredential);
    signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); 

2 个答案:

答案 0 :(得分:2)

如果您想要更少的代码,那么有一个帮助类用于执行此操作的签名。

X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory();
x509Factory.setEmitEntityCertificate(true);
x509Factory.setEmitEntityCertificateChain(true);
x509Factory.setEmitX509IssuerSerial(true);
x509Factory.setEmitX509SubjectName(true);

Configuration.getGlobalSecurityConfiguration().getKeyInfoGeneratorManager().registerFactory("x509emitingKeyInfoGenerator", x509Factory);

SecurityHelper.prepareSignatureParams(signature, SPCredentials.getCredential(), null,  "x509emitingKeyInfoGenerator");

设置KeyInfo,签名算法等。使用工厂上的setEmit方法设置应添加到KeyInfo的内容

有关详细信息,请阅读my blog post on it。 我还写了一个book on OpenSAML,在那里我详细解释了签名和加密功能。

答案 1 :(得分:0)

对于那些寻求答案的人,我找到了将KayInfo元素与X509Data一起添加的解决方案,如下所示,并且工作正常......

KeyInfo keyInfo=(KeyInfo)Configuration.getBuilderFactory().getBuilder(KeyInfo.DEFAULT_ELEMENT_NAME).buildObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data=(X509Data)Configuration.getBuilderFactory().getBuilder(X509Data.DEFAULT_ELEMENT_NAME).buildObject(X509Data.DEFAULT_ELEMENT_NAME);
        X509Certificate cert=(X509Certificate)Configuration.getBuilderFactory().getBuilder(X509Certificate.DEFAULT_ELEMENT_NAME).buildObject(X509Certificate.DEFAULT_ELEMENT_NAME);
        signature.setSigningCredential(signingCredential);
        value=org.apache.xml.security.utils.Base64.encode(signingCredential.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);