/**
   * 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
  /**
   * 문자열 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;
  }
示例#3
0
 private SecureRandom getSecureRandom(String RNGAlgorithm, String RNGProvider) {
   try {
     SecureRandom r;
     if (RNGProvider != null) {
       r = SecureRandom.getInstance(RNGAlgorithm, RNGProvider);
     } else {
       r = SecureRandom.getInstance(RNGAlgorithm);
     }
     r.nextBytes(new byte[1]);
     return r;
   } catch (NoSuchProviderException e) {
     // Fallback to any provider for the algorithm
     return getSecureRandom(RNGAlgorithm, null);
   } catch (NoSuchAlgorithmException e) {
     if (RNGProvider != null) {
       return getSecureRandom(RNGAlgorithm, null);
     }
     Spout.getLogger()
         .severe(
             "Unable to find algorithm to generate random number generator for key pair creation ("
                 + RNGAlgorithm
                 + ", "
                 + RNGProvider
                 + ")");
     return null;
   }
 }
示例#4
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));
         }
       }
     }
   }
 }
示例#5
0
 static {
   // Generate 8 bytes of random data.
   SecureRandom secureRandom = new SecureRandom();
   byte bytes[] = new byte[8];
   secureRandom.nextBytes(bytes);
   randomBytes = bytes;
 }
示例#6
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");
    }
  }
示例#7
0
 /**
  * Generate a random int value uniformly distributed between <code>lower</code> and <code>upper
  * </code>, inclusive. This algorithm uses a secure random number generator.
  *
  * @param lower the lower bound.
  * @param upper the upper bound.
  * @return the random integer.
  */
 public int nextSecureInt(int lower, int upper) {
   if (lower >= upper) {
     throw new IllegalArgumentException("lower bound must be < upper bound");
   }
   SecureRandom sec = getSecRan();
   return lower + (int) (sec.nextDouble() * (upper - lower + 1));
 }
  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");
  }
  private static byte[] generateSalt() throws NoSuchAlgorithmException {
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    byte[] salt = new byte[16];
    random.nextBytes(salt);

    return salt;
  }
示例#10
0
  /**
   * 获得加密后的16进制形式口令
   *
   * @param password
   * @return
   * @throws NoSuchAlgorithmException
   * @throws UnsupportedEncodingException
   */
  public static String getEncryptedPwd(String password)
      throws NoSuchAlgorithmException, UnsupportedEncodingException {
    // 声明加密后的口令数组变量
    byte[] pwd = null;
    // 随机数生成器
    SecureRandom random = new SecureRandom();
    // 声明盐数组变量
    byte[] salt = new byte[SALT_LENGTH];
    // 将随机数放入盐变量中
    random.nextBytes(salt);

    // 声明消息摘要对象
    MessageDigest md = null;
    // 创建消息摘要
    md = MessageDigest.getInstance("MD5");
    // 将盐数据传入消息摘要对象
    md.update(salt);
    // 将口令的数据传给消息摘要对象
    md.update(password.getBytes("UTF-8"));
    // 获得消息摘要的字节数组
    byte[] digest = md.digest();

    // 因为要在口令的字节数组中存放盐,所以加上盐的字节长度
    pwd = new byte[digest.length + SALT_LENGTH];
    // 将盐的字节拷贝到生成的加密口令字节数组的前12个字节,以便在验证口令时取出盐
    System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH);
    // 将消息摘要拷贝到加密口令字节数组从第13个字节开始的字节
    System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length);
    // 将字节数组格式加密后的口令转化为16进制字符串格式的口令
    return byteToHexString(pwd);
  }
示例#11
0
 /** Generate a local password and save it in the local-password file. */
 public void postConstruct() {
   logger.fine("Generating local password");
   SecureRandom random = new SecureRandom();
   byte[] pwd = new byte[PASSWORD_BYTES];
   random.nextBytes(pwd);
   password = toHex(pwd);
   File localPasswordFile = new File(env.getConfigDirPath(), LOCAL_PASSWORD_FILE);
   PrintWriter w = null;
   try {
     if (!localPasswordFile.exists()) {
       localPasswordFile.createNewFile();
       /*
        * XXX - There's a security hole here.
        * Between the time the file is created and the permissions
        * are changed to prevent others from opening it, someone
        * else could open it and wait for the data to be written.
        * Java needs the ability to create a file that's readable
        * only by the owner; coming in JDK 7.
        */
       localPasswordFile.setWritable(false, false); // take from all
       localPasswordFile.setWritable(true, true); // owner only
       localPasswordFile.setReadable(false, false); // take from all
       localPasswordFile.setReadable(true, true); // owner only
     }
     w = new PrintWriter(localPasswordFile);
     w.println(password);
   } catch (IOException ex) {
     // ignore errors
     logger.log(Level.FINE, "Exception writing local password file", ex);
   } finally {
     if (w != null) w.close();
   }
 }
示例#12
0
  private HashMap<Point2D, String> makePointList(String category, List<Report> toolResults) {
    HashMap<Point2D, String> map = new HashMap<Point2D, String>();
    char ch = 'A';

    // make a list of all points.  Add in a tiny random to prevent exact duplicate coordinates in
    // map
    for (Report r : toolResults) {
      OverallResult or = r.getOverallResults().getResults(category);
      double x = or.getFalsePositiveRate() * 100 + sr.nextDouble() * .000001;
      double y =
          or.getTruePositiveRate() * 100
              + sr.nextDouble() * .000001
              - 1; // this puts the label just below the point
      Point2D p = new Point2D.Double(x, y);
      String label = "" + ch;
      map.put(p, label);
      ch++;
    }
    Point2D ap =
        new Point2D.Double(
            afr * 100 + sr.nextDouble() * .000001, atr * 100 + sr.nextDouble() * .000001 - 1);

    map.put(ap, "" + ch);
    dedupify(map);
    return map;
  }
示例#13
0
  public Message startAuthentication(AuthenticationMessage msg)
      throws AuthenticationException, GeneralSecurityException {
    if (msg instanceof RequestLoginMessage) {
      RequestLoginMessage rlm = (RequestLoginMessage) msg;
      username = rlm.getLogin();

      if (!allowRoot && username.equals("root")) {
        throw new AuthenticationException("Must authenticate as a regular user first.");
      }

      // generate challange
      byte[] passhash = UserManager.v().getPassHash(username);
      if (passhash == null) {
        throw new AuthenticationException("User has no password");
      }

      ChallangeMessage cm = new ChallangeMessage();
      SecureRandom rand = new SecureRandom();
      rand.nextBytes(randNumber);
      cm.setChallange(randNumber, passhash);
      state = CL_CHALLANGE_SENT;

      // send the challange
      return cm;
    } else if (msg instanceof ChallangeCheckStatusMessage) {
      // After authentication is complete the client sends this message
      //  It can be safely ignored. We don't care that the client has
      //  actually authenticated us.
      return null;
    }

    throw new AuthenticationException("State Error");
  }
示例#14
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;
  }
  /* 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 static void main(String[] args) {
    SecureRandom random;
    try {
      random = SecureRandom.getInstance("SHA1PRNG");
      byte[] keyBytes = new byte[16];
      random.nextBytes(keyBytes);

      byte[] ivBytes = new byte[16];
      random.nextBytes(ivBytes);

      KeyIVPair keyIvPair =
          new KeyIVPair(
              "8x/xUBgX0Up+3UEo39dSeG277JhVj31+ElHkN5+EC0Q=",
              "Y2SUiIN6JXTdKNK/ZMDyVtLB7gAM9MCCiyrP1xd3bSQ=");
      // keyIvPair.setKeyBytes(keyBytes);
      // keyIvPair.setIvBytes(ivBytes);

      Gson gson = new GsonBuilder().create();
      ConsoleProxyPasswordBasedEncryptor encryptor =
          new ConsoleProxyPasswordBasedEncryptor(gson.toJson(keyIvPair));

      String encrypted = encryptor.encryptText("Hello, world");

      System.out.println("Encrypted result: " + encrypted);

      String decrypted = encryptor.decryptText(encrypted);

      System.out.println("Decrypted result: " + decrypted);

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
  }
 public void afterPropertiesSet() throws Exception {
   if (provider == null) {
     srand = SecureRandom.getInstance(algorithm);
   } else {
     srand = SecureRandom.getInstance(algorithm, provider);
   }
 }
示例#18
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headers = request.getHeaders("foo");
    if (headers.hasMoreElements()) {
      param = headers.nextElement(); // just grab first element
    }

    String bar = doSomething(param);

    try {
      java.security.SecureRandom secureRandomGenerator =
          java.security.SecureRandom.getInstance("SHA1PRNG");

      // Get 40 random bytes
      byte[] randomBytes = new byte[40];
      secureRandomGenerator.nextBytes(randomBytes);
      response.getWriter().println("Random bytes are: " + new String(randomBytes));

    } catch (java.security.NoSuchAlgorithmException e) {
      System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
      throw new ServletException(e);
    } finally {
      response
          .getWriter()
          .println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
  } // end doPost
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2() throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_t) {
      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
      /* FIX: Use a hardcoded string */
      data = "foo";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

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

      data = ""; /* init data */

      /* read user input from console with readLine*/
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        data = buffread.readLine();
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }
      }
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_t) {
      MessageDigest hash = MessageDigest.getInstance("SHA-512");
      hash.update(data.getBytes()); /* FLAW: SHA512 with a predictable salt */
      byte[] hashv = hash.digest("hash me".getBytes());
      IO.writeLine(IO.toHex(hashv));
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      SecureRandom r = new SecureRandom();

      MessageDigest hash = MessageDigest.getInstance("SHA-512");
      hash.update(r.getSeed(32)); /* FIX: Use a sufficiently random salt */
      byte[] hashv = hash.digest("hash me".getBytes());

      IO.writeLine(IO.toHex(hashv));
    }
  }
  /**
   * @tests javax.crypto.Cipher#getParameters()
   * @tests javax.crypto.Cipher#init(int, java.security.Key, java.security.AlgorithmParameters,
   *     java.security.SecureRandom)
   */
  public void test_getParameters() throws Exception {

    /*
     * If this test is changed, implement the following:
     * test_initILjava_security_KeyLjava_security_AlgorithmParametersLjava_security_SecureRandom()
     */

    SecureRandom sr = new SecureRandom();
    Cipher cipher = null;

    byte[] apEncoding = null;

    byte[] iv = new byte[8];
    sr.nextBytes(iv);

    AlgorithmParameters ap = AlgorithmParameters.getInstance("DESede");
    ap.init(iv, "RAW");
    apEncoding = ap.getEncoded("ASN.1");

    cipher = Cipher.getInstance(algorithm + "/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap, sr);

    byte[] cipherParmsEnc = cipher.getParameters().getEncoded("ASN.1");
    assertTrue("Parameters differ", Arrays.equals(apEncoding, cipherParmsEnc));
  }
示例#21
0
 /**
  * Generate a random long value uniformly distributed between <code>lower</code> and <code>upper
  * </code>, inclusive. This algorithm uses a secure random number generator.
  *
  * @param lower the lower bound.
  * @param upper the upper bound.
  * @return the random integer.
  */
 public long nextSecureLong(long lower, long upper) {
   if (lower >= upper) {
     throw new IllegalArgumentException("lower bound must be < upper bound");
   }
   SecureRandom sec = getSecRan();
   return lower + (long) (sec.nextDouble() * (upper - lower + 1));
 }
 private static byte[] key(final byte[] key) throws Exception {
   final KeyGenerator gen = KeyGenerator.getInstance(ALGORITHM);
   final SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
   sr.setSeed(key);
   gen.init(128, sr);
   return gen.generateKey().getEncoded();
 }
 // ---------------------------------------------------------------
 private byte[] getSalt(int saltSize) throws NoSuchAlgorithmException, NoSuchProviderException {
   // SecureRandom sr = SecureRandom.getInstance( SECURE_RANDOM_ALGORITHM,
   // SECURITY_PROVIDER );
   SecureRandom sr = new SecureRandom();
   sr.setSeed(System.currentTimeMillis());
   return sr.generateSeed(saltSize);
 }
示例#24
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);
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Bitmap bm = null;
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object
    byte[] b = baos.toByteArray();

    byte[] keyStart = "this is a key".getBytes();
    KeyGenerator kgen;
    try {
      kgen = KeyGenerator.getInstance("AES");
      SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
      sr.setSeed(keyStart);
      kgen.init(128, sr); // 192 and 256 bits may not be available
      SecretKey skey = kgen.generateKey();
      byte[] key = skey.getEncoded();

      // encrypt
      byte[] encryptedData = encrypt(key, b);
      // decrypt
      byte[] decryptedData = decrypt(key, encryptedData);
    } catch (NoSuchAlgorithmException e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    } catch (Exception e) {
      // TODO 自動產生的 catch 區塊
      e.printStackTrace();
    }
  }
  /** @return Creates a unique path to an activity in the form of 2010-01-21-09-randombit */
  public static String createId() {
    Calendar c = Calendar.getInstance();

    String[] vals = new String[4];
    vals[0] = "" + c.get(Calendar.YEAR);
    vals[1] = StringUtils.leftPad("" + (c.get(Calendar.MONTH) + 1), 2, "0");
    vals[2] = StringUtils.leftPad("" + c.get(Calendar.DAY_OF_MONTH), 2, "0");
    vals[3] = StringUtils.leftPad("" + c.get(Calendar.HOUR_OF_DAY), 2, "0");

    StringBuilder id = new StringBuilder();

    for (String v : vals) {
      id.append(v).append("-");
    }

    byte[] bytes = new byte[20];
    String randomHash = "";
    try {
      if (random == null) {
        random = SecureRandom.getInstance("SHA1PRNG");
      }
      random.nextBytes(bytes);
      randomHash = Arrays.toString(bytes);
      randomHash = org.sakaiproject.nakamura.util.StringUtils.sha1Hash(randomHash);
    } catch (NoSuchAlgorithmException e) {
    } catch (UnsupportedEncodingException e) {
    }

    id.append(randomHash);
    return id.toString();
  }
示例#27
0
 private static byte[] randomBytes(int length) throws GeneralSecurityException {
   fixPrng();
   SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM);
   byte[] b = new byte[length];
   random.nextBytes(b);
   return b;
 }
示例#28
0
  /**
   * Generate a UUID using <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a> UUID
   * generation of a type 4 or randomly generated UUID.
   *
   * @return the 32 character long UUID string.
   * @throws KeyManagerException
   */
  protected String generateUUID() throws KeyManagerException {
    byte vfour[] = new byte[KEY_LENGTH];

    if (isRandomMode() == SECURE) {
      if (secureRandom == null) {
        try {
          secureRandom = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
          setRandomMode(!SECURE);
          log.warn("Unable to use SecureRandom", e);
        }
      }

      if (isRandomMode() == SECURE) {
        secureRandom.nextBytes(vfour);
      }
    }

    if (isRandomMode() != SECURE) {
      if (random == null) {
        random = new Random();
      }

      random.nextBytes(vfour);
    }

    vfour[6] &= 0x0F;
    vfour[6] |= (4 << 4);
    vfour[8] &= 0x3F;
    vfour[8] |= 0x80;

    return Hex.encode(vfour);
  }
示例#29
0
 /**
  * This method: Encrypts bytes using a cipher. Generates MAC for intialization vector of the
  * cipher Generates MAC for encrypted data Returns a byte array consisting of the following
  * concatenated together: |MAC for cnrypted Data | MAC for Init Vector | Encrypted Data |
  *
  * @param bytes The byte array to be encrypted.
  * @return the encrypted byte array.
  */
 public byte[] encrypt(byte[] bytes) {
   byte[] securedata = null;
   try {
     // Generate IV
     SecureRandom rand = new SecureRandom();
     byte[] iv = new byte[16];
     rand.nextBytes(iv);
     IvParameterSpec ivspec = new IvParameterSpec(iv);
     Cipher encryptCipher = Cipher.getInstance(CIPHER_CODE);
     encryptCipher.init(Cipher.ENCRYPT_MODE, sk, ivspec);
     Mac encryptMac = Mac.getInstance(MAC_CODE);
     encryptMac.init(sk);
     encryptMac.update(iv);
     // encrypt the plaintext
     byte[] encdata = encryptCipher.doFinal(bytes);
     byte[] macBytes = encryptMac.doFinal(encdata);
     byte[] tmp = concatBytes(macBytes, iv);
     securedata = concatBytes(tmp, encdata);
   } catch (NoSuchAlgorithmException
       | NoSuchPaddingException
       | InvalidKeyException
       | InvalidAlgorithmParameterException
       | IllegalStateException
       | IllegalBlockSizeException
       | BadPaddingException e) {
     if (LOGGER.isLoggable(Level.SEVERE)) {
       LOGGER.log(
           Level.SEVERE,
           "Unexpected exception initializing encryption." + "  No encryption will be performed.",
           e);
     }
     return null;
   }
   return securedata;
 }
示例#30
0
文件: OCPAgent.java 项目: ccbon/ocp
 public Id generateId() throws Exception {
   MessageDigest md = MessageDigest.getInstance(ds().network.getProperty("hash", "SHA-1"));
   SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
   byte[] input = new byte[200];
   random.nextBytes(input);
   return new Id(md.digest(input));
 }