本文整理汇总了Java中javax.xml.crypto.dsig.Reference类的典型用法代码示例。如果您正苦于以下问题:Java Reference类的具体用法?Java Reference怎么用?Java Reference使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Reference类属于javax.xml.crypto.dsig包,在下文中一共展示了Reference类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: isSignatureGlobal
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
@SuppressWarnings("rawtypes")
private static boolean isSignatureGlobal(XMLSignature signature, String rootID) {
LOG.debug("Starting signature globality check...");
LOG.debug("Signature: {}", signature);
LOG.debug("Root ID: {}", rootID);
boolean isGlobal = false;
// We check each Reference. One must be the rootId or be ""
String refRootID = "#" + rootID;
for (Object o : signature.getSignedInfo().getReferences()) {
String uri = ((Reference) o).getURI();
if ("".equals(uri) || refRootID.equals(uri)) {
isGlobal = true;
break;
}
}
LOG.debug("Signature globality check result: {}", isGlobal);
return isGlobal;
}
示例2: explainValidationProblem
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
private static String explainValidationProblem(
DOMValidateContext context, XMLSignature signature)
throws XMLSignatureException {
@SuppressWarnings("unchecked") // Safe by specification.
List<Reference> references = signature.getSignedInfo().getReferences();
StringBuilder builder = new StringBuilder();
builder.append("Signature failed core validation\n");
boolean sv = signature.getSignatureValue().validate(context);
builder.append("Signature validation status: " + sv + "\n");
for (Reference ref : references) {
builder.append("references[");
builder.append(ref.getURI());
builder.append("] validity status: ");
builder.append(ref.validate(context));
builder.append("\n");
}
return builder.toString();
}
示例3: getReferencedSameDocumentObjects
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
protected List<XMLObject> getReferencedSameDocumentObjects(List<Reference> relevantReferences, List<XMLObject> relevantObjects) {
List<XMLObject> referencedObjects = new ArrayList<XMLObject>(1);
for (Reference ref : relevantReferences) {
String refUri = getSameDocumentReferenceUri(ref);
if (refUri == null) {
continue;
}
XMLObject referencedOb = getReferencedObject(relevantObjects, refUri);
if (referencedOb != null) {
referencedObjects.add(referencedOb);
continue;
}
// content could also be indirectly referenced via manifest
addManifestReferencedObjects(relevantObjects, referencedObjects, refUri);
}
return referencedObjects;
}
示例4: addManifestReferencedObjects
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
@SuppressWarnings("unchecked")
protected void addManifestReferencedObjects(List<XMLObject> allObjects, List<XMLObject> referencedObjects, String manifestId) {
Manifest manifest = getReferencedManifest(allObjects, manifestId);
if (manifest == null) {
return;
}
for (Reference manifestRef : (List<Reference>) manifest.getReferences()) {
String manifestRefUri = getSameDocumentReferenceUri(manifestRef);
if (manifestRefUri == null) {
continue;
}
XMLObject manifestReferencedOb = getReferencedObject(allObjects, manifestRefUri);
if (manifestReferencedOb != null) {
referencedObjects.add(manifestReferencedOb);
}
}
}
示例5: get
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
@Override
public Output get(Input input) throws Exception {
Transform transform = input.getSignatureFactory().newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null);
Reference ref = input.getSignatureFactory().newReference("#propertiesObject",
input.getSignatureFactory().newDigestMethod(input.getContentDigestAlgorithm(), null), Collections.singletonList(transform),
null, null);
String doc2 = "<ts:timestamp xmlns:ts=\"http:/timestamp\">" + System.currentTimeMillis() + "</ts:timestamp>";
InputStream is = new ByteArrayInputStream(doc2.getBytes("UTF-8"));
Document doc = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).parse(is);
DOMStructure structure = new DOMStructure(doc.getDocumentElement());
SignatureProperty prop = input.getSignatureFactory().newSignatureProperty(Collections.singletonList(structure),
input.getSignatureId(), "property");
SignatureProperties properties = input.getSignatureFactory().newSignatureProperties(Collections.singletonList(prop), "properties");
XMLObject propertiesObject = input.getSignatureFactory().newXMLObject(Collections.singletonList(properties), "propertiesObject",
null, null);
XmlSignatureProperties.Output result = new Output();
result.setReferences(Collections.singletonList(ref));
result.setObjects(Collections.singletonList(propertiesObject));
return result;
}
示例6: addDigestInfosAsReferences
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
private void addDigestInfosAsReferences(List<DigestInfo> digestInfos, XMLSignatureFactory signatureFactory,
List<Reference> references)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MalformedURLException {
if (null == digestInfos) {
return;
}
for (DigestInfo digestInfo : digestInfos) {
byte[] documentDigestValue = digestInfo.digestValue;
DigestMethod digestMethod = signatureFactory.newDigestMethod(getXmlDigestAlgo(digestInfo.digestAlgo), null);
String uri = FilenameUtils.getName(new File(digestInfo.description).toURI().toURL().getFile());
Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null,
documentDigestValue);
references.add(reference);
}
}
示例7: sign
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
public <T extends Node> T sign(T node) {
checkNotNull(node);
checkArgument(node instanceof Document || node instanceof Element);
try {
Element element = node instanceof Document ? ((Document) node).getDocumentElement() : (Element) node;
DOMSignContext dsc = new DOMSignContext(privateKey, element);
XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
List<Transform> transformList = new LinkedList<>();
transformList.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
transformList.add(signatureFactory.newTransform(C14N_TRANSFORM_METHOD, (TransformParameterSpec) null));
Node child = findFirstElementChild(element);
((Element) child).setIdAttribute("Id", true);
String id = child.getAttributes().getNamedItem("Id").getNodeValue();
String uri = String.format("#%s", id);
Reference reference = signatureFactory.newReference(uri,
signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null);
SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory
.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
KeyInfoFactory kif = signatureFactory.getKeyInfoFactory();
X509Data x509Data = kif.newX509Data(Collections.singletonList(certificateChain[0]));
KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(x509Data));
XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
xmlSignature.sign(dsc);
return node;
}
catch (Exception ex) {
throw new IllegalArgumentException("Erro ao assinar XML.", ex);
}
}
示例8: sign
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
public synchronized void sign()
throws MarshalException,
XMLSignatureException,
KeyException {
if (this.document == null)
throw new RuntimeException("Can't sign a NULL document");
Reference reference = this.signatureFactory.newReference(
referenceUri,
this.digestMethod,
this.transformList,
null,
null);
SignedInfo signedInfo = this.signatureFactory.newSignedInfo(
this.canonicalizationMethod,
this.signatureMethod,
Collections.singletonList(reference));
// Create the KeyInfo containing the X509Data.
X509Data xd = this.keyInfoFactory.newX509Data(
Collections.singletonList(this.certificateWithKey.certificate));
KeyInfo keyInfo = this.keyInfoFactory.newKeyInfo(Collections.singletonList(xd));
XMLSignature signature = this.signatureFactory.newXMLSignature(
signedInfo,
keyInfo);
DOMSignContext signingContext = new DOMSignContext(
this.certificateWithKey.privateKey,
document.getDocumentElement());
signature.sign(signingContext);
}
示例9: validate
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
public synchronized boolean validate()
throws MarshalException,
XMLSignatureException {
// Find Signature element.
NodeList list = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (list.getLength() == 0) {
throw new RuntimeException("Cannot find Signature element");
}
// Create a DOMValidateContext and specify a KeySelector
// and document context.
DOMValidateContext validateContext = new DOMValidateContext(new X509CertificateKeySelector(), list.item(0));
// Unmarshal the XMLSignature.
XMLSignature signature = this.signatureFactory.unmarshalXMLSignature(validateContext);
// Validate the XMLSignature.
if (signature.validate(validateContext)) {
return true;
} else {
Iterator<?> i = signature.getSignedInfo().getReferences().iterator();
for (int j = 0; i.hasNext(); j++) {
System.out.print("ref[" + j + "] -> ");
Reference ref = (Reference) i.next();
System.out.print(ref.getURI());
System.out.print(", ");
System.out.print(ref.getDigestMethod().toString());
System.out.print(", ");
System.out.print(ref.getId());
boolean refValid = ref.validate(validateContext);
System.out.print(", validity status: " + refValid + "\r\n");
}
return false;
}
}
示例10: signSamlElement
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
/**
* Sign SAML element.
*
* @param element the element
* @param privKey the priv key
* @param pubKey the pub key
* @return the element
*/
private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) {
try {
final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS);
final XMLSignatureFactory sigFactory = XMLSignatureFactory
.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
final List<Transform> envelopedTransform = Collections.singletonList(sigFactory.newTransform(Transform.ENVELOPED,
(TransformParameterSpec) null));
final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory
.newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null);
// Create the SignatureMethod based on the type of key
final SignatureMethod signatureMethod;
final String algorithm = pubKey.getAlgorithm();
switch (algorithm) {
case "DSA":
signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
break;
case "RSA":
signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
break;
default:
throw new RuntimeException("Error signing SAML element: Unsupported type of key");
}
final CanonicalizationMethod canonicalizationMethod = sigFactory
.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
(C14NMethodParameterSpec) null);
// Create the SignedInfo
final SignedInfo signedInfo = sigFactory.newSignedInfo(
canonicalizationMethod, signatureMethod, Collections.singletonList(ref));
// Create a KeyValue containing the DSA or RSA PublicKey
final KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory();
final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey);
// Create a KeyInfo and add the KeyValue to it
final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValuePair));
// Convert the JDOM document to w3c (Java XML signature API requires w3c representation)
final Element w3cElement = toDom(element);
// Create a DOMSignContext and specify the DSA/RSA PrivateKey and
// location of the resulting XMLSignature's parent element
final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement);
final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement);
dsc.setNextSibling(xmlSigInsertionPoint);
// Marshal, generate (and sign) the enveloped signature
final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo);
signature.sign(dsc);
return toJdom(w3cElement);
} catch (final Exception e) {
throw new RuntimeException("Error signing SAML element: " + e.getMessage(), e);
}
}
示例11: sign
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
public Document sign(FileInputStream fileStream, KeyPair keyPair)
throws ParserConfigurationException, SAXException, IOException,
NoSuchAlgorithmException, InvalidAlgorithmParameterException,
KeyException, MarshalException, XMLSignatureException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(fileStream);
DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
document.getDocumentElement());
XMLSignatureFactory signFactory = XMLSignatureFactory
.getInstance("DOM");
Reference ref = signFactory.newReference("", signFactory
.newDigestMethod(digestMethod, null), Collections
.singletonList(signFactory.newTransform(Transform.ENVELOPED,
(TransformParameterSpec) null)), null, null);
SignedInfo si = signFactory.newSignedInfo(signFactory
.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
(C14NMethodParameterSpec) null), signFactory
.newSignatureMethod(signatureMethod, null), Collections
.singletonList(ref));
KeyInfoFactory kif = signFactory.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(keyPair.getPublic());
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
XMLSignature signature = signFactory.newXMLSignature(si, ki);
signature.sign(signContext);
return document;
}
示例12: test_create_signature_enveloping
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
private void test_create_signature_enveloping(
SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks
) throws Exception {
// create reference
Reference ref = fac.newReference("#DSig.Object_1", dm, null,
XMLObject.TYPE, null);
// create SignedInfo
SignedInfo si = fac.newSignedInfo(withoutComments, sm,
Collections.singletonList(ref));
Document doc = db.newDocument();
// create Objects
Element webElem = doc.createElementNS(null, "Web");
Text text = doc.createTextNode("up up and away");
webElem.appendChild(text);
XMLObject obj = fac.newXMLObject(Collections.singletonList
(new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null);
// create XMLSignature
XMLSignature sig = fac.newXMLSignature
(si, ki, Collections.singletonList(obj), null, null);
DOMSignContext dsc = new DOMSignContext(signingKey, doc);
dsc.setDefaultNamespacePrefix("dsig");
sig.sign(dsc);
TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement());
// XMLUtils.outputDOM(doc.getDocumentElement(), System.out);
DOMValidateContext dvc = new DOMValidateContext
(ks, doc.getDocumentElement());
XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
assertTrue(sig.equals(sig2));
assertTrue(sig2.validate(dvc));
}
示例13: assinarDocumento
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
public String assinarDocumento(final String conteudoXml) throws Exception {
final KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (InputStream certificadoStream = new ByteArrayInputStream(this.config.getCertificado())) {
keyStore.load(certificadoStream, this.config.getCertificadoSenha().toCharArray());
}
final KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyStore.aliases().nextElement(), new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray()));
final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
final List<Transform> transforms = new ArrayList<>(2);
transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
transforms.add(signatureFactory.newTransform(AssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null));
final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate()));
final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
try (StringReader stringReader = new StringReader(conteudoXml)) {
final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(stringReader));
for (final String elementoAssinavel : AssinaturaDigital.ELEMENTOS_ASSINAVEIS) {
final NodeList elements = document.getElementsByTagName(elementoAssinavel);
for (int i = 0; i < elements.getLength(); i++) {
final Element element = (Element) elements.item(i);
final String id = element.getAttribute("Id");
element.setIdAttribute("Id", true);
final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null);
final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference));
final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode()));
}
}
return this.converteDocumentParaXml(document);
}
}
示例14: getNodeForMessageBodyInEnvelopingCase
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
protected Node getNodeForMessageBodyInEnvelopingCase(Input input) throws Exception { //NOPMD
Node node;
List<Reference> relevantReferences = getReferencesForMessageMapping(input);
List<XMLObject> relevantObjects = getObjectsForMessageMapping(input);
DOMStructure domStruc = getDomStructureForMessageBody(relevantReferences, relevantObjects);
node = domStruc.getNode();
return node;
}
示例15: getDomStructureForMessageBody
import javax.xml.crypto.dsig.Reference; //导入依赖的package包/类
/**
* Returns the DOM structure which is transformed to a byte array and set to
* the camel message body.
*
* @param relevantReferences
* input from method
* {@link #getReferencesForMessageMapping(ReferencesAndObjects)}
* @param relevantObjects
* input from method
* {@link #getObjectsForMessageMapping(ReferencesAndObjects)}
* @return dom structure
* @throws Exception
* if an error occurs
*/
protected DOMStructure getDomStructureForMessageBody(List<Reference> relevantReferences, List<XMLObject> relevantObjects)
throws Exception { //NOPMD
List<XMLObject> referencedObjects = getReferencedSameDocumentObjects(relevantReferences, relevantObjects);
if (referencedObjects.isEmpty()) {
throw new XmlSignatureException(
String.format("Unsupported XML signature document: Content object not found in the enveloping XML signature."));
}
if (referencedObjects.size() > 1) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < referencedObjects.size(); i++) {
XMLObject xmlOb = referencedObjects.get(i);
sb.append(xmlOb.getId());
if (i < referencedObjects.size() - 1) {
sb.append(", ");
}
}
throw new XmlSignatureException(String.format(
"Unsupported XML signature document: More than one content objects found. Object IDs: %s", sb.toString()));
}
@SuppressWarnings("unchecked")
List<XMLStructure> structures = referencedObjects.get(0).getContent();
if (structures.size() == 0) {
throw new XmlSignatureException(
"Unsupported XML signature: XML signature is not enveloping; content not found in XML signature: structure list is empty.");
}
if (structures.size() > 1) {
throw new XmlSignatureException("Unsupported XML signature: more than one structure elements in referenced content object.");
}
XMLStructure structure = structures.get(0);
// only dom currently supported
DOMStructure domStruc = (DOMStructure) structure;
return domStruc;
}