本文整理匯總了Java中javax.xml.crypto.dsig.DigestMethod類的典型用法代碼示例。如果您正苦於以下問題:Java DigestMethod類的具體用法?Java DigestMethod怎麽用?Java DigestMethod使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
DigestMethod類屬於javax.xml.crypto.dsig包,在下文中一共展示了DigestMethod類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: certificateChain
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
@Test
public void certificateChain() throws Exception {
XmlSignerEndpoint endpoint = getSignerEndpoint();
endpoint.setProperties(new CertChainXAdESSignatureProperties());
Document doc = testEnveloping();
Map<String, String> prefix2Namespace = getPrefix2NamespaceMap();
String pathToSignatureProperties = getPathToSignatureProperties();
// signing certificate
checkXpath(doc, pathToSignatureProperties + "etsi:SigningCertificate/etsi:Cert/etsi:CertDigest/ds:DigestMethod/@Algorithm",
prefix2Namespace, DigestMethod.SHA256);
checkXpath(doc, pathToSignatureProperties + "etsi:SigningCertificate/etsi:Cert/etsi:CertDigest/ds:DigestValue/text()",
prefix2Namespace, NOT_EMPTY);
checkXpath(doc, pathToSignatureProperties + "etsi:SigningCertificate/etsi:Cert/etsi:IssuerSerial/ds:X509IssuerName/text()",
prefix2Namespace, NOT_EMPTY);
checkXpath(doc, pathToSignatureProperties + "etsi:SigningCertificate/etsi:Cert/etsi:IssuerSerial/ds:X509SerialNumber/text()",
prefix2Namespace, NOT_EMPTY);
}
示例2: addDigestInfosAsReferences
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的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);
}
}
示例3: sign
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的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);
}
}
示例4: XmlSignatureHandler
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
public XmlSignatureHandler() throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException {
this.builderFactory = DocumentBuilderFactory.newInstance();
this.builderFactory.setNamespaceAware(true);
this.transformerFactory = TransformerFactory.newInstance();
this.signatureFactory = XMLSignatureFactory.getInstance("DOM");
this.digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);
this.transformList = new ArrayList<Transform>(2);
this.transformList.add(
signatureFactory.newTransform(
Transform.ENVELOPED,
(TransformParameterSpec) null));
this.transformList.add(
signatureFactory.newTransform(
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315",
(TransformParameterSpec) null));
this.canonicalizationMethod = this.signatureFactory.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null);
this.signatureMethod = this.signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
this.keyInfoFactory = this.signatureFactory.getKeyInfoFactory();
}
示例5: signSamlElement
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的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);
}
}
示例6: performSign
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
private void performSign ( final Key key, final Certificate cert ) throws Exception
{
final SignatureRequestBuilder builder = new SignatureRequestBuilder ();
final Document doc = builder.fromString ( this.callback.getDocument () );
final Configuration cfg = new RequestSigner.Configuration ();
cfg.setDigestMethod ( DigestMethod.SHA1 );
new RequestSigner ( cfg ).sign ( key, cert, doc );
this.callback.setSignedDocument ( builder.toString ( doc, false ) );
}
示例7: HMACSignatureAlgorithmTest
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
public HMACSignatureAlgorithmTest() throws Exception {
//
// If the BouncyCastle provider is not installed, then try to load it
// via reflection.
//
if (Security.getProvider("BC") == null) {
Constructor<?> cons = null;
try {
Class<?> c = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
cons = c.getConstructor(new Class[] {});
} catch (Exception e) {
//ignore
}
if (cons != null) {
Provider provider = (Provider)cons.newInstance();
Security.insertProviderAt(provider, 2);
bcInstalled = true;
}
}
db = XMLUtils.createDocumentBuilder(false);
// create common objects
fac = XMLSignatureFactory.getInstance("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());
withoutComments = fac.newCanonicalizationMethod
(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
// Digest Methods
sha1 = fac.newDigestMethod(DigestMethod.SHA1, null);
hmacSha1 = fac.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#hmac-sha1", null);
hmacSha224 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha224", null);
hmacSha256 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", null);
hmacSha384 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha384", null);
hmacSha512 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-sha512", null);
ripemd160 = fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160", null);
sks = new KeySelectors.SecretKeySelector("testkey".getBytes("ASCII"));
}
示例8: test_create_signature_enveloping
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的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));
}
示例9: assinarDocumento
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的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);
}
}
示例10: getMessageDigestAlgorithm
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
protected String getMessageDigestAlgorithm(String xmlSigDigestMethod, String errorMessage) throws XmlSignatureException {
String algorithm;
if (DigestMethod.SHA1.equals(xmlSigDigestMethod)) {
algorithm = "SHA-1";
} else if (DigestMethod.SHA256.equals(xmlSigDigestMethod)) {
algorithm = "SHA-256";
} else if ("http://www.w3.org/2001/04/xmldsig-more#sha384".equals(xmlSigDigestMethod)) {
algorithm = "SHA-384";
} else if (DigestMethod.SHA512.equals(getDigestAlgorithmForSigningCertificate())) {
algorithm = "SHA-512";
} else {
throw new XmlSignatureException(String.format(errorMessage, xmlSigDigestMethod));
}
return algorithm;
}
示例11: getDigestAlgorithmUri
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
protected String getDigestAlgorithmUri() throws XmlSignatureException {
String result = getConfiguration().getDigestAlgorithm();
if (result == null) {
String signatureAlgorithm = getConfiguration().getSignatureAlgorithm();
if (signatureAlgorithm != null) {
if (signatureAlgorithm.contains(SHA1)) {
result = DigestMethod.SHA1;
} else if (signatureAlgorithm.contains(SHA224)) {
result = HTTP_WWW_W3_ORG_2001_04_XMLDSIG_MORE_SHA224;
} else if (signatureAlgorithm.contains(SHA256)) {
result = DigestMethod.SHA256;
} else if (signatureAlgorithm.contains(SHA384)) {
result = HTTP_WWW_W3_ORG_2001_04_XMLDSIG_MORE_SHA384;
} else if (signatureAlgorithm.contains(SHA512)) {
result = DigestMethod.SHA512;
} else if (signatureAlgorithm.contains(RIPEMD160)) {
return DigestMethod.RIPEMD160;
}
}
}
if (result != null) {
LOG.debug("Digest algorithm: {}", result);
return result;
}
throw new XmlSignatureException(
"Digest algorithm missing for XML signature generation. Specify the digest algorithm in the configuration.");
}
示例12: preSign
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
List<Transform> transforms = new LinkedList<Transform>();
Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");
// XPath v1 - slow...
// Transform envelopedTransform = signatureFactory.newTransform(
// CanonicalizationMethod.XPATH, new XPathFilterParameterSpec(
// "not(ancestor-or-self::ds:Signature)",
// xpathNamespaceMap));
// XPath v2 - fast...
List<XPathType> types = new ArrayList<XPathType>(1);
types.add(new XPathType("/descendant::*[name()='ds:Signature']", XPathType.Filter.SUBTRACT, xpathNamespaceMap));
Transform envelopedTransform = signatureFactory.newTransform(CanonicalizationMethod.XPATH2,
new XPathFilter2ParameterSpec(types));
transforms.add(envelopedTransform);
Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
(TransformParameterSpec) null);
transforms.add(exclusiveTransform);
Reference reference = signatureFactory.newReference("", digestMethod, transforms, null, this.dsReferenceId);
references.add(reference);
}
示例13: preSign
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
List<Transform> transforms = new LinkedList<Transform>();
Transform envelopedTransform = signatureFactory.newTransform(CanonicalizationMethod.ENVELOPED,
(TransformParameterSpec) null);
transforms.add(envelopedTransform);
Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
(TransformParameterSpec) null);
transforms.add(exclusiveTransform);
Reference reference = signatureFactory.newReference("", digestMethod, transforms, null, null);
references.add(reference);
}
示例14: preSign
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
LOG.debug("pre sign");
Element dateElement = document.createElementNS("", "dc:date");
dateElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:dc", "http://purl.org/dc/elements/1.1/");
DateTime dateTime = new DateTime(DateTimeZone.UTC);
DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
String now = fmt.print(dateTime);
now = now.substring(0, now.indexOf("Z"));
LOG.debug("now: " + now);
dateElement.setTextContent(now);
String signaturePropertyId = "sign-prop-" + UUID.randomUUID().toString();
List<XMLStructure> signaturePropertyContent = new LinkedList<XMLStructure>();
signaturePropertyContent.add(new DOMStructure(dateElement));
SignatureProperty signatureProperty = signatureFactory.newSignatureProperty(signaturePropertyContent,
"#" + signatureId, signaturePropertyId);
List<XMLStructure> objectContent = new LinkedList<XMLStructure>();
List<SignatureProperty> signaturePropertiesContent = new LinkedList<SignatureProperty>();
signaturePropertiesContent.add(signatureProperty);
SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertiesContent,
null);
objectContent.add(signatureProperties);
objects.add(signatureFactory.newXMLObject(objectContent, null, null, null));
DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
Reference reference = signatureFactory.newReference("#" + signaturePropertyId, digestMethod);
references.add(reference);
}
示例15: addManifestObject
import javax.xml.crypto.dsig.DigestMethod; //導入依賴的package包/類
private void addManifestObject(XMLSignatureFactory signatureFactory, Document document, String signatureId,
List<Reference> references, List<XMLObject> objects)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
Manifest manifest = constructManifest(signatureFactory, document);
String objectId = "idPackageObject"; // really has to be this value.
List<XMLStructure> objectContent = new LinkedList<XMLStructure>();
objectContent.add(manifest);
addSignatureTime(signatureFactory, document, signatureId, objectContent);
objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null));
DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null,
"http://www.w3.org/2000/09/xmldsig#Object", null);
references.add(reference);
}