Last updated
on 04-09-2012
at 12:00 AM


I’m currently writing all sorts of code for work with OpenSAML, we’re trying to do this in a nice test-driven manner, but it’s extremely difficult to generate X509 certificates at runtime, and surprisingly difficult to mock them sensibly for our unit (well, here really integration) tests that actual use any of the OpenSAML library.

In the end, for the component tests we’ve just gone for actually keeping a Java key store on disk, since actually faking completely usable certificates at runtime became entirely impractical, and there’s too much information actually required in the end-to-end case for us to easily stub all of it. It is technically doable, but the process is very involved, and we quickly decided that was not a route we wanted to head down.

In the unit tests meanwhile, this is fairly practical, since you can mock just enough for OpenSAML to understand it in the relevant context, and you don’t need enough to make it a fully valid certificate. As an example, we’re generating IdP metadata, which includes a KeyInfo element describing the OpenSAML credential that’ll be used, and it turns out you can sneak and mock the essentials like this:

byte[] certBytes = new byte[] { 1, 2, 3, 4, 5, 6 }; X509Certificate cert = mock(X509Certificate.class); when(cert.getEncoded()).thenReturn(certBytes); PublicKey pk = mock(PublicKey.class); when(cert.getPublicKey()).thenReturn(pk); X509Credential cred = SecurityHelper.getSimpleCredential(cert, null); X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory(); keyInfoGeneratorFactory.setEmitEntityCertificate(true); KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance(); KeyInfo keyInfo = keyInfoGenerator.generate(cred);

Surprisingly tricky working most of that out, but a bit of trial and error along with the seemingly undocumented SecurityHelper class, and it comes together in the end.