3

For testing purpose I need to use SecureRandom with a custom algorithm. How is it possible?

I think I have to subclass SecureRandom and provide a SecureRandomSpi custom implementation:

 167:   /**
 168:      A constructor for SecureRandom. It constructs a new 
 169:      SecureRandom using the specified SecureRandomSpi from
 170:      the specified security provier. 
 171: 
 172:      @param secureRandomSpi A SecureRandomSpi class
 173:      @param provider A Provider class
 174:    */
 175:   protected SecureRandom(SecureRandomSpi secureRandomSpi, Provider provider)
 176:   {
 177:     this(secureRandomSpi, provider, "unknown");
 178:   }

Is there a simple way or can anyone provide ad example?

Alvins
  • 867
  • 16
  • 27

1 Answers1

0

The constructor

protected SecureRandom(SecureRandomSpi secureRandomSpi, Provider provider) 

is protected, you shouldn't use it. Use instead

public static SecureRandom getInstance(String algorithm)

If you have defined your own algorithm you must Create a Provider and register it so when you specify the name of the algorithm, the jre can find it. But you probably want to use a existig one.

However, if you have created your own crypto algorithm just use it instead of encapsulate into SecureRandom API. If its good enought sure some Provider will pay to you to add it to its API ;D

  • Can you write a simple example? – Alvins Jul 12 '16 at 15:24
  • About using a existing alg? For example SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.nextInt() will return a random integer from the 2^32 different values. More info here: http://stackoverflow.com/questions/27622625/securerandom-with-nativeprng-vs-sha1prng. About register your own Provider I'm afraid there isn't such thing as a simple example. But look here: http://stackoverflow.com/questions/10060261/how-do-i-get-java-to-use-my-security-provider – Marco A. Hernandez Jul 12 '16 at 15:46
  • About providing a custom alg. A simple one that return ++seed – Alvins Jul 12 '16 at 16:05
  • What do you mean with "one that return ++seed"? You can use SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); byte[] seed = sr.generateSeed(5); to obtain a 5 bytes seed computed using the SHA1PRNG seed generation algorithm . Do you need something like that? – Marco A. Hernandez Jul 12 '16 at 16:21
  • I need to implement a custom algorithm. `SecureRandom sr = SecureRandom.getInstance("myCustomAlg");` For example myCustomAlg can simply return ++seed each `nextInt()` – Alvins Jul 13 '16 at 08:14
  • 2
    Then you must create a security Provider, sign it and register it. As I said it's a complex process and there is no simple examples. You must follow the instructions from Oracle Docs. The point is, why do you want to use the SecureRandom API? This is an API designed to use well known cipher implementations. For testing purposes it will be simpler call to your own class. Something like MyCustomAlg.getRandomValue(seed); – Marco A. Hernandez Jul 13 '16 at 09:01