01: package org.bouncycastle.crypto.generators;
02:
03: import org.bouncycastle.crypto.CipherParameters;
04: import org.bouncycastle.crypto.params.ParametersWithRandom;
05: import org.bouncycastle.crypto.params.RSAKeyParameters;
06: import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
07:
08: import java.math.BigInteger;
09: import java.security.SecureRandom;
10:
11: /**
12: * Generate a random factor suitable for use with RSA blind signatures
13: * as outlined in Chaum's blinding and unblinding as outlined in
14: * "Handbook of Applied Cryptography", page 475.
15: */
16: public class RSABlindingFactorGenerator {
17: private static BigInteger ZERO = BigInteger.valueOf(0);
18: private static BigInteger ONE = BigInteger.valueOf(1);
19:
20: private RSAKeyParameters key;
21: private SecureRandom random;
22:
23: /**
24: * Initialise the factor generator
25: *
26: * @param param the necessary RSA key parameters.
27: */
28: public void init(CipherParameters param) {
29: if (param instanceof ParametersWithRandom) {
30: ParametersWithRandom rParam = (ParametersWithRandom) param;
31:
32: key = (RSAKeyParameters) rParam.getParameters();
33: random = rParam.getRandom();
34: } else {
35: key = (RSAKeyParameters) param;
36: random = new SecureRandom();
37: }
38:
39: if (key instanceof RSAPrivateCrtKeyParameters) {
40: throw new IllegalArgumentException(
41: "generator requires RSA public key");
42: }
43: }
44:
45: /**
46: * Generate a suitable blind factor for the public key the generator was initialised with.
47: *
48: * @return a random blind factor
49: */
50: public BigInteger generateBlindingFactor() {
51: if (key == null) {
52: throw new IllegalStateException("generator not initialised");
53: }
54:
55: BigInteger m = key.getModulus();
56: int length = m.bitLength() - 1; // must be less than m.bitLength()
57: BigInteger factor;
58: BigInteger gcd;
59:
60: do {
61: factor = new BigInteger(length, random);
62: gcd = factor.gcd(m);
63: } while (factor.equals(ZERO) || factor.equals(ONE)
64: || !gcd.equals(ONE));
65:
66: return factor;
67: }
68: }
|