本文整理匯總了Java中javax.xml.crypto.dsig.XMLSignatureFactory.getInstance方法的典型用法代碼示例。如果您正苦於以下問題:Java XMLSignatureFactory.getInstance方法的具體用法?Java XMLSignatureFactory.getInstance怎麽用?Java XMLSignatureFactory.getInstance使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類javax.xml.crypto.dsig.XMLSignatureFactory
的用法示例。
在下文中一共展示了XMLSignatureFactory.getInstance方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: verifySignature
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
/**
* Verification via the default JSR105 implementation triggers some
* canonicalization errors.
*
* @param odfUrl
* @param signatureNode
* @throws MarshalException
* @throws XMLSignatureException
*/
private boolean verifySignature(URL odfUrl, Node signatureNode) throws MarshalException, XMLSignatureException {
// work-around for Java 7
Element signedPropertiesElement = (Element) ((Element) signatureNode)
.getElementsByTagNameNS(XAdESXLSignatureFacet.XADES_NAMESPACE, "SignedProperties").item(0);
if (null != signedPropertiesElement) {
signedPropertiesElement.setIdAttribute("Id", true);
}
DOMValidateContext domValidateContext = new DOMValidateContext(new KeyInfoKeySelector(), signatureNode);
ODFURIDereferencer dereferencer = new ODFURIDereferencer(odfUrl);
domValidateContext.setURIDereferencer(dereferencer);
XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance();
LOG.debug("java version: " + System.getProperty("java.version"));
/*
* Requires Java 6u10 because of a bug. See also:
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6696582
*/
XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext);
boolean validity = xmlSignature.validate(domValidateContext);
return validity;
}
示例2: useKeystore
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
public Assinador useKeystore(KeyStore keyStore, String keyAlias, String privateKeyPass) throws UnrecoverableKeyException,
KeyStoreException, NoSuchAlgorithmException, KeyException {
this.privateKey = (PrivateKey) keyStore.getKey(keyAlias, privateKeyPass.toCharArray());
this.cert = (X509Certificate) keyStore.getCertificate(keyAlias);
// Retrieve signing key
// PrivateKey privateKey = (PrivateKey) keyStore.getKey(KEY_ALIAS,
// PRIVATE_KEY_PASS.toCharArray());
//
// X509Certificate cert = (X509Certificate)
// keyStore.getCertificate(KEY_ALIAS);
try {
String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
sigFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
} catch (Throwable e) {
throw new RuntimeException(
"Error while loading XMLSignatureFactory (using 'jsr105Provider=org.jcp.xml.dsig.internal.dom.XMLDSigRI')", e);
}
PublicKey publicKey = cert.getPublicKey();
// Create a KeyValue containing the RSA PublicKey
this.keyInfoFactory = sigFactory.getKeyInfoFactory();
this.keyValue = keyInfoFactory.newKeyValue(publicKey);
return this;
}
示例3: isValid
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
public boolean isValid() throws Exception {
NodeList nodes = xmlDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nodes == null || nodes.getLength() == 0) {
throw new Exception("Can't find signature in document.");
}
if (setIdAttributeExists()) {
tagIdAttributes(xmlDoc);
}
X509Certificate cert = samlSettings.getCertificate();
DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), nodes.item(0));
XMLSignatureFactory sigF = XMLSignatureFactory.getInstance("DOM");
XMLSignature xmlSignature = sigF.unmarshalXMLSignature(ctx);
return xmlSignature.validate(ctx);
}
示例4: XmlSignatureHandler
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的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.XMLSignatureFactory; //導入方法依賴的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: RequestSigner
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
public RequestSigner ( final Configuration configuration ) throws Exception
{
this.fac = XMLSignatureFactory.getInstance ( "DOM" );
this.md = this.fac.newDigestMethod ( configuration.getDigestMethod (), null );
this.kif = this.fac.getKeyInfoFactory ();
this.t = this.fac.newTransform ( Transform.ENVELOPED, (TransformParameterSpec)null );
this.ref = this.fac.newReference ( "", this.md, Collections.singletonList ( this.t ), null, null );
this.cm = this.fac.newCanonicalizationMethod ( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec)null );
}
示例7: sign
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的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;
}
示例8: validate
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
private boolean validate(final DOMValidateContext validationContext)
throws DigitalSignatureValidationException {
try {
// if (getLogger().isDebugLoggingEnabled()) {
// enableReferenceCaching(validationContext);
// }
XMLSignatureFactory factory = XMLSignatureFactory
.getInstance(XML_MECHANISM_TYPE);
XMLSignature signature = factory
.unmarshalXMLSignature(validationContext);
boolean validationResult = signature.validate(validationContext);
validationResult = workaroundOpenamBug(signature,
validationContext, validationResult);
// if (getLogger().isDebugLoggingEnabled()) {
// debugLogReferences(signature, validationContext);
// }
return validationResult;
} catch (XMLSignatureException | MarshalException exception) {
throw new DigitalSignatureValidationException(
"Error occurred during digital signature validation process",
DigitalSignatureValidationException.ReasonEnum.EXCEPTION_OCCURRED,
exception);
}
}
示例9: main
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
"Signature");
if (nl.getLength() == 0) {
throw new RuntimeException("Couldn't find 'Signature' element");
}
Element element = (Element) nl.item(0);
byte[] keyBytes = Base64.getDecoder().decode(validationKey);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey key = kf.generatePublic(spec);
KeySelector ks = KeySelector.singletonKeySelector(key);
DOMValidateContext vc = new DOMValidateContext(ks, element);
// disable secure validation mode
vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
// set a dummy dereferencer to be able to get content by references
vc.setURIDereferencer(dereferencer);
XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
XMLSignature signature = factory.unmarshalXMLSignature(vc);
// run validation
signature.validate(vc);
}
示例10: main
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
public static void main(String[] args) {
try {
XMLSignatureFactory sf = XMLSignatureFactory.getInstance(
"DOM", "SomeProviderThatDoesNotExist");
}
catch(NoSuchProviderException e) {
// this is expected
}
}
示例11: validateXmlDSig
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
/**
* Utility function to validate XML Signature to do a self check
* @param signed request
* @return
*/
private boolean validateXmlDSig(String signed, X509Certificate cert){
try {
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(signed.getBytes("utf-8")));
NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
NodeList bodyNodeList = doc.getElementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/", "Body");
if (signatureNodeList.getLength() == 0) {
throw new Exception("Cannot find Signature element");
}
DOMValidateContext valContext = new DOMValidateContext(cert.getPublicKey(), signatureNodeList.item(0));
valContext.setIdAttributeNS((Element)bodyNodeList.item(0),"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd","Id");
XMLSignatureFactory factory =
XMLSignatureFactory.getInstance("DOM");
XMLSignature signature =
factory.unmarshalXMLSignature(valContext);
boolean coreValidity = signature.validate(valContext);
/*
//detailed validation - use when solving validity problems
boolean sv = signature.getSignatureValue().validate(valContext);
Iterator<Reference> i = signature.getSignedInfo().getReferences().iterator();
for (int j=0; i.hasNext(); j++) {
boolean refValid = ( i.next()).validate(valContext);
}
*/
return coreValidity;
}
catch (Exception e){
throw new IllegalArgumentException("validation failes", e);
}
}
示例12: HMACSignatureAlgorithmTest
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的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"));
}
示例13: LocalHttpCacheURIDereferencer
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
public LocalHttpCacheURIDereferencer() {
XMLSignatureFactory xmlSignatureFactory =
XMLSignatureFactory.getInstance("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());
ud = xmlSignatureFactory.getURIDereferencer();
String base = BASEDIR == null ? "./": BASEDIR;
File dir = new File(base + FS + "src/test/resources" + FS + "javax" +
FS + "xml" + FS + "crypto" + FS + "dsig");
uriMap = new HashMap<String, File>();
uriMap.put("http://www.w3.org/TR/xml-stylesheet",
new File(dir, "xml-stylesheet"));
uriMap.put("http://www.w3.org/Signature/2002/04/xml-stylesheet.b64",
new File(dir, "xml-stylesheet.b64"));
uriMap.put("http://www.ietf.org/rfc/rfc3161.txt",
new File(dir, "rfc3161.txt"));
}
示例14: dsig
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
public void dsig() throws Exception {
XMLSignatureFactory fac = XMLSignatureFactory.getInstance
("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());
long start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
fac.newCanonicalizationMethod
(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
}
long end = System.currentTimeMillis();
long elapsed = end - start;
if (log.isDebugEnabled()) {
log.debug("Elapsed: " + elapsed);
log.debug("dsig succeeded");
}
}
示例15: isValida
import javax.xml.crypto.dsig.XMLSignatureFactory; //導入方法依賴的package包/類
public boolean isValida(final InputStream xmlStream) throws Exception {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
final Document document = dbf.newDocumentBuilder().parse(xmlStream);
final NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nodeList.getLength() == 0) {
throw new IllegalStateException("N\u00e3o foi encontrada a assinatura do XML.");
}
final String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
final DOMValidateContext validateContext = new DOMValidateContext(new X509KeySelector(), nodeList.item(0));
for (final String tag : AssinaturaDigital.ELEMENTOS_ASSINAVEIS) {
final NodeList elements = document.getElementsByTagName(tag);
if (elements.getLength() > 0) {
validateContext.setIdAttributeNS((Element) elements.item(0), null, "Id");
}
}
return signatureFactory.unmarshalXMLSignature(validateContext).validate(validateContext);
}