Sie sind auf Seite 1von 2

import import import import import import import import import import import import import

java.io.*; java.security.Key; java.security.KeyStore; java.security.cert.X509Certificate; javax.xml.parsers.DocumentBuilderFactory; org.apache.commons.io.IOUtils; org.apache.xml.security.Init; org.apache.xml.security.c14n.Canonicalizer; org.apache.xml.security.signature.XMLSignature; org.apache.xml.security.transforms.Transforms; org.apache.xml.security.utils.Constants; org.apache.xml.security.utils.ElementProxy; org.w3c.dom.Document;

public class CreateSignatureCompressed { private private private private static static static static final final final final String String String String PRIVATE_KEY_ALIAS = "test-alias"; PRIVATE_KEY_PASS = "test"; KEY_STORE_PASS = "test"; KEY_STORE_TYPE = "JKS";

public static void main(String... unused) throws Exception { final InputStream fileInputStream = new FileInputStream("test.xml"); try { output(signFile(fileInputStream, new File("keystore.jks")), "signedtest.xml"); } finally { IOUtils.closeQuietly(fileInputStream); } } public static ByteArrayOutputStream signFile(InputStream xmlFile, File priva teKeyFile) throws Exception { final Document doc = DocumentBuilderFactory.newInstance().newDocumentBui lder().parse(xmlFile); Init.init(); ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, ""); final KeyStore keyStore = loadKeyStore(privateKeyFile); final XMLSignature sig = new XMLSignature(doc, null, XMLSignature.ALGO_I D_SIGNATURE_RSA); final Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); final Key privateKey = keyStore.getKey(PRIVATE_KEY_ALIAS, PRIVATE_KEY_PA SS.toCharArray()); final X509Certificate cert = (X509Certificate)keyStore.getCertificate(PR IVATE_KEY_ALIAS); sig.addKeyInfo(cert); sig.addKeyInfo(cert.getPublicKey()); sig.sign(privateKey); doc.getDocumentElement().appendChild(sig.getElement()); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_ WITH_COMMENTS).canonicalizeSubtree(doc)); return outputStream; } private static KeyStore loadKeyStore(File privateKeyFile) throws Exception {

final InputStream fileInputStream = new FileInputStream(privateKeyFile); try { final KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE); keyStore.load(fileInputStream, KEY_STORE_PASS.toCharArray()); return keyStore; } finally { IOUtils.closeQuietly(fileInputStream); } } private static void output(ByteArrayOutputStream signedOutputStream, String fileName) throws IOException { final OutputStream fileOutputStream = new FileOutputStream(fileName); try { fileOutputStream.write(signedOutputStream.toByteArray()); fileOutputStream.flush(); } finally { IOUtils.closeQuietly(fileOutputStream); } } }