Example usage for java.security SecureRandom getInstance

List of usage examples for java.security SecureRandom getInstance

Introduction

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

Prototype

public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SecureRandom object that implements the specified Random Number Generator (RNG) algorithm.

Usage

From source file:org.openintents.safe.CryptoHelper.java

/**
 * Generate a random salt for use with the cipher.
 *
 * @return String version of the 8 byte salt
 * @author Randy McEoin//from w w w  .  j  ava 2 s  .  c  om
 */
public static String generateSalt() throws NoSuchAlgorithmException {
    byte[] salt = new byte[8];
    SecureRandom sr;
    try {
        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.nextBytes(salt);
        if (debug) {
            Log.d(TAG, "generateSalt: salt=" + salt.toString());
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw e;
    }
    return toHexString(salt);
}

From source file:helma.servlet.AbstractServletClient.java

/**
 * Init this servlet.//from   w ww .  j a  va  2 s .com
 *
 * @param init the servlet configuration
 *
 * @throws ServletException ...
 */
public void init(ServletConfig init) throws ServletException {
    super.init(init);

    // get max size for file uploads per file
    String upstr = init.getInitParameter("uploadLimit");
    try {
        uploadLimit = (upstr == null) ? 1024 : Integer.parseInt(upstr);
    } catch (NumberFormatException x) {
        log("Bad number format for uploadLimit: " + upstr);
        uploadLimit = 1024;
    }
    // get max total upload size
    upstr = init.getInitParameter("totalUploadLimit");
    try {
        totalUploadLimit = (upstr == null) ? uploadLimit : Integer.parseInt(upstr);
    } catch (NumberFormatException x) {
        log("Bad number format for totalUploadLimit: " + upstr);
        totalUploadLimit = uploadLimit;
    }
    // soft fail mode for upload errors
    uploadSoftfail = ("true".equalsIgnoreCase(init.getInitParameter("uploadSoftfail")));

    // get cookie domain
    cookieDomain = init.getInitParameter("cookieDomain");
    if (cookieDomain != null) {
        cookieDomain = cookieDomain.toLowerCase();
    }

    // get session cookie name
    sessionCookieName = init.getInitParameter("sessionCookieName");
    if (sessionCookieName == null) {
        sessionCookieName = "HopSession";
    }

    // disable binding session cookie to ip address?
    protectedSessionCookie = !("false".equalsIgnoreCase(init.getInitParameter("protectedSessionCookie")));

    // debug mode for printing out detailed error messages
    debug = ("true".equalsIgnoreCase(init.getInitParameter("debug")));

    // generally disable response caching for clients?
    caching = !("false".equalsIgnoreCase(init.getInitParameter("caching")));

    // Get random number generator for session ids
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
        secureRandom = true;
    } catch (NoSuchAlgorithmException nsa) {
        random = new Random();
        secureRandom = false;
    }
    random.setSeed(
            random.nextLong() ^ System.currentTimeMillis() ^ hashCode() ^ Runtime.getRuntime().freeMemory());
    random.nextLong();

}

From source file:org.wso2.carbon.ui.filters.CSRFProtector.java

private static String generateCSRFToken() throws NoSuchAlgorithmException {
    byte random[] = new byte[16];

    // Render the result as a String of hexadecimal digits
    StringBuilder buffer = new StringBuilder();

    SecureRandom.getInstance(CSRFConstants.CSRF_TOKEN_PRNG).nextBytes(random);

    for (int j = 0; j < random.length; j++) {
        byte b1 = (byte) ((random[j] & 0xf0) >> 4);
        byte b2 = (byte) (random[j] & 0x0f);
        if (b1 < 10) {
            buffer.append((char) ('0' + b1));
        } else {//from www  . ja  v  a  2  s  .  c  o  m
            buffer.append((char) ('A' + (b1 - 10)));
        }
        if (b2 < 10) {
            buffer.append((char) ('0' + b2));
        } else {
            buffer.append((char) ('A' + (b2 - 10)));
        }
    }

    return buffer.toString();
}

From source file:burrito.util.StringUtils.java

/**
 * Genererar en random strng/* w  ww. ja v  a  2  s  . c  o m*/
 * @param length
 * @return
 */
public static String generateRandomString(int length) {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        char[] chars = new char[length];

        for (int i = 0; i < length; i++) {
            chars[i] = randomStringAlphabet[random.nextInt(randomStringAlphabet.length)];
        }

        return String.valueOf(chars);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML1ArtifactResolutionTest.java

@SuppressWarnings("unchecked")
protected SAMLArtifactMapEntry stageArtifact(String relyingPartyId) throws Exception {
    SAMLObjectBuilder<Assertion> assetionBuilder = (SAMLObjectBuilder<Assertion>) builderFactory
            .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
    Assertion assertion = assetionBuilder.buildObject();

    SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG");
    byte[] assertionHandle = new byte[20];
    handleGenerator.nextBytes(assertionHandle);
    SAML1ArtifactType0002 artifact = new SAML1ArtifactType0002(assertionHandle, relyingPartyId);

    SAMLArtifactMap artifactMap = (SAMLArtifactMap) getApplicationContext().getBean("shibboleth.ArtifactMap");
    artifactMap.put(artifact.base64Encode(), relyingPartyId, "urn:example.org:idp1", assertion);
    return artifactMap.get(artifact.base64Encode());
}

From source file:com.snaplogic.snaps.uniteller.CustomUFSSecurityMgr.java

@Override
public String generatePassword() throws UFSSecurityMgrException {
    String id = null;//from   w  w  w .  j  a va 2  s .  co m
    try {
        byte[] byteArr = new byte[256];
        SecureRandom secureRnd = SecureRandom.getInstance(ENC_ALG);
        secureRnd.setSeed(new Long(System.currentTimeMillis()).toString().getBytes());
        MessageDigest md = MessageDigest.getInstance(DS_ALG);
        secureRnd.nextBytes(byteArr);
        md.update(byteArr);
        md.update(new Long(System.currentTimeMillis()).toString().getBytes());
        byteArr = md.digest();
        id = Base64.encode(byteArr, 0, 12);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new UFSSecurityMgrException(e.getMessage());
    }
    return id;
}

From source file:org.restlet.ext.oauth.OAuthProxy.java

/**
 * Sets up an OAuthProxy./*from  w  ww  .j a v a2  s  .co  m*/
 * 
 * @param useBasicSecret
 *            If true use http basic authentication otherwise use form
 *            based.
 * @param ctx
 *            The Restlet context.
 * @param requestClient
 *            A predefined client that will be used for remote client
 *            request. Useful when you need to set e.g. SSL initialization
 *            parameters
 */
public OAuthProxy(Context ctx, boolean useBasicSecret, org.restlet.Client requestClient) {
    this.basicSecret = useBasicSecret;
    setContext(ctx);
    no.add(CacheDirective.noStore());
    this.cc = requestClient;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:com.serli.maven.plugin.quality.mojo.LicenseMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*from   w  w  w  .j a v  a  2  s.com*/
        RANDOM = SecureRandom.getInstance("SHA1PRNG");
    } catch (Exception e) {
        e.printStackTrace();
    }

    // TODO s'inspirer de
    // http://maven-license-plugin.googlecode.com/svn/branches/maven-license-plugin-1.x.x/src/main/java/com/google/code/mojo/license/LicenseCheckMojo.java
    // TODO extends de AbstractLicenseMojo, mais ecrire dans un fichier les
    // 'missingHeader'
    // TODO choper le fichier nomm par l'URL

    // TODO voir aussi le project-info pour avoir les licenses des dependances
    // (determiner la compatibilite des licenses ?)
    // TODO voir comment ils gerent avec le DependenciesRenderer :
    // http://svn.apache.org/viewvc/maven/plugins/tags/maven-project-info-reports-plugin-2.2/src/main/java/org/apache/maven/report/projectinfo/dependencies/renderer/DependenciesRenderer.java?view=markup
    projectLicenses = new ArrayList<LightLicense>();
    List licenses = project.getModel().getLicenses();
    for (Iterator i = licenses.iterator(); i.hasNext();) {
        License license = (License) i.next();
        LightLicense projectLicense = new LightLicense();
        projectLicense.setName(license.getName());
        projectLicense.setUrl(license.getUrl());
        header = projectLicense.getUrl();
        projectLicenses.add(projectLicense);

        // TODO que faire si plusieurs licenses pour le projet

        // URL licenseUrl = null;
        // try {
        // licenseUrl = getLicenseURL(project, license.getUrl());
        // System.out.println("licenseURL = " + licenseUrl);
        // } catch (MalformedURLException e) {
        // getLog().error(e.getMessage());
        // } catch (IOException e) {
        // getLog().error(e.getMessage());
        // }
        //
        // if (licenseUrl != null && licenseUrl.getProtocol().equals("file")) {
        // }

    }

    checkHeaders();

    DependencyNode dependencyTreeNode = resolveProject();
    getAllDependencies(dependencyTreeNode);

    stockAllArtifactAndItsLicense(dependencyTreeNode);
    // TODO enlever le projet des autres listes et maps
    // printGroupedLicenses();
    // printLicenses();
    StringBuffer buffer = printResults();
    try {
        Util.writeFile(buffer.toString(), outputFile, getLog());
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * ?//from   ww w  .  ja  v a  2s.co  m
 * 
 * @param ctx
 *            
 * @return key
 */
public static Key generateSecretKey(SecurityContext ctx) {
    try {
        KeyGenerator skg = KeyGenerator.getInstance(ctx.getSymmetryKeyAlgorithm(), ctx.getJceProvider());
        SecureRandom secureRandom = SecureRandom.getInstance(ctx.getSecureRandomAlgorithm());
        skg.init(ctx.getSymmetryKeySize(), secureRandom);
        SecretKey key = skg.generateKey();
        return key;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}