javapkcs#11secure-random

Java use SecureRandom with SunPKCS11 provider


I would like to use my PKCS#11 enabled device as a source of SecureRandom.

So I have done the following:

Provider pkcs11provider = new sun.security.pkcs11.SunPKCS11(pkcs11config);
Security.addProvider(pkcs11provider);

byte[] rb = new byte[100];
SecureRandom sr = SecureRandom.getInstance("PKCS11", pkcs11provider);
sr.nextBytes(rb);

And I always get an exception:

Exception in thread "main" java.security.NoSuchAlgorithmException: no such algorithm: PKCS11 for provider SunPKCS11-HSM
    at sun.security.jca.GetInstance.getService(GetInstance.java:101)
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:218)
    at java.security.SecureRandom.getInstance(SecureRandom.java:383)

What I am doing wrong? According JDK PKCS#11 Reference Guide "PKCS11" should be supported algorithm for SecureRandom.


Solution

  • "PKCS11" doesn't sound like an algorithm name. It is the provider name. A provider can have their own algorithm names for specific crypto operations. To see what all algorithms they have, you can run this code snippet to see them.

    Set<Provider.Service> services = pkcs11provider.getServices();
    
    services.forEach(service ->
    {
        // System.out.println(service.getType()); // --> Look for 'SecureRandom' type
        System.out.println(service.getAlgorithm());
    });
    

    Look for 'SecureRandom' type, and that's the algorithm you have to pass in as the first argument in SecureRandom.getInstance(.., ..).