本文整理汇总了Java中javax.xml.crypto.dsig.keyinfo.KeyInfoFactory.newX509Data方法的典型用法代码示例。如果您正苦于以下问题:Java KeyInfoFactory.newX509Data方法的具体用法?Java KeyInfoFactory.newX509Data怎么用?Java KeyInfoFactory.newX509Data使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.xml.crypto.dsig.keyinfo.KeyInfoFactory
的用法示例。
在下文中一共展示了KeyInfoFactory.newX509Data方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: loadCertificates
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
private static void loadCertificates(XMLSignatureFactory signatureFactory) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, CertificateException, IOException, CertificadoException {
Certificado certificado = configuracoesNfe.getCertificado();
KeyStore.PrivateKeyEntry pkEntry = null;
KeyStore keyStore = CertificadoService.getKeyStore(certificado);
pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(certificado.getNome(), new KeyStore.PasswordProtection(certificado.getSenha().toCharArray()));
privateKey = pkEntry.getPrivateKey();
KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
List<X509Certificate> x509Content = new ArrayList<X509Certificate>();
x509Content.add(CertificadoService.getCertificate(certificado, keyStore));
X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
}
示例2: sign
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的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);
}
}
示例3: loadCertificates
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
private static void loadCertificates(XMLSignatureFactory signatureFactory) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, CertificateException, IOException, CertificadoException {
Certificado certificado = configuracoesCte.getCertificado();
KeyStore keyStore = CertificadoService.getKeyStore(certificado);
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(certificado.getNome(), new KeyStore.PasswordProtection(certificado.getSenha().toCharArray()));
privateKey = pkEntry.getPrivateKey();
KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
List<X509Certificate> x509Content = new ArrayList<X509Certificate>();
x509Content.add(CertificadoService.getCertificate(certificado, keyStore));
X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
}
示例4: assinarDocumento
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的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);
}
}
示例5: createKeyInfo
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
private KeyInfo createKeyInfo(KeyInfoFactory kif) throws Exception {
X509Certificate[] chain = getCertificateChain();
if (chain == null) {
return null;
}
X509Data x509D = kif.newX509Data(Arrays.asList(chain));
return kif.newKeyInfo(Collections.singletonList(x509D), "_" + UUID.randomUUID().toString());
}
示例6: signDOM
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
public static void signDOM(Node node, PrivateKey privateKey, Certificate origCert) {
XMLSignatureFactory fac = initXMLSigFactory();
X509Certificate cert = (X509Certificate) origCert;
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List<Object> x509Content = new ArrayList<Object>();
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
DOMSignContext dsc = new DOMSignContext(privateKey, node);
dsc.putNamespacePrefix("http://www.w3.org/2000/09/xmldsig#", "ns2");
// Create the XMLSignature, but don't sign it yet.
try {
SignedInfo si = initSignedInfo(fac);
XMLSignature signature = fac.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
示例7: signDOM
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
private void signDOM(Node node, PrivateKey privateKey, Certificate origCert) {
XMLSignatureFactory fac = initXMLSigFactory();
X509Certificate cert = (X509Certificate) origCert;
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List<Object> x509Content = new ArrayList<Object>();
//x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
DOMSignContext dsc = new DOMSignContext(privateKey, node);
dsc.putNamespacePrefix(XML_DIGSIG_NS, "ns2");
// Create the XMLSignature, but don't sign it yet.
try {
SignedInfo si = initSignedInfo(fac);
XMLSignature signature = fac.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
示例8: getKeyInfo
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
public KeyInfo getKeyInfo(String alias, XMLSignatureFactory fac) throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException {
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
X509Certificate x509Certificate = getX509Certificate(alias);
List x509Content = new ArrayList();
x509Content.add(x509Certificate.getSubjectX500Principal().getName());
x509Content.add(x509Certificate);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
return ki;
}
示例9: signSamlAssertion
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
/**
* Signs the SAML assertion using the specified public and private keys.
*
* @param document
* SAML assertion be signed.
* @param privateKey
* Private key used to sign SAML assertion.
* @param publicKey
* Public key used to sign SAML asserion.
* @return w3c element representation of specified document.
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws KeyException
* @throws MarshalException
* @throws XMLSignatureException
*/
private Element signSamlAssertion(Document document, PrivateKey privateKey, X509Certificate certificate)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
XMLSignatureException {
XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
List<Transform> envelopedTransform = Collections.singletonList(signatureFactory.newTransform(
Transform.ENVELOPED, (TransformParameterSpec) null));
Reference ref = signatureFactory.newReference("", signatureFactory.newDigestMethod(DigestMethod.SHA1, null),
envelopedTransform, null, null);
SignatureMethod signatureMethod = null;
if (certificate.getPublicKey() instanceof DSAPublicKey) {
signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
} else if (certificate.getPublicKey() instanceof RSAPublicKey) {
signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
}
CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
Collections.singletonList(ref));
KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
X509Data data = keyInfoFactory.newX509Data(Collections.singletonList(certificate));
KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(data));
Element w3cElement = document.getDocumentElement();
Node xmlSigInsertionPoint = getXmlSignatureInsertionLocation(w3cElement);
DOMSignContext dsc = new DOMSignContext(privateKey, w3cElement, xmlSigInsertionPoint);
XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
signature.sign(dsc);
return w3cElement;
}
示例10: assinarDocumento
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
public String assinarDocumento(final String conteudoXml, final String... elementosAssinaveis) throws Exception {
final String certificateAlias = config.getCertificadoAlias() != null ? config.getCertificadoAlias() : config.getCertificadoKeyStore().aliases().nextElement();
final KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray());
final KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) config.getCertificadoKeyStore().getEntry(certificateAlias, passwordProtection);
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 : elementosAssinaveis) {
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);
}
}
示例11: signMessage
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
public String signMessage(String message, String signedElementId, boolean useEnvelopedTransform, String signatureParent, String signatureSibling)
throws ConfigurationException {
try {
// Create a DOM XMLSignatureFactory that will be used to
// generate the enveloped signature.
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
List<Transform> transforms = new LinkedList<>();
if (useEnvelopedTransform) {
transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
}
transforms.add(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
(C14NMethodParameterSpec) null));
Reference ref = fac.newReference(signedElementId, fac.newDigestMethod(DigestMethod.SHA1, null),
transforms, null, null);
// Create the SignedInfo.
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
(C14NMethodParameterSpec) null),
fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
Collections.singletonList(ref));
KeyStore.PrivateKeyEntry keyEntry
= (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyAlias, new KeyStore.PasswordProtection(password));
X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List x509Content = new ArrayList(2);
x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Instantiate the document to be signed.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(message.getBytes()));
// set explicitly all Id attributes
setAllIdAttributesInDocument(doc, "Id");
setAllIdAttributesInDocument(doc, "ID");
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
dsc.setDefaultNamespacePrefix(signatureNamespacePrefix);
List<? extends Node> nl1 = DomUtilities.evaluateXPath(doc, "//*[local-name()=\"" + signatureParent + "\"]");
List<? extends Node> nl2 = DomUtilities.evaluateXPath(doc, "//*[local-name()=\"" + signatureSibling + "\"]");
System.out.println(nl1.get(0));
dsc.setParent(nl1.get(0));
dsc.setNextSibling(nl2.get(0));
// Create the XMLSignature, but don't sign it yet.
XMLSignature signature = fac.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
String result = DomUtilities.domToString(doc);
return result;
} catch (IOException | InvalidAlgorithmParameterException | KeyStoreException |
MarshalException | NoSuchAlgorithmException | ParserConfigurationException |
SAXException | UnrecoverableEntryException | XMLSignatureException |
XPathExpressionException e) {
throw new ConfigurationException(e);
}
}
示例12: sign
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
private static Document sign(Document doc) throws NoSuchAlgorithmException,
InvalidAlgorithmParameterException, KeyStoreException,
CertificateException, FileNotFoundException, IOException,
UnrecoverableEntryException, javax.xml.crypto.MarshalException,
XMLSignatureException, TransformerException {
// Create a DOM XMLSignatureFactory that will be used to
// generate the enveloped signature.
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
// Create a Reference to the enveloped document (in this case,
// you are signing the whole document, so a URI of "" signifies
// that, and also specify the SHA1 digest algorithm and
// the ENVELOPED Transform.
Transform transform = fac.newTransform(Transform.ENVELOPED,
(TransformParameterSpec) null);
DigestMethod digestMethod = fac
.newDigestMethod(DigestMethod.SHA1, null);
Reference ref = fac.newReference("", digestMethod,
Collections.singletonList(transform), null, null);
// Create the SignedInfo.
CanonicalizationMethod canonicalizationMethod = fac
.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
(C14NMethodParameterSpec) null);
SignatureMethod signatureMethod = fac.newSignatureMethod(
SignatureMethod.RSA_SHA1, null);
SignedInfo si = fac.newSignedInfo(canonicalizationMethod,
signatureMethod, Collections.singletonList(ref));
// Load the KeyStore and get the signing key and certificate.
String password = "123456";
String keyAlias = "1";
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream("UDIR.PAS2.keystore"),password.toCharArray());
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks
.getEntry(keyAlias,
new KeyStore.PasswordProtection(password.toCharArray()));
X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List x509Content = new ArrayList();
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(),
doc.getDocumentElement());
// Create the XMLSignature, but don't sign it yet.
XMLSignature signature = fac.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
// Output the resulting document.
OutputStream os = new FileOutputStream("xmlOut.xml");
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(os));
return doc;
}
示例13: applyXMLDSig
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
/**
* Apply an XMLDSig onto the passed document.
*
* @param aPrivateKey
* The private key used for signing. May not be <code>null</code>.
* @param aCertificate
* The certificate to be used. May not be <code>null</code>.
* @param aDocument
* The document to be signed. The signature will always be the first
* child element of the document element. The document may not contains
* any disg:Signature element. This element is inserted manually.
* @throws Exception
* In case something goes wrong
*/
public void applyXMLDSig (@Nonnull final PrivateKey aPrivateKey,
@Nonnull final X509Certificate aCertificate,
@Nonnull final Document aDocument) throws Exception
{
ValueEnforcer.notNull (aPrivateKey, "privateKey");
ValueEnforcer.notNull (aCertificate, "certificate");
ValueEnforcer.notNull (aDocument, "document");
ValueEnforcer.notNull (aDocument.getDocumentElement (), "Document is missing a document element");
if (aDocument.getDocumentElement ().getChildNodes ().getLength () == 0)
throw new IllegalArgumentException ("Document element has no children!");
// Check that the document does not contain another Signature element
final NodeList aNodeList = aDocument.getElementsByTagNameNS (XMLSignature.XMLNS, XMLDSigSetup.ELEMENT_SIGNATURE);
if (aNodeList.getLength () > 0)
throw new IllegalArgumentException ("Document already contains an XMLDSig Signature element!");
// Create a DOM XMLSignatureFactory that will be used to generate the
// enveloped signature.
final XMLSignatureFactory aSignatureFactory = XMLDSigSetup.getXMLSignatureFactory ();
// Create a Reference to the enveloped document (we are signing the whole
// document, so a URI of "" signifies that, and also specify the SHA1 digest
// algorithm and the ENVELOPED Transform)
final Reference aReference = aSignatureFactory.newReference ("",
createDigestMethod (aSignatureFactory),
createTransformList (aSignatureFactory),
null,
null);
// Create the SignedInfo.
final SignedInfo aSignedInfo = aSignatureFactory.newSignedInfo (createCanonicalizationMethod (aSignatureFactory),
createSignatureMethod (aSignatureFactory),
CollectionHelper.makeUnmodifiable (aReference));
// Create the KeyInfo containing the X509Data.
final KeyInfoFactory aKeyInfoFactory = aSignatureFactory.getKeyInfoFactory ();
// The X509 certificate
final ICommonsList <Object> aX509Content = new CommonsArrayList <> (aCertificate.getSubjectX500Principal ()
.getName (),
aCertificate);
final X509Data aX509Data = aKeyInfoFactory.newX509Data (aX509Content);
// The public key itself
final KeyValue aKeyValue = aKeyInfoFactory.newKeyValue (aCertificate.getPublicKey ());
// Collect certificate and key value in key info
final KeyInfo aKeyInfo = aKeyInfoFactory.newKeyInfo (CollectionHelper.makeUnmodifiable (aX509Data, aKeyValue));
// Create the XMLSignature, but don't sign it yet.
final XMLSignature aXMLSignature = aSignatureFactory.newXMLSignature (aSignedInfo, aKeyInfo);
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
// -> The signature is always the first child element of the document
// element for ebInterface
final DOMSignContext aDOMSignContext = new DOMSignContext (aPrivateKey,
aDocument.getDocumentElement (),
aDocument.getDocumentElement ().getFirstChild ());
// The namespace prefix to be used for the signed XML
aDOMSignContext.setDefaultNamespacePrefix ("dsig");
// Marshal, generate, and sign the enveloped signature.
aXMLSignature.sign (aDOMSignContext);
}
示例14: signElementByTag
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //导入方法依赖的package包/类
public void signElementByTag(SOAPMessage soapMessage, String tag) throws Exception {
SOAPUtility.refreshSoap(soapMessage);
//Формируем новый документ из части сообщения
NodeList tagNodeList = soapMessage.getSOAPPart().getElementsByTagName(tag);
Document newXMLDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Node copyNode = newXMLDocument.importNode(tagNodeList.item(0), true);
newXMLDocument.appendChild(copyNode);
//Подписываемый элемент
NodeList newNodeList = newXMLDocument.getElementsByTagName(tag);
Element signedNode = (Element) newNodeList.item(0);
Provider xmlDSigProvider = new ru.CryptoPro.JCPxml.dsig.internal.dom.XMLDSigRI();
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", xmlDSigProvider);
List<Transform> transformList = new ArrayList<Transform>();
Transform transform = fac.newTransform(Transform.ENVELOPED, (XMLStructure) null);
Transform transformC14N = fac.newTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, (XMLStructure) null);
transformList.add(transform);
transformList.add(transformC14N);
Reference ref = fac.newReference("", fac.newDigestMethod("http://www.w3.org/2001/04/xmldsig-more#gostr3411", null), transformList, null, null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
(C14NMethodParameterSpec) null),
fac.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411", null),
Collections.singletonList(ref));
KeyInfoFactory kif = fac.getKeyInfoFactory();
X509Data x509d = kif.newX509Data(Collections.singletonList(cert));
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(x509d));
javax.xml.crypto.dsig.XMLSignature sig = fac.newXMLSignature(si, ki);
DOMSignContext signContext = new DOMSignContext(privateKey, signedNode);
signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");
sig.sign(signContext);
//Заменяем исходный элемент на подписанный
Document doc = soapMessage.getSOAPPart().getEnvelope().getOwnerDocument();
Node signedTag = newXMLDocument.getFirstChild();
Node oldNode = tagNodeList.item(0);
Node parentNode = oldNode.getParentNode();
parentNode.removeChild(oldNode);
Node newNode = doc.importNode(signedTag, true);
parentNode.appendChild(newNode);
}