Advertisement
Guest User

Untitled

a guest
Apr 3rd, 2012
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. import java.security.*;
  2.  
  3. /**
  4.  * SecureSFMT provides byte SFMT generate int value to hashing by SHA2.
  5.  */
  6. public class SecureSFMT {
  7.  
  8.     /* 256bit div 8bit eq 32byte */
  9.     final static int DIGEST_LENGTH = 32;
  10.  
  11.     MessageDigest digest;
  12.  
  13.     SFMT sfmt;
  14.    
  15.     byte[] buffer = new byte[DIGEST_LENGTH];
  16.  
  17.     int index = DIGEST_LENGTH;
  18.    
  19.     public SecureSFMT(int ... seed) {
  20.         try {
  21.             digest = MessageDigest.getInstance("SHA-256");
  22.         } catch (NoSuchAlgorithmException e) {
  23.             throw new RuntimeException(e);
  24.         }
  25.         sfmt = new SFMT(seed);
  26.     }
  27.  
  28.     public byte nextByte() {
  29.         if(index == DIGEST_LENGTH) {
  30.             init();
  31.             index = 0;
  32.         }
  33.         return buffer[index++];
  34.     }
  35.  
  36.     void init() {
  37.         for (int i = 0; i < DIGEST_LENGTH; ) {
  38.             int v = sfmt.nextInt();
  39.             buffer[i++] = (byte) v;
  40.             buffer[i++] = (byte)(v >>> 8);
  41.             buffer[i++] = (byte)(v >>> 16);
  42.             buffer[i++] = (byte)(v >>> 24);
  43.         }
  44.         digest.update(buffer);
  45.         try {
  46.             digest.digest(buffer, 0, DIGEST_LENGTH);
  47.         } catch (DigestException e) {
  48.             throw new RuntimeException(e);
  49.         }
  50.     }
  51.  
  52.     public int nextInt(int count) {
  53.         int mask = 0;
  54.        
  55.         int bitCount;
  56.         for (bitCount = 0; count > (1 << bitCount); bitCount++) {
  57.             mask |= (1 << bitCount);
  58.         }
  59.        
  60.         int value;
  61.         do {
  62.             value = 0;
  63.             for(int shift = 0; shift < bitCount; shift += 8) {
  64.                 int v = (nextByte() & 0xff) << shift;
  65.                 value |= (v & mask);
  66.             }
  67.         } while(value >= count);
  68.        
  69.         return value;
  70.     }
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement