Example usage for java.security SecureRandom nextInt

List of usage examples for java.security SecureRandom nextInt

Introduction

In this page you can find the example usage for java.security SecureRandom nextInt.

Prototype

public int nextInt() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.

Usage

From source file:io.stallion.services.SecureTempTokens.java

public String idToRandomString(Long id) {
    SecureRandom random = new SecureRandom();
    Integer rand = random.nextInt();
    Long n = rand * 1000000000 + id;
    return Base64.getEncoder().encodeToString(BigInteger.valueOf(n).toByteArray());
}

From source file:eu.trentorise.smartcampus.permissionprovider.auth.google.GoogleAuthHelper.java

/**
 * Generates a secure state token./*  w w w.jav  a  2 s. co  m*/
 */
private String generateStateToken() {
    SecureRandom sr1 = new SecureRandom();
    return "google;" + sr1.nextInt();
}

From source file:Uuid32Generator.java

public String generate() {
    StringBuilder strRetVal = new StringBuilder();
    String strTemp;/*  w  w w  . j  a  va 2s. co m*/
    try {
        // IPAddress segment
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipaddr = addr.getAddress();
        for (byte anIpaddr : ipaddr) {
            Byte b = new Byte(anIpaddr);
            strTemp = Integer.toHexString(b.intValue() & 0x000000ff);
            strRetVal.append(ZEROS.substring(0, 2 - strTemp.length()));
            strRetVal.append(strTemp);
        }
        strRetVal.append(':');

        // CurrentTimeMillis() segment
        strTemp = Long.toHexString(System.currentTimeMillis());
        strRetVal.append(ZEROS.substring(0, 12 - strTemp.length()));
        strRetVal.append(strTemp).append(':');

        // random segment
        SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
        strTemp = Integer.toHexString(prng.nextInt());
        while (strTemp.length() < 8) {
            strTemp = '0' + strTemp;
        }
        strRetVal.append(strTemp.substring(4)).append(':');

        // IdentityHash() segment
        strTemp = Long.toHexString(System.identityHashCode(this));
        strRetVal.append(ZEROS.substring(0, 8 - strTemp.length()));
        strRetVal.append(strTemp);
    } catch (UnknownHostException uhex) {
        throw new RuntimeException("Unknown host.", uhex);
    } catch (NoSuchAlgorithmException nsaex) {
        throw new RuntimeException("Algorithm 'SHA1PRNG' is unavailiable.", nsaex);
    }
    return strRetVal.toString().toUpperCase();
}

From source file:com.github.beat.signer.pdf_signer.TSAClient.java

/**
 *
 * @param messageImprint/*from ww w. j a  v a2 s.com*/
 *            imprint of message contents
 * @return the encoded time stamp token
 * @throws IOException
 *             if there was an error with the connection or data from the
 *             TSA server, or if the time stamp response could not be
 *             validated
 */
public byte[] getTimeStampToken(byte[] messageImprint) throws IOException {
    digest.reset();
    byte[] hash = digest.digest(messageImprint);

    // 32-bit cryptographic nonce
    // FIXME sicher??
    SecureRandom random = new SecureRandom();
    int nonce = random.nextInt();

    // generate TSA request
    TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
    tsaGenerator.setCertReq(true);
    ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm());
    TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));

    // get TSA response
    byte[] tsaResponse = getTSAResponse(request.getEncoded());

    TimeStampResponse response;
    try {
        response = new TimeStampResponse(tsaResponse);
        response.validate(request);
    } catch (TSPException e) {
        throw new IOException(e);
    }

    TimeStampToken token = response.getTimeStampToken();
    if (token == null) {
        throw new IOException("Response does not have a time stamp token");
    }

    return token.getEncoded();
}

From source file:TSAClient.java

/**
 *
 * @param messageImprint imprint of message contents
 * @return the encoded time stamp token//w  w  w . j  a  va 2 s.c o m
 * @throws IOException if there was an error with the connection or data from the TSA server,
 *                     or if the time stamp response could not be validated
 */
public byte[] getTimeStampToken(byte[] messageImprint) throws IOException {
    digest.reset();
    byte[] hash = digest.digest(messageImprint);

    // 32-bit cryptographic nonce
    SecureRandom random = new SecureRandom();
    int nonce = random.nextInt();

    // generate TSA request
    TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
    tsaGenerator.setCertReq(true);
    ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm());
    TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));

    // get TSA response
    byte[] tsaResponse = getTSAResponse(request.getEncoded());

    TimeStampResponse response;
    try {
        response = new TimeStampResponse(tsaResponse);
        response.validate(request);
    } catch (TSPException e) {
        throw new IOException(e);
    }

    TimeStampToken token = response.getTimeStampToken();
    if (token == null) {
        throw new IOException("Response does not have a time stamp token");
    }

    return token.getEncoded();
}

From source file:edu.hm.muse.controller.Logincontroller.java

@RequestMapping(value = "/adminlogin.secu", method = RequestMethod.GET)
public ModelAndView showAdminLoginScreen(HttpSession session) {
    ModelAndView mv = new ModelAndView("adminlogin");
    mv.addObject("msg", "Enter password");

    SecureRandom random = new SecureRandom();

    int token = random.nextInt();

    mv.addObject("csrftoken", token);
    session.setAttribute("csrftoken", token);

    return mv;//from   w w w.  ja  v  a 2 s. co m
}

From source file:org.apache.ftpserver.ssl.Ssl.java

/**
 * Get SSL Context./*  w w  w  .j a v  a  2 s.  c o m*/
 */
private synchronized SSLContext getSSLContext(String protocol) throws Exception {

    // null value check
    if (protocol == null) {
        protocol = m_sslProtocol;
    }

    // if already stored - return it
    SSLContext ctx = (SSLContext) m_sslContextMap.get(protocol);
    if (ctx != null) {
        return ctx;
    }

    // create new secure random object
    SecureRandom random = new SecureRandom();
    random.nextInt();

    // create SSLContext
    ctx = SSLContext.getInstance(protocol);
    ctx.init(m_keyManagerFactory.getKeyManagers(), m_trustManagerFactory.getTrustManagers(), random);

    // store it in map
    m_sslContextMap.put(protocol, ctx);
    return ctx;
}

From source file:edu.hm.muse.controller.Logincontroller.java

@RequestMapping(value = "/adminlogin.secu", method = RequestMethod.POST)
public ModelAndView doAdminLogin(@RequestParam(value = "mpwd", required = false) String mpwd,
        @RequestParam(value = "csrftoken", required = false) String csrfParam, HttpServletResponse response,
        HttpSession session) {//from   w  ww  . j  a  v a  2 s  . c om
    if (null == mpwd || mpwd.isEmpty()) {
        throw new SuperFatalAndReallyAnnoyingException(
                "I can not process, because the requestparam mpwd is empty or null or something like this");
    }

    String sql = "select count (*) from M_ADMIN where mpwd = ?";

    try {
        String digest = calculateSHA256(new ByteArrayInputStream(mpwd.getBytes("UTF8")));

        int res = 0;

        res = jdbcTemplate.queryForInt(sql, new Object[] { digest }, new int[] { Types.VARCHAR });

        Integer csrfTokenSess = (Integer) session.getAttribute("csrftoken");
        if (res != 0 && csrfParam != null && !csrfParam.isEmpty() && csrfTokenSess != null) {
            Integer csrfParamToken = Integer.parseInt(csrfParam);
            if (csrfParamToken.intValue() == csrfTokenSess.intValue()) {
                SecureRandom random = new SecureRandom();
                int token = random.nextInt();
                session.setAttribute("user", "admin");
                session.setAttribute("login", true);
                session.setAttribute("admintoken", token);
                response.addCookie(new Cookie("admintoken", String.valueOf(token)));
                session.removeAttribute("csrftoken");
                return new ModelAndView("redirect:adminintern.secu");
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (ClassCastException ccastEx) {
        ccastEx.printStackTrace();
    } catch (NumberFormatException nfoEx) {
        nfoEx.printStackTrace();
    } catch (DataAccessException e) {
        throw new SuperFatalAndReallyAnnoyingException(
                String.format("Sorry but %sis a bad grammar or has following problem %s", sql, e.getMessage()));
    }
    ModelAndView mv = returnToAdminLogin(session);
    return mv;
}

From source file:com.sap.prd.mobile.ios.mios.xcodeprojreader.ProjectFile.java

public String generateReference() {
    MessageDigest md = null;//from  w  w w  .  java  2 s. c om
    SecureRandom prng = null;
    try {
        md = MessageDigest.getInstance("SHA1");
        prng = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
    }

    String randomNum = new Integer(prng.nextInt()).toString();
    String ref = new String(Hex.encodeHex(md.digest(randomNum.getBytes())));
    return ref.toUpperCase().substring(0, 24);
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

private BigInteger getSecureRandomeInt() {
    final SecureRandom secureRandom = new SecureRandom();
    final BigInteger bigInt = BigInteger.valueOf(secureRandom.nextInt());
    return new BigInteger(1, bigInt.toByteArray());
}