use of org.apache.xml.security.transforms.Transforms in project OpenAM by OpenRock.
the class AMSignatureProvider method signWithWSSSAMLTokenProfile.
/**
* Sign part of the xml document referered by the supplied a list
* of id attributes of nodes
* @param doc XML dom object
* @param cert Signer's certificate
* @param assertionID assertion ID
* @param algorithm XML signature algorithm
* @param ids list of id attribute values of nodes to be signed
* @param wsfVersion the web services version.
* @return SAML Security Token signature
* @throws XMLSignatureException if the document could not be signed
*/
public Element signWithWSSSAMLTokenProfile(Document doc, java.security.cert.Certificate cert, String assertionID, String algorithm, List ids, String wsfVersion) throws XMLSignatureException {
if (doc == null) {
SAMLUtilsCommon.debug.error("signXML: doc is null.");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
}
if (cert == null) {
SAMLUtilsCommon.debug.error("signWithWSSSAMLTokenProfile: " + "Certificate is null");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
}
if (assertionID == null) {
SAMLUtilsCommon.debug.error("signWithWSSSAMLTokenProfile: " + "AssertionID is null");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullInput"));
}
this.wsfVersion = wsfVersion;
String wsseNS = SAMLConstants.NS_WSSE;
String wsuNS = SAMLConstants.NS_WSU;
if ((wsfVersion != null) && (wsfVersion.equals(SOAPBindingConstants.WSF_11_VERSION))) {
wsseNS = WSSEConstants.NS_WSSE_WSF11;
wsuNS = WSSEConstants.NS_WSU_WSF11;
}
Element root = (Element) doc.getDocumentElement().getElementsByTagNameNS(wsseNS, SAMLConstants.TAG_SECURITY).item(0);
XMLSignature signature = null;
try {
ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, SAMLConstants.PREFIX_DS);
Element wsucontext = org.apache.xml.security.utils.XMLUtils.createDSctx(doc, "wsu", wsuNS);
NodeList wsuNodes = (NodeList) XPathAPI.selectNodeList(doc, "//*[@wsu:Id]", wsucontext);
if (wsuNodes != null && wsuNodes.getLength() != 0) {
for (int i = 0; i < wsuNodes.getLength(); i++) {
Element elem = (Element) wsuNodes.item(i);
String id = elem.getAttributeNS(wsuNS, "Id");
if (id != null && id.length() != 0) {
elem.setIdAttributeNS(wsuNS, "Id", true);
}
}
}
String certAlias = keystore.getCertificateAlias(cert);
PrivateKey privateKey = (PrivateKey) keystore.getPrivateKey(certAlias);
if (privateKey == null) {
SAMLUtilsCommon.debug.error("private key is null");
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("nullprivatekey"));
}
if (algorithm == null || algorithm.length() == 0) {
algorithm = getKeyAlgorithm(privateKey);
}
if (!isValidAlgorithm(algorithm)) {
throw new XMLSignatureException(SAMLUtilsCommon.bundle.getString("invalidalgorithm"));
}
signature = new XMLSignature(doc, "", algorithm, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
root.appendChild(signature.getElement());
int size = ids.size();
for (int i = 0; i < size; ++i) {
Transforms transforms = new Transforms(doc);
transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
String id = (String) ids.get(i);
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("id = " + id);
}
signature.addDocument("#" + id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
}
KeyInfo keyInfo = signature.getKeyInfo();
Element securityTokenRef = doc.createElementNS(wsseNS, SAMLConstants.TAG_SECURITYTOKENREFERENCE);
keyInfo.addUnknownElement(securityTokenRef);
securityTokenRef.setAttributeNS(SAMLConstants.NS_XMLNS, SAMLConstants.TAG_XMLNS, wsseNS);
securityTokenRef.setAttributeNS(SAMLConstants.NS_XMLNS, SAMLConstants.TAG_XMLNS_SEC, SAMLConstants.NS_SEC);
securityTokenRef.setAttributeNS(null, SAMLConstants.TAG_USAGE, SAMLConstants.TAG_SEC_MESSAGEAUTHENTICATION);
Element reference = doc.createElementNS(wsseNS, SAMLConstants.TAG_REFERENCE);
reference.setAttributeNS(null, SAMLConstants.TAG_URI, "#" + assertionID);
securityTokenRef.appendChild(reference);
signature.sign(privateKey);
} catch (Exception e) {
SAMLUtilsCommon.debug.error("signWithWSSX509TokenProfile " + "Exception: ", e);
throw new XMLSignatureException(e.getMessage());
}
if (SAMLUtilsCommon.debug.messageEnabled()) {
SAMLUtilsCommon.debug.message("SAML Signed doc = " + XMLUtils.print(doc.getDocumentElement()));
}
return signature.getElement();
}
use of org.apache.xml.security.transforms.Transforms in project xades4j by luisgoncalves.
the class KeyInfoBuilder method buildKeyInfo.
void buildKeyInfo(X509Certificate signingCertificate, XMLSignature xmlSig) throws KeyingDataException, UnsupportedAlgorithmException {
// Check key usage.
// - KeyUsage[0] = digitalSignature
// - KeyUsage[1] = nonRepudiation
boolean[] keyUsage = signingCertificate.getKeyUsage();
if (keyUsage != null && !keyUsage[0] && !keyUsage[1]) {
throw new SigningCertKeyUsageException(signingCertificate);
}
try {
signingCertificate.checkValidity();
} catch (CertificateException ce) {
// CertificateExpiredException or CertificateNotYetValidException
throw new SigningCertValidityException(signingCertificate);
}
if (this.basicSignatureOptionsProvider.includeSigningCertificate()) {
try {
X509Data x509Data = new X509Data(xmlSig.getDocument());
x509Data.addCertificate(signingCertificate);
x509Data.addSubjectName(signingCertificate);
x509Data.addIssuerSerial(signingCertificate.getIssuerX500Principal().getName(), signingCertificate.getSerialNumber());
xmlSig.getKeyInfo().add(x509Data);
if (this.basicSignatureOptionsProvider.signSigningCertificate()) {
String keyInfoId = xmlSig.getId() + "-keyinfo";
xmlSig.getKeyInfo().setId(keyInfoId);
// Use same canonicalization URI as specified in the ds:CanonicalizationMethod for Signature.
Algorithm canonAlg = this.algorithmsProvider.getCanonicalizationAlgorithmForSignature();
CanonicalizerUtils.checkC14NAlgorithm(canonAlg);
Transforms transforms = TransformUtils.createTransforms(canonAlg, this.algorithmsParametersMarshaller, xmlSig.getDocument());
xmlSig.addDocument('#' + keyInfoId, transforms, this.algorithmsProvider.getDigestAlgorithmForDataObjsReferences());
}
} catch (XMLSignatureException ex) {
throw new UnsupportedAlgorithmException("Digest algorithm not supported in the XML Signature provider", this.algorithmsProvider.getDigestAlgorithmForDataObjsReferences(), ex);
} catch (XMLSecurityException ex) {
throw new KeyingDataException(ex.getMessage(), ex);
}
}
if (this.basicSignatureOptionsProvider.includePublicKey()) {
xmlSig.addKeyInfo(signingCertificate.getPublicKey());
}
}
use of org.apache.xml.security.transforms.Transforms in project xades4j by luisgoncalves.
the class SignatureUtils method processReferences.
static ReferencesRes processReferences(XMLSignature signature) throws QualifyingPropertiesIncorporationException, XAdES4jXMLSigException {
SignedInfo signedInfo = signature.getSignedInfo();
List<RawDataObjectDesc> dataObjsReferences = new ArrayList<RawDataObjectDesc>(signedInfo.getLength() - 1);
Reference signedPropsRef = null;
for (int i = 0; i < signedInfo.getLength(); i++) {
Reference ref;
try {
ref = signedInfo.item(i);
} catch (XMLSecurityException ex) {
throw new XAdES4jXMLSigException(String.format("Cannot process the %dth reference", i), ex);
}
String refTypeUri = ref.getType();
// with its value set to: http://uri.etsi.org/01903#SignedProperties."
if (QualifyingProperty.SIGNED_PROPS_TYPE_URI.equals(refTypeUri)) {
if (signedPropsRef != null) {
throw new QualifyingPropertiesIncorporationException("Multiple references to SignedProperties");
}
signedPropsRef = ref;
} else {
RawDataObjectDesc dataObj = new RawDataObjectDesc(ref);
dataObjsReferences.add(dataObj);
try {
Transforms transfs = ref.getTransforms();
if (transfs != null) {
for (int j = 0; j < transfs.getLength(); ++j) {
dataObj.withTransform(new GenericAlgorithm(transfs.item(j).getURI()));
}
}
} catch (XMLSecurityException ex) {
throw new XAdES4jXMLSigException("Cannot process transfroms", ex);
}
}
}
if (null == signedPropsRef) // !!!
// Still may be a XAdES signature, if the signing certificate is
// protected. For now, that scenario is not supported.
{
throw new QualifyingPropertiesIncorporationException("SignedProperties reference not found");
}
return new ReferencesRes(dataObjsReferences, signedPropsRef);
}
use of org.apache.xml.security.transforms.Transforms in project santuario-java by apache.
the class RetrievalMethodResolver method resolveInput.
/**
* Resolves the input from the given retrieval method
* @return the input from the given retrieval method
* @throws XMLSecurityException
*/
private static XMLSignatureInput resolveInput(RetrievalMethod rm, String baseURI, boolean secureValidation) throws XMLSecurityException {
Attr uri = rm.getURIAttr();
// Apply the transforms
Transforms transforms = rm.getTransforms();
ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation);
XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation);
if (transforms != null) {
LOG.debug("We have Transforms");
resource = transforms.performTransforms(resource);
}
return resource;
}
use of org.apache.xml.security.transforms.Transforms in project santuario-java by apache.
the class SignedEncryptedTest method secureAndVerify.
public void secureAndVerify(TransformerFactory transformerFactory, boolean useDocumentSerializer) throws Exception {
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = null;
try (InputStream is = new ByteArrayInputStream(SAMPLE_MSG.getBytes(StandardCharsets.UTF_8))) {
document = builder.parse(is);
}
// Set up the Key
KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
KeyPair kp = rsaKeygen.generateKeyPair();
PrivateKey priv = kp.getPrivate();
PublicKey pub = kp.getPublic();
XMLSignature sig = new XMLSignature(document, "", XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
Element sigElement = sig.getElement();
document.getDocumentElement().appendChild(sigElement);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
Element element = (Element) xpath.evaluate("//*[local-name()='Body']", document, XPathConstants.NODE);
String id = UUID.randomUUID().toString();
element.setAttributeNS(null, "Id", id);
element.setIdAttributeNS(null, "Id", true);
Transforms transforms = new Transforms(document);
transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
sig.addDocument("#" + id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
sig.addKeyInfo(pub);
sig.sign(priv);
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(256);
SecretKey secretKey = keygen.generateKey();
XMLCipher cipher = XMLCipher.getInstance(XMLCipher.AES_128);
cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
document = cipher.doFinal(document, element, true);
XMLCipher deCipher = XMLCipher.getInstance(XMLCipher.AES_128);
if (transformerFactory != null && deCipher.getSerializer() instanceof TransformSerializer) {
Field f = deCipher.getSerializer().getClass().getDeclaredField("transformerFactory");
f.setAccessible(true);
f.set(deCipher.getSerializer(), transformerFactory);
}
if (useDocumentSerializer) {
deCipher.setSerializer(new DocumentSerializer());
}
deCipher.init(XMLCipher.DECRYPT_MODE, secretKey);
deCipher.doFinal(document, element, true);
XMLSignature xmlSignatureVerifier = new XMLSignature(sigElement, "");
Assert.assertTrue(xmlSignatureVerifier.checkSignatureValue(pub));
}
Aggregations