/**
   * Generate a new random password
   *
   * @return a new random password
   */
  private String generateRandomPassword(
      String[] rnd0, String[] rnd1, String[] rnd2, String[] rnd3, String[] rnd4) {
    StringBuilder ret = new StringBuilder();

    // Get lists of random words. We could cache these, but this method is
    // rarely called and caching would
    // depend on user locale, so we prefer to waste CPU better than memory.

    // Get a true random number generator
    SecureRandom rnd;
    try {
      rnd = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException ex) {
      rnd = new SecureRandom();
    }

    // Generate random numbers
    int i0 = rnd.nextInt(rnd0.length);
    int i1 = rnd.nextInt(rnd1.length);
    int i2 = rnd.nextInt(rnd2.length);
    int i3 = rnd.nextInt(rnd3.length);
    int i4 = rnd.nextInt(rnd4.length);

    // Compose password
    ret.append(rnd0[i0]);
    ret.append(rnd1[i1]);
    ret.append(rnd2[i2]);
    ret.append(rnd3[i3]);
    ret.append(rnd4[i4]);

    return ret.toString();
  }
예제 #2
0
 public void putOutMessages() {
   synchronized (collectedMessages) {
     int sendable;
     int pool = collectedMessages.size();
     if (pool >= (MIN_POOL + MIN_SEND)) {
       sendable = pool - MIN_SEND;
       sendable = Math.min(sendable, Math.max(1, (int) Math.round((double) pool * SEND_RATE)));
     } else {
       sendable = 0;
     }
     if (sendable > 0) {
       if (isRequestPool) {
         for (int i = 0; i < sendable; i++) {
           int chosen = secureRandom.nextInt(collectedMessages.size());
           anonNode.putOutRequest((Request) collectedMessages.remove(chosen));
         }
       } else {
         for (int i = 0; i < sendable; i++) {
           int chosen = secureRandom.nextInt(collectedMessages.size());
           anonNode.putOutReply((Reply) collectedMessages.remove(chosen));
         }
       }
     }
   }
 }
예제 #3
0
 /**
  * Changes the internal state to a new, fully-random version that should have no relation to the
  * previous state. May be somewhat slow; you shouldn't need to call this often.
  */
 public void randomize() {
   byte[] bytes = sec.generateSeed(128);
   for (int i = sec.nextInt() & 127, c = 0; c < 128; c++, i = i + 1 & 127) {
     state[i & 15] |= bytes[c] << ((i >> 4) << 3);
   }
   choice = sec.nextInt(16);
 }
예제 #4
0
 /**
  * Builds a ChaosRNG with a cryptographically-random seed. Future random generation uses less
  * secure methods but should still make it extremely difficult to "divine" the future RNG results.
  */
 public ChaosRNG() {
   sec = new SecureRandom();
   byte[] bytes = new byte[128];
   sec.nextBytes(bytes);
   for (int i = sec.nextInt() & 127, c = 0; c < 128; c++, i = i + 1 & 127) {
     state[i & 15] |= bytes[c] << ((i >> 4) << 3);
   }
   choice = sec.nextInt(16);
 }
예제 #5
0
 protected static String randomWord(int lenght, SecureRandom random) {
   StringBuilder builder = new StringBuilder(lenght);
   for (int i = 0; i < lenght; ++i) {
     if (i % 2 == 0) {
       builder.append(consonants[random.nextInt(consonants.length)]);
     } else {
       builder.append(vowels[random.nextInt(vowels.length)]);
     }
   }
   return builder.toString();
 }
예제 #6
0
  public static int getRandomInteger() throws IdentityException {

    try {
      SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
      int number = prng.nextInt();
      while (number < 0) {
        number = prng.nextInt();
      }
      return number;
    } catch (NoSuchAlgorithmException e) {
      log.error("Error when generating a random number.", e);
      throw new IdentityException("Error when generating a random number.", e);
    }
  }
  /* goodG2B1() - use goodsource and badsink by changing first private_final_t to private_final_f */
  private void goodG2B1() throws Throwable {
    int data;
    /* INCIDENTAL: CWE 570 Statement is Always False */
    if (private_final_f) {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
      Logger log_bad = Logger.getLogger("local-logger");
      SecureRandom r = new SecureRandom();
      data = r.nextInt();
    } else {

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded number that won't cause underflow, overflow,
      divide by zero, or loss-of-precision issues */
      data = 2;
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_t) {
      /* POTENTIAL FLAW: Zero denominator will cause an issue.  An integer division will
      result in an exception. */
      IO.writeLine("bad: 100/" + String.valueOf(data) + " = " + (100 / data) + "\n");
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      /* FIX: test for a zero denominator */
      if (data != 0) {
        IO.writeLine("100/" + String.valueOf(data) + " = " + (100 / data) + "\n");
      } else {
        IO.writeLine("This would result in a divide by zero");
      }
    }
  }
  public void testSOEProof() {
    final StringBuilder sb = new StringBuilder();
    final SecureRandom random = new SecureRandom();
    sb.append("class SOE_test {\n BigInteger BIG = new BigInteger(\n");
    int i;
    for (i = 0; i < 100000; i++) {
      sb.append("  \"").append(Math.abs(random.nextInt())).append("\" +\n");
    }
    sb.append("  \"\");\n}");

    final PsiJavaFile file = (PsiJavaFile) createLightFile("SOE_test.java", sb.toString());
    long t = System.currentTimeMillis();
    final StubElement tree = NEW_BUILDER.buildStubTree(file);
    t = System.currentTimeMillis() - t;
    assertEquals(
        "PsiJavaFileStub []\n"
            + "  IMPORT_LIST:PsiImportListStub\n"
            + "  CLASS:PsiClassStub[name=SOE_test fqn=SOE_test]\n"
            + "    MODIFIER_LIST:PsiModifierListStub[mask=4096]\n"
            + "    TYPE_PARAMETER_LIST:PsiTypeParameterListStub\n"
            + "    EXTENDS_LIST:PsiRefListStub[EXTENDS_LIST:]\n"
            + "    IMPLEMENTS_LIST:PsiRefListStub[IMPLEMENTS_LIST:]\n"
            + "    FIELD:PsiFieldStub[BIG:BigInteger=;INITIALIZER_NOT_STORED;]\n"
            + "      MODIFIER_LIST:PsiModifierListStub[mask=4096]\n",
        DebugUtil.stubTreeToString(tree));
    System.out.println("SOE depth=" + i + ", time=" + t + "ms");
  }
예제 #9
0
  /**
   * A 32 byte GUID generator (Globally Unique ID). These artificial keys SHOULD <strong>NOT
   * </strong> be seen by the user, not even touched by the DBA but with very rare exceptions, just
   * manipulated by the database and the programs.
   *
   * <p>Usage: Add an id field (type java.lang.String) to your EJB, and add
   * setId(XXXUtil.generateGUID(this)); to the ejbCreate method.
   */
  public static final String generateGUID(Object o) {
    StringBuffer tmpBuffer = new StringBuffer(16);
    if (hexServerIP == null) {
      java.net.InetAddress localInetAddress = null;
      try {
        // get the inet address

        localInetAddress = java.net.InetAddress.getLocalHost();
      } catch (java.net.UnknownHostException uhe) {
        System.err.println(
            "MembreUtil: Could not get the local IP address using InetAddress.getLocalHost()!");
        // todo: find better way to get around this...
        uhe.printStackTrace();
        return null;
      }
      byte serverIP[] = localInetAddress.getAddress();
      hexServerIP = hexFormat(getInt(serverIP), 8);
    }

    String hashcode = hexFormat(System.identityHashCode(o), 8);
    tmpBuffer.append(hexServerIP);
    tmpBuffer.append(hashcode);

    long timeNow = System.currentTimeMillis();
    int timeLow = (int) timeNow & 0xFFFFFFFF;
    int node = seeder.nextInt();

    StringBuffer guid = new StringBuffer(32);
    guid.append(hexFormat(timeLow, 8));
    guid.append(tmpBuffer.toString());
    guid.append(hexFormat(node, 8));
    return guid.toString();
  }
예제 #10
0
  public static String generateOTP(int otpLengthNumber) {
    String otp = new String();
    int otpSample = 0;
    for (int i = 0; i < otpLengthNumber; i++) {
      otp = otp + "9";
    }

    otpSample = Integer.parseInt(otp);

    SecureRandom prng;
    try {
      prng = SecureRandom.getInstance("SHA1PRNG"); // Number Generation Algorithm
      otp = new Integer(prng.nextInt(otpSample)).toString();
      otp = (otp.length() < otpLengthNumber) ? padleft(otp, otpLengthNumber, '0') : otp;
    } catch (NoSuchAlgorithmException e) {
    }

    //        If generated OTP exists in DB -regenerate OTP again
    boolean otpExists = false;
    if (otpExists) {
      generateOTP(otpLengthNumber);
    } else {
      return otp;
    }
    return otp;
  }
예제 #11
0
  private void rawModeTest(
      String sigName,
      ASN1ObjectIdentifier digestOID,
      PrivateKey privKey,
      PublicKey pubKey,
      SecureRandom random)
      throws Exception {
    byte[] sampleMessage = new byte[1000 + random.nextInt(100)];
    random.nextBytes(sampleMessage);

    Signature normalSig = Signature.getInstance(sigName, "BC");
    normalSig.initSign(privKey);
    normalSig.update(sampleMessage);
    byte[] normalResult = normalSig.sign();

    MessageDigest digest = MessageDigest.getInstance(digestOID.getId(), "BC");
    byte[] hash = digest.digest(sampleMessage);
    byte[] digInfo = derEncode(digestOID, hash);

    Signature rawSig = Signature.getInstance("RSA", "BC");
    rawSig.initSign(privKey);
    rawSig.update(digInfo);
    byte[] rawResult = rawSig.sign();

    if (!Arrays.areEqual(normalResult, rawResult)) {
      fail("raw mode signature differs from normal one");
    }

    rawSig.initVerify(pubKey);
    rawSig.update(digInfo);

    if (!rawSig.verify(rawResult)) {
      fail("raw mode signature verification failed");
    }
  }
예제 #12
0
  /**
   * 문자열 A에서 Z사이의 랜덤 문자열을 구하는 기능을 제공 시작문자열과 종료문자열 사이의 랜덤 문자열을 구하는 기능
   *
   * @param startChr - 첫 문자
   * @param endChr - 마지막문자
   * @return 랜덤문자
   * @exception MyException
   * @see
   */
  public static String getRandomStr(char startChr, char endChr) {

    int randomInt;
    String randomStr = null;

    // 시작문자 및 종료문자를 아스키숫자로 변환한다.
    int startInt = Integer.valueOf(startChr);
    int endInt = Integer.valueOf(endChr);

    // 시작문자열이 종료문자열보가 클경우
    if (startInt > endInt) {
      throw new IllegalArgumentException("Start String: " + startChr + " End String: " + endChr);
    }

    try {
      // 랜덤 객체 생성
      SecureRandom rnd = new SecureRandom();

      do {
        // 시작문자 및 종료문자 중에서 랜덤 숫자를 발생시킨다.
        randomInt = rnd.nextInt(endInt + 1);
      } while (randomInt < startInt); // 입력받은 문자 'A'(65)보다 작으면 다시 랜덤 숫자 발생.

      // 랜덤 숫자를 문자로 변환 후 스트링으로 다시 변환
      randomStr = (char) randomInt + "";
    } catch (Exception e) {
      e.printStackTrace();
    }

    // 랜덤문자열를 리턴
    return randomStr;
  }
예제 #13
0
  /**
   * Generate a sequence of secure random positive integers which is guaranteed not to repeat in the
   * last 100 calls to this function.
   *
   * @return a random positive integer
   */
  public static int getPositiveNonRepeatingRandomInteger() {

    // initialize on first call
    if (sr == null) {
      sr = new SecureRandom();
      lastRandomsSeen = new int[RANDOM_HISTORY_SIZE];

      for (int x = 0; x < lastRandomsSeen.length; x++) lastRandomsSeen[x] = -1;
    }

    int toReturn;
    do {
      // pick a number
      toReturn = sr.nextInt(Integer.MAX_VALUE);

      // check we havn't see it recently
      for (int seen : lastRandomsSeen) {
        if (seen == toReturn) {
          toReturn = -1;
          break;
        }
      }
    } while (toReturn == -1);

    // update history
    lastRandomsSeen[randomInsertPointer] = toReturn;
    randomInsertPointer = (randomInsertPointer + 1) % lastRandomsSeen.length;

    return toReturn;
  }
예제 #14
0
  public void resetQuiz() {
    AssetManager assets = getActivity().getAssets();
    fileNameList.clear();

    try {
      String[] paths = assets.list("Flag");

      for (String path : paths) {
        fileNameList.add(path.replace(".png", ""));
      }
    } catch (IOException e) {
      Log.e(TAG, "Error", e);
    }

    questionNumber = 0;
    totalGuesses = 0;
    flagflagList.clear();

    int flagCounter = 1;
    int numberOfflags = fileNameList.size();

    while (flagCounter <= NUMBER_OF_QUESTIONS) {
      int randomIndex = random.nextInt(numberOfflags);

      String fileName = fileNameList.get(randomIndex);

      if (!flagflagList.contains(fileName)) {
        flagflagList.add(fileName);
        ++flagCounter;
      }
    }
    //        scoreTimer.scheduleAtFixedRate(scoreTask, 0, 800);

    loadNextFlag();
  }
예제 #15
0
  protected int chooseExtraPadBlocks(SecureRandom r, int max) {
    //        return r.nextInt(max + 1);

    int x = r.nextInt();
    int n = lowestBitSet(x);
    return Math.min(n, max);
  }
예제 #16
0
  private void randomTest(SecureRandom srng) throws InvalidCipherTextException {
    int DAT_LEN = srng.nextInt() >>> 22; // Note: JDK1.0 compatibility
    byte[] nonce = new byte[NONCE_LEN];
    byte[] authen = new byte[AUTHEN_LEN];
    byte[] datIn = new byte[DAT_LEN];
    byte[] key = new byte[16];
    srng.nextBytes(nonce);
    srng.nextBytes(authen);
    srng.nextBytes(datIn);
    srng.nextBytes(key);

    AESFastEngine engine = new AESFastEngine();
    KeyParameter sessKey = new KeyParameter(key);
    EAXBlockCipher eaxCipher = new EAXBlockCipher(engine);

    AEADParameters params = new AEADParameters(sessKey, MAC_LEN * 8, nonce, authen);
    eaxCipher.init(true, params);

    byte[] intrDat = new byte[eaxCipher.getOutputSize(datIn.length)];
    int outOff = eaxCipher.processBytes(datIn, 0, DAT_LEN, intrDat, 0);
    outOff += eaxCipher.doFinal(intrDat, outOff);

    eaxCipher.init(false, params);
    byte[] datOut = new byte[eaxCipher.getOutputSize(outOff)];
    int resultLen = eaxCipher.processBytes(intrDat, 0, outOff, datOut, 0);
    eaxCipher.doFinal(datOut, resultLen);

    if (!areEqual(datIn, datOut)) {
      fail("EAX roundtrip failed to match");
    }
  }
예제 #17
0
 public static String createId() {
   char[] id = new char[len];
   SecureRandom r = new SecureRandom();
   for (int i = 0; i < len; i++) {
     id[i] = idchars[r.nextInt(idchars.length)];
   }
   return new String(id);
 }
예제 #18
0
 public static char[] generateRandomPassword(int len, boolean allCaps) {
   char[] charSet = allCaps ? symbolsAllCaps : symbols;
   char[] pw = new char[len];
   for (int i = 0; i < len; i++) {
     pw[i] = charSet[rng.nextInt(charSet.length)];
   }
   return pw;
 }
예제 #19
0
 /**
  * 产生任意给定长度的随纯机数字字符串。
  *
  * @param iLength 产生随机数的位数
  * @return 给定位数的随机数
  */
 public static String getRandomIntNum(int iLength) {
   sr.setSeed(System.currentTimeMillis());
   StringBuffer sb = new StringBuffer();
   for (int i = 0; i < iLength; i++) {
     sb.append(Math.abs(sr.nextInt(10)));
   }
   return sb.toString();
 }
  public static String chooseImage() {
    /* chooses either image or text as it medium for passing a and b */

    SecureRandom r = new SecureRandom();
    int pos = r.nextInt(6) + 1;

    return Integer.toString(pos);
  }
예제 #21
0
 private char[] getRandomChars(int length) {
   SecureRandom rand = new SecureRandom();
   char[] chars = new char[length];
   for (int i = 0; i < length; i++) {
     chars[i] = (char) rand.nextInt();
   }
   return chars;
 }
예제 #22
0
 /**
  * generate a new oid. called only internally by getOid()
  *
  * @return oid
  */
 private String generateOid(final long pTimeNow) {
   // get time as unsigned int
   int timeLow = (int) pTimeNow & -1;
   // get next random number
   int random = _seeder.nextInt();
   // instantiate new oid with universally unique identifier
   return hexFormat(timeLow, BLOCK_LENGTH) + _middleString + hexFormat(random, BLOCK_LENGTH);
 }
예제 #23
0
  private Tetromino createRandomTetromino() {
    Tetromino result = null;

    SecureRandom random = new SecureRandom();

    random.setSeed(UUID.randomUUID().hashCode());

    int type = random.nextInt(NUMBER_OF_TETROMINO_TYPE);
    switch (type) {
      case TETROMINO_L:
        result = new LTetromino();
        break;
      case TETROMINO_J:
        result = new JTetromino();
        break;
      case TETROMINO_S:
        result = new STetromino();
        break;
      case TETROMINO_Z:
        result = new ZTetromino();
        break;
      case TETROMINO_T:
        result = new TTetromino();
        break;
      case TETROMINO_O:
        result = new OTetromino();
        break;
      case TETROMINO_I:
        result = new ITetromino();
        break;
    }

    int color = random.nextInt(Tetromino.NUMBER_OF_COLOR) + 1;
    result.setColor(color);
    result.setX(0);
    result.setY(0);

    int col = result.getFirstBlockColIndex();
    int row = result.getFirstBlockRowIndex();

    result.setX(4 - col);
    result.setY(0 - row);

    return result;
  }
예제 #24
0
 private static String generateSalt(final int length) {
   final SecureRandom random = new SecureRandom();
   final StringBuilder sb = new StringBuilder(length);
   for (int i = 0; i < length; i++) {
     sb.append(
         ChaiResponseSet.SALT_CHARS.charAt(random.nextInt(ChaiResponseSet.SALT_CHARS.length())));
   }
   return sb.toString();
 }
 private static String generateKey() {
   StringBuilder sb = new StringBuilder();
   char[] chars = COMPONENT_CHARS.toCharArray();
   SecureRandom r = new SecureRandom();
   for (int i = 0; i < 20; i++) {
     sb.append(chars[r.nextInt(chars.length - 1)]);
   }
   return sb.toString();
 }
예제 #26
0
  private String generateTokenData(String id) {
    String chars = "" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "";

    final int PW_LENGTH = 16;
    StringBuilder pass = new StringBuilder();
    for (int i = 0; i < PW_LENGTH; i++) pass.append(chars.charAt(random.nextInt(chars.length())));
    String token = pass.toString() + "_" + id;
    return token;
  }
  /* goodB2G() - use badsource and goodsink */
  private void goodB2G() throws Throwable {
    int data;

    Logger log_bad = Logger.getLogger("local-logger");

    SecureRandom r = new SecureRandom();
    data = r.nextInt();

    (new CWE190_Integer_Overflow__random_add_51b()).goodB2G_sink(data);
  }
예제 #28
0
 @VisibleForTesting
 protected VerificationCode generateVerificationCode() {
   try {
     SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
     int randomInt = 100000 + random.nextInt(900000);
     return new VerificationCode(randomInt);
   } catch (NoSuchAlgorithmException e) {
     throw new AssertionError(e);
   }
 }
 /**
  * Generates random salt.
  */
 private String generateSalt() {
     StringBuilder buf = new StringBuilder();
     SecureRandom sr = new SecureRandom();
     for( int i=0; i<6; i++ ) {// log2(52^6)=34.20... so, this is about 32bit strong.
         boolean upper = sr.nextBoolean();
         char ch = (char)(sr.nextInt(26) + 'a');
         if(upper)   ch=Character.toUpperCase(ch);
         buf.append(ch);
     }
     return buf.toString();
 }
예제 #30
0
  /**
   * Creates a new Bloom filter with given number of hash functions and expected number of elements.
   *
   * @param n the expected number of elements.
   * @param d the number of hash functions; under obvious uniformity and indipendence assumptions,
   *     if the filter has not more than <code>n</code> elements, false positives will happen with
   *     probability 2<sup>-<var>d</var></sup>.
   * @param seed an array of bytes that will be used as a seed by {@link
   *     SecureRandom#SecureRandom(byte[])}.
   */
  public BloomFilter(final long n, final int d, final byte[] seed) {
    this.d = d;
    final long wantedNumberOfBits = (long) Math.ceil(n * (d / NATURAL_LOG_OF_2));
    if (wantedNumberOfBits > MAX_BITS)
      throw new IllegalArgumentException(
          "The wanted number of bits (" + wantedNumberOfBits + ") is larger than " + MAX_BITS);
    bits = new long[(int) ((wantedNumberOfBits + Long.SIZE - 1) / Long.SIZE)];
    m = bits.length * (long) Long.SIZE;

    if (DEBUG) System.err.println("Number of bits: " + m);

    final SecureRandom random = new SecureRandom(seed);
    weight = new int[d][];
    init = new int[d];
    for (int i = 0; i < d; i++) {
      weight[i] = new int[NUMBER_OF_WEIGHTS];
      init[i] = random.nextInt();
      for (int j = 0; j < NUMBER_OF_WEIGHTS; j++) weight[i][j] = random.nextInt();
    }
  }