Changeset 380c1e5


Ignore:
Timestamp:
Mar 9, 2011 3:55:00 PM (9 years ago)
Author:
zzz <zzz@…>
Branches:
master
Children:
a1032ab
Parents:
21dbee0
Message:

efficiently use entropy in padding

File:
1 edited

Legend:

Unmodified
Added
Removed
  • router/java/src/net/i2p/router/tunnel/TrivialPreprocessor.java

    r21dbee0 r380c1e5  
    109109        //_log.debug("# pad bytes:  " + numPadBytes + " payloadLength: " + payloadLength + " instructions: " + instructionsLength);
    110110
    111         int paddingRemaining = numPadBytes;
    112         // FIXME inefficient, waste of 3/4 of the entropy
    113         // Should get a byte array of random, change all the zeros to something else, and ArrayCopy
    114         while (paddingRemaining > 0) {
    115             byte b = (byte)(_context.random().nextInt() & 0xFF);
    116             if (b != 0x00) {
    117                 fragments[offset] = b;
    118                 offset++;
    119                 paddingRemaining--;
    120             }
     111        if (numPadBytes > 0) {
     112            fillRandomNonZero(fragments, offset, numPadBytes);
     113            offset += numPadBytes;
    121114        }
    122115       
     
    125118        if (_log.shouldLog(Log.DEBUG))
    126119            _log.debug("Preprocessing beginning of the fragment instructions at " + offset);
     120    }
     121
     122    /**
     123     *  Efficiently fill with nonzero random data
     124     *  Don't waste too much entropy or call random() too often.
     125     *  @since 0.8.5
     126     */
     127    private void fillRandomNonZero(byte[] b, int off, int len) {
     128        // get about as much as we think we will need, overestimate some
     129        final int est = len + (len / 128) + 3;
     130        final byte[] tmp = new byte[est];
     131        _context.random().nextBytes(tmp);
     132        int extra = len;
     133        for (int i = 0; i < len; i++) {
     134            while (tmp[i] == 0) {
     135                if (extra < est)
     136                    tmp[i] = tmp[extra++];  // use from the extra we have at the end
     137                else
     138                    tmp[i] = (byte)(_context.random().nextInt() & 0xFF);  // waste 3/4 of the entropy
     139            }
     140        }
     141        System.arraycopy(tmp, 0, b, off, len);
    127142    }
    128143
Note: See TracChangeset for help on using the changeset viewer.