]> WPIA git - gigi.git/blob - src/club/wpia/gigi/crypto/key/KeyCheckSmallFactors.java
a0965344fc103674f2e561741a421a623220f785
[gigi.git] / src / club / wpia / gigi / crypto / key / KeyCheckSmallFactors.java
1 package club.wpia.gigi.crypto.key;
2
3 import java.math.BigInteger;
4 import java.security.PublicKey;
5 import java.security.interfaces.RSAPublicKey;
6 import java.util.ArrayList;
7
8 import club.wpia.gigi.GigiApiException;
9 import club.wpia.gigi.output.template.SprintfCommand;
10
11 public class KeyCheckSmallFactors extends KeyCheck {
12
13     private static final long MAX_CHECKED_SMALL_PRIME_BOUNDARY = 10000;
14
15     private static final BigInteger[] primes;
16
17     static {
18         ArrayList<BigInteger> prims = new ArrayList<>(1024);
19
20         NextPrime:
21         for (long i = 2; i < MAX_CHECKED_SMALL_PRIME_BOUNDARY; i++) {
22             for (BigInteger p : prims) {
23                 if (BigInteger.ZERO.equals(BigInteger.valueOf(i).mod(p))) {
24                     continue NextPrime;
25                 }
26             }
27
28             prims.add(BigInteger.valueOf(i));
29         }
30
31         primes = prims.toArray(new BigInteger[0]);
32
33         register(new KeyCheckSmallFactors());
34     }
35
36     @Override
37     public void check(PublicKey key) throws GigiApiException {
38         if ( !(key instanceof RSAPublicKey)) {
39             return;
40         }
41
42         BigInteger modulus = ((RSAPublicKey) key).getModulus();
43
44         // Check for small prime factors below 10000
45         for (BigInteger n : primes) {
46             if (BigInteger.ZERO.equals(modulus.mod(n))) {
47                 throw new GigiApiException(SprintfCommand.createSimple("Small factors check of public key: Key is divisible by {0}.", n.toString()));
48             }
49         }
50     }
51
52 }