1 | /******************************************************************************
|
---|
2 | *
|
---|
3 | * Copyright (C) 1998 Logi Ragnarsson
|
---|
4 | *
|
---|
5 | * Adapted 1999 for use in MindTerm by Mats Andersson ([email protected])
|
---|
6 | * This class is the Spinner class of the Cryptonite library found at:
|
---|
7 | * <http://www.hi.is/~logir/cryptonite/>
|
---|
8 | *
|
---|
9 | * This program is free software; you can redistribute it and/or modify
|
---|
10 | * it under the terms of the GNU General Public License as published by
|
---|
11 | * the Free Software Foundation; either version 2 of the License, or
|
---|
12 | * (at your option) any later version.
|
---|
13 | *
|
---|
14 | * This program is distributed in the hope that it will be useful,
|
---|
15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
17 | * GNU General Public License for more details.
|
---|
18 | *
|
---|
19 | *****************************************************************************
|
---|
20 | * $Author: mats $
|
---|
21 | * $Date: 1999/07/19 17:13:50 $
|
---|
22 | * $Name: rel1-2-1 $
|
---|
23 | *****************************************************************************/
|
---|
24 | package mindbright.security;
|
---|
25 |
|
---|
26 | /** Helper class for the RandomSpinner (SecureRandom) class. */
|
---|
27 | public class Spinner extends Thread {
|
---|
28 |
|
---|
29 | /** Return the number of spins performed in t milliseconds. */
|
---|
30 | public static int spin(long t) {
|
---|
31 | int counter = 0;
|
---|
32 | Thread s = new Spinner(t);
|
---|
33 | s.start();
|
---|
34 | do {
|
---|
35 | ++counter;
|
---|
36 | Thread.yield();
|
---|
37 | } while (s.isAlive());
|
---|
38 | return counter;
|
---|
39 | }
|
---|
40 |
|
---|
41 | /* This one is completely bogus, but after the initial seeding we trust the
|
---|
42 | milliseconds to be "random-enough"...
|
---|
43 | */
|
---|
44 | public static int bogusSpin() {
|
---|
45 | Runtime rt = Runtime.getRuntime();
|
---|
46 | int bogus;
|
---|
47 | Thread.yield();
|
---|
48 | rt.gc();
|
---|
49 | bogus = (int)System.currentTimeMillis();
|
---|
50 | bogus = ((bogus & 0xff) + ((bogus & 0xff00) >>> 8)) & 0xff;
|
---|
51 | return bogus;
|
---|
52 | }
|
---|
53 |
|
---|
54 | private long t;
|
---|
55 |
|
---|
56 | private Spinner(long t) {
|
---|
57 | this.t=t;
|
---|
58 | }
|
---|
59 |
|
---|
60 | public void run() {
|
---|
61 | try {
|
---|
62 | Thread.sleep(t);
|
---|
63 | } catch (InterruptedException ex) {
|
---|
64 | }
|
---|
65 | }
|
---|
66 |
|
---|
67 | /**
|
---|
68 | * Returns t such that spin(t) is larger than n. This value may change as
|
---|
69 | * the load of the system changes.
|
---|
70 | */
|
---|
71 | public static int guessTime(int n) {
|
---|
72 | int t=5;
|
---|
73 | while(spin(t)<n)
|
---|
74 | t=(t*3)/2;
|
---|
75 | return t;
|
---|
76 | }
|
---|
77 |
|
---|
78 | }
|
---|