You are on page 1of 1

public static void main(String[] args) throws Exception {

// http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/
XMLDigitalSignature.html
//
byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\
n".getBytes();
// load the document that's going to be signed
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(inputXml));

// // create a key pair


// KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
// kpg.initialize(512);
// KeyPair kp = kpg.generateKeyPair();
PublicKey pub = getPublicKey("C:\\work\\fhirserver\\tests\\signatures\\
public_key.der");
PrivateKey priv = getPrivateKey("C:\\work\\fhirserver\\tests\\signatures\\
private_key.der");

// sign the document


DOMSignContext dsc = new DOMSignContext(priv, doc.getDocumentElement());
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1,


null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED,
(TransformParameterSpec) null)), null, null);
SignedInfo si =
fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1,
null), Collections.singletonList(ref));

KeyInfoFactory kif = fac.getKeyInfoFactory();


KeyValue kv = kif.newKeyValue(pub);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(dsc);

OutputStream os = new FileOutputStream("c:\\temp\\java-digsig.xml");


new XmlGenerator().generate(doc.getDocumentElement(), os);
}
}

You might also like