Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.security.*;
- /**
- * SecureSFMT provides byte SFMT generate int value to hashing by SHA2.
- */
- public class SecureSFMT {
- /* 256bit div 8bit eq 32byte */
- final static int DIGEST_LENGTH = 32;
- MessageDigest digest;
- SFMT sfmt;
- byte[] buffer = new byte[DIGEST_LENGTH];
- int index = DIGEST_LENGTH;
- public SecureSFMT(int ... seed) {
- try {
- digest = MessageDigest.getInstance("SHA-256");
- } catch (NoSuchAlgorithmException e) {
- throw new RuntimeException(e);
- }
- sfmt = new SFMT(seed);
- }
- public byte nextByte() {
- if(index == DIGEST_LENGTH) {
- init();
- index = 0;
- }
- return buffer[index++];
- }
- void init() {
- for (int i = 0; i < DIGEST_LENGTH; ) {
- int v = sfmt.nextInt();
- buffer[i++] = (byte) v;
- buffer[i++] = (byte)(v >>> 8);
- buffer[i++] = (byte)(v >>> 16);
- buffer[i++] = (byte)(v >>> 24);
- }
- digest.update(buffer);
- try {
- digest.digest(buffer, 0, DIGEST_LENGTH);
- } catch (DigestException e) {
- throw new RuntimeException(e);
- }
- }
- public int nextInt(int count) {
- int mask = 0;
- int bitCount;
- for (bitCount = 0; count > (1 << bitCount); bitCount++) {
- mask |= (1 << bitCount);
- }
- int value;
- do {
- value = 0;
- for(int shift = 0; shift < bitCount; shift += 8) {
- int v = (nextByte() & 0xff) << shift;
- value |= (v & mask);
- }
- } while(value >= count);
- return value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement