Example usage for java.security SecureRandom nextLong

List of usage examples for java.security SecureRandom nextLong

Introduction

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

Prototype

public long nextLong() 

Source Link

Document

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

Usage

From source file:Main.java

public static synchronized String getNonce() {
    SecureRandom sr = new SecureRandom();
    return Long.toString(Math.abs(sr.nextLong()), Character.MAX_RADIX);
}

From source file:Main.java

public static String generateNonce() {
    try {//from   w w w .  jav  a 2  s.c om
        // Create a secure random number generator
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

        // Get 1024 random bits
        byte[] bytes = new byte[1024 / 8];
        sr.nextBytes(bytes);

        // Create two secure number generators with the same seed
        int seedByteCount = 10;
        byte[] seed = sr.generateSeed(seedByteCount);

        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        SecureRandom sr2 = SecureRandom.getInstance("SHA1PRNG");
        sr2.setSeed(seed);

        String nonce = Long.toHexString(sr2.nextLong());
        nonce = nonce.substring(0, 7);

        return nonce;

    } catch (NoSuchAlgorithmException e) {
    }
    return null;
}

From source file:de.dominikschadow.javasecurity.csrf.CSRFTokenHandler.java

private static String getToken() throws NoSuchAlgorithmException, NoSuchProviderException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
    sr.nextBytes(new byte[20]);
    return String.valueOf(sr.nextLong());
}

From source file:utils.Hash.java

/**
 * Creates a psedorandom string//  w  ww  .jav a 2 s .  c  o  m
 * @return Random String
 */
public static String randomString() {
    String result = new String();
    try {
        byte byteArray[] = new byte[16];
        SecureRandom psn1 = SecureRandom.getInstance("SHA1PRNG");
        psn1.setSeed(psn1.nextLong());
        psn1.nextBytes(byteArray);
        BigInteger bigInt = new BigInteger(byteArray);
        result = bigInt.toString();
        log.debug("Generated String = " + result);

    } catch (Exception e) {
        log.error("Random Number Error : " + e.toString());
    }
    return result;
}

From source file:utils.Hash.java

/**
 * Generates a small psedorandom string//from   w  ww .  j ava  2s  . c  o m
 * @return Random String
 */
public static String smallRandomString() {
    String result = new String();
    try {
        byte byteArray[] = new byte[4];
        SecureRandom psn1 = SecureRandom.getInstance("SHA1PRNG");
        psn1.setSeed(psn1.nextLong());
        psn1.nextBytes(byteArray);
        BigInteger bigInt = new BigInteger(byteArray);
        result = bigInt.toString();
        log.debug("Generated String = " + result);

    } catch (Exception e) {
        log.error("Random Number Error : " + e.toString());
    }
    return result;
}

From source file:servlets.module.challenge.BrokenCryptoHomeMade.java

public static String randomKeyLengthString() {
    String result = new String();
    try {/*from ww  w. j a v  a 2s  . c o  m*/
        byte byteArray[] = new byte[16];
        SecureRandom psn1 = SecureRandom.getInstance("SHA1PRNG");
        psn1.setSeed(psn1.nextLong());
        psn1.nextBytes(byteArray);
        result = new String(byteArray, Charset.forName("US-ASCII"));
        //log.debug("Generated Key = " + result);
        if (result.length() != 16) {
            log.error("Generated Key is the incorrect Length: Shortening ");
            result = result.substring(0, 15);
            if (result.length() != 16)
                log.fatal("Encryption key length is Still not Right");
        }
    } catch (Exception e) {
        log.error("Random Number Error : " + e.toString());
    }
    return result;
}

From source file:utils.Hash.java

/**
 * Creates a psedorandom base64 string/*w  w  w .  j  a v  a  2s  .  c om*/
 * @return Random String
 */
public static String randomBase64String() {
    String result = new String();
    try {
        byte byteArray[] = new byte[256];
        SecureRandom psn1 = SecureRandom.getInstance("SHA1PRNG");

        Base64 base64 = new Base64();
        psn1.setSeed(psn1.nextLong());
        psn1.nextBytes(byteArray);
        result = new String(byteArray, Charset.forName("US-ASCII"));
        result = base64.encode(thisString(thisString(byteArray.toString())).getBytes()).toString();
        log.debug("Generated String = " + result);
    } catch (Exception e) {
        log.error("Random Number Error : " + e.toString());
    }
    return result;
}

From source file:com.sonicle.webtop.core.util.IdentifierUtils.java

/**
 * @deprecated use com.sonicle.commons.IdentifierUtils.getRandomAlphaNumericString instead
 * @return//  w ww .  j a v a2s.co m
 */
@Deprecated
public static synchronized String getRandomAlphaNumericString(int length) {
    try {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        Random rand = new Random();
        char buff[] = new char[length];
        for (int i = 0; i < length; ++i) {
            // reseed rand once you've used up all available entropy bits
            if ((i % 10) == 0)
                rand.setSeed(sr.nextLong()); // 64 bits of random!
            buff[i] = VALID_CHARACTERS[rand.nextInt(VALID_CHARACTERS.length)];
        }
        return new String(buff);
    } catch (NoSuchAlgorithmException ex) {
        return null;
    }
}

From source file:controllers.acentera.Auth.java

private static WebUser create(String email, String password) throws Exception {
    UsernamePasswordToken upToken = new UsernamePasswordToken(email, password);

    //Get potential Existing Partner..
    Partner partner = PartnerImpl.getPartnerByEmail(email);

    if (partner == null) {
        //Must Create
        partner = new Partner();
        SecureRandom mySecureRand = new SecureRandom();
        Long secureInitializer = mySecureRand.nextLong();

        String API = Utils.getRandomGUID();
        String SALT = Utils.getRandomGUID();
        partner.setNiceName("");
        partner.setAPIKEY(Utils.hexStringToByteArray(API));
        partner.setName(email);/*from w  ww .  ja  va2s .co  m*/
        partner.setSALT(SALT);
        partner.generateKeys();

        // Usually this can be a field rather than a method variable
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        Integer randomNum = rand.nextInt((1990300 - 10) + 1) + 10;

        PartnerImpl.save(partner);
        PluginManager.notifyEvent(PluginEvent.WEBUSER_PARTNER_CREATED, partner);
    }

    Long pid = partner.getId();

    SecureRandom mySecureRand = new SecureRandom();
    Long secureInitializer = mySecureRand.nextLong();

    String API = Utils.getRandomGUID();
    String SALT = Utils.getRandomGUID();

    // Usually this can be a field rather than a method variable
    Random rand = new Random();

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    Integer randomNum = rand.nextInt((1990300 - 10) + 1) + 10;

    User theUser = UserImpl.getUserByEmail(email);

    if (theUser == null) {
        theUser = new User();
    }

    //Set null...
    theUser.setType(null);

    theUser.setLang("en");
    theUser.setEmail(email);
    theUser.setPassword(password);
    theUser.setPartner(partner);

    UserImpl.saveOrUpdate(theUser);

    PluginManager.notifyEvent(PluginEvent.WEBUSER_USER_CREATED, theUser);

    WebUser wu = new WebUser(theUser.getEmail(), theUser.getPassword(),
            new UsernamePasswordToken(theUser.getEmail(), theUser.getPassword()));
    if (wu.authenticate()) {
        return wu;
    } else {
        return null;
    }
}

From source file:org.talend.designer.maven.utils.PomUtil.java

/**
 * /*from ww w  .  ja  v a  2 s . c o m*/
 * Create pom without refresh eclipse resources
 * 
 * @param artifact
 * @return
 */
public static String generatePom2(MavenArtifact artifact) {
    try {
        Project project = ProjectManager.getInstance().getCurrentProject();
        IProject fsProject = ResourceUtils.getProject(project);
        SecureRandom random = new SecureRandom();
        IPath tempPath = fsProject.getLocation().append("temp").append("pom" + Math.abs(random.nextLong()));
        File tmpFolder = new File(tempPath.toPortableString());
        tmpFolder.mkdirs();
        String pomFile = tempPath.append(TalendMavenConstants.POM_FILE_NAME).toPortableString();
        Model pomModel = new Model();
        pomModel.setModelVersion(TalendMavenConstants.POM_VERSION);
        pomModel.setModelEncoding(TalendMavenConstants.DEFAULT_ENCODING);
        pomModel.setGroupId(artifact.getGroupId());
        pomModel.setArtifactId(artifact.getArtifactId());
        pomModel.setVersion(artifact.getVersion());
        String artifactType = artifact.getType();
        if (artifactType == null || "".equals(artifactType)) {
            artifactType = TalendMavenConstants.PACKAGING_JAR;
        }
        pomModel.setPackaging(artifactType);

        ByteArrayOutputStream buf = new ByteArrayOutputStream();

        MavenPlugin.getMaven().writeModel(pomModel, buf);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(false);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        TransformerFactory tfactory = TransformerFactory.newInstance();

        Document document = documentBuilder.parse(new ByteArrayInputStream(buf.toByteArray()));
        Element documentElement = document.getDocumentElement();

        NamedNodeMap attributes = documentElement.getAttributes();

        if (attributes == null || attributes.getNamedItem("xmlns") == null) { //$NON-NLS-1$
            Attr attr = document.createAttribute("xmlns"); //$NON-NLS-1$
            attr.setTextContent("http://maven.apache.org/POM/4.0.0"); //$NON-NLS-1$
            documentElement.setAttributeNode(attr);
        }

        if (attributes == null || attributes.getNamedItem("xmlns:xsi") == null) { //$NON-NLS-1$
            Attr attr = document.createAttribute("xmlns:xsi"); //$NON-NLS-1$
            attr.setTextContent("http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$
            documentElement.setAttributeNode(attr);
        }

        if (attributes == null || attributes.getNamedItem("xsi:schemaLocation") == null) { //$NON-NLS-1$
            Attr attr = document.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", //$NON-NLS-1$
                    "xsi:schemaLocation"); //$NON-NLS-1$
            attr.setTextContent(
                    "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"); //$NON-NLS-1$
            documentElement.setAttributeNode(attr);
        }
        Transformer transformer = tfactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File(pomFile));
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(source, result);

        return pomFile;
    } catch (PersistenceException e) {
        ExceptionHandler.process(e);
    } catch (CoreException e) {
        ExceptionHandler.process(e);
    } catch (ParserConfigurationException e) {
        ExceptionHandler.process(e);
    } catch (SAXException e) {
        ExceptionHandler.process(e);
    } catch (IOException e) {
        ExceptionHandler.process(e);
    } catch (TransformerConfigurationException e) {
        ExceptionHandler.process(e);
    } catch (TransformerException e) {
        ExceptionHandler.process(e);
    }
    return null;
}