0% found this document useful (0 votes)
22 views

Java Code

This document summarizes code that digitally signs an XML document using XML digital signatures. It loads an XML document, gets a public and private key, creates a digital signature for the document using the private key, and outputs the signed XML document to a file.

Uploaded by

ashish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java Code

This document summarizes code that digitally signs an XML document using XML digital signatures. It loads an XML document, gets a public and private key, creates a digital signature for the document using the private key, and outputs the signed XML document to a file.

Uploaded by

ashish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 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