Example usage for java.security SecureRandom SecureRandom

List of usage examples for java.security SecureRandom SecureRandom

Introduction

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

Prototype

public SecureRandom() 

Source Link

Document

Constructs a secure random number generator (RNG) implementing the default random number algorithm.

Usage

From source file:hivemall.math.random.RandomNumberGeneratorFactory.java

@Nonnull
public static PRNG createPRNG(@Nonnull PRNGType type) {
    final PRNG rng;
    switch (type) {
    case java:// w  w  w.  ja v  a2s.  c  o m
        rng = new JavaRandom();
        break;
    case secure:
        rng = new JavaRandom(new SecureRandom());
        break;
    case smile:
        rng = new SmileRandom();
        break;
    case smileMT:
        rng = new SmileRandom(new smile.math.random.MersenneTwister());
        break;
    case smileMT64:
        rng = new SmileRandom(new smile.math.random.MersenneTwister64());
        break;
    case commonsMath3MT:
        rng = new CommonsMathRandom(new org.apache.commons.math3.random.MersenneTwister());
        break;
    default:
        throw new IllegalStateException("Unexpected type: " + type);
    }
    return rng;
}

From source file:com.bconomy.autobit.Encryption.java

public static void makeRandomKey() {
    SecureRandom random;/*from w  w w  .j a v  a2 s .c o  m*/
    try {
        random = SecureRandom.getInstanceStrong();
    } catch (NoSuchAlgorithmException ex) {
        random = new SecureRandom();
    }
    key = new byte[16];
    random.nextBytes(key);
}

From source file:de.micromata.genome.gwiki.auth.PasswordUtils.java

/**
 * Creates a salted password//  w  ww. j a  v a  2  s  . c  o m
 * 
 * @param clearPassword
 * @return
 */
public static String createSaltedPassword(String clearPassword) {
    Validate.notNull(clearPassword);
    Random r = new SecureRandom();
    String salt = RandomStringUtils.random(SALTLENGTH, 32, 127, true, true, null, r);
    return encodePassword(salt, clearPassword);
}

From source file:Main.java

public static SSLContext getDefaultSLLContext() {
    SSLContext sslContext = null;
    try {/*from   w w  w .j a  v  a 2s .c  o  m*/
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManagers }, new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sslContext;
}

From source file:Main.java

/**
 * Generates a public/private key pair that meets Thali's security requirements
 * @return//ww w.j  a  v a2  s .  c o m
 */
public static KeyPair GenerateThaliAcceptablePublicPrivateKeyPair() {
    KeyPairGenerator keyPairGenerator = null;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance(KeyTypeIdentifier);
        // TODO: http://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html talks about security
        // failures in Android caused by improperly initialized RNGs. It would appear that this issue doesn't
        // apply to the latest version of Android. But obviously this is something that has to be further investigated
        // to make sure we are doing this correctly.
        keyPairGenerator.initialize(KeySizeInBits, new SecureRandom());
        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:net.fenyo.gnetwatch.CommandLine.java

/**
 * General entry point./*  w w w .  j a  v a2  s  .  c  o  m*/
 * @param args command line arguments.
 * @return void.
 * @throws IOException io exception.
 * @throws FileNotFoundException file not found.
 */
public static void main(final String[] args)
        throws IOException, FileNotFoundException, InterruptedException, AlgorithmException {
    Config config = null;
    Synchro synchro = null;
    Background background = null;
    GUI gui = null;
    Main main = null;
    SNMPManager snmp_manager = null;
    CaptureManager capture_mgr = null;

    if (args.length > 0) {
        if (args.length == 4 && args[0].equals("import") && args[1].equals("source")) {
            importGenericSrc(args);
            return;
        }
        log.error("invalid arguments");
        System.exit(1);
    }

    // Get configuration properties
    config = new Config();

    // Set debug level
    // debug level 1: simulate hundreds of ping per second to check the DB and hibernate abilities to handle lots of events
    config.setDebugLevel(0);

    // Read general logging rules
    GenericTools.initLogEngine(config);
    log.info(config.getString("log_engine_initialized"));
    log.info(config.getString("begin"));

    /*
    final MessageBox dialog = new MessageBox(new Shell(new org.eclipse.swt.widgets.Display()),
        SWT.ICON_QUESTION | SWT.YES | SWT.NO);
    // traduire
    dialog.setText("GNetWatch startup");
    dialog.setMessage("Database Selection:\ndo you want to erase the current database content ?");
    dialog.open();
    */

    // Initialize Object-Relational mapping
    synchro = new Synchro(config);

    // Do not check SSL certificates
    SSLContext ssl_context = null;
    try {
        ssl_context = SSLContext.getInstance("SSL");
        ssl_context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
    } catch (final NoSuchAlgorithmException ex) {
        log.error("Exception", ex);
    } catch (final KeyManagementException ex) {
        log.error("Exception", ex);
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(ssl_context.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public final boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    // Initialize background processes management
    background = new Background(config);
    background.createBackgroundThread();

    // Initialize packet capture on every interface
    capture_mgr = new CaptureManager(config);

    // Initialize main processes management
    main = new Main(config, capture_mgr);

    // Build SNMP Manager
    snmp_manager = new SNMPManager();

    // Build GUI
    gui = new GUI(config, background, main, snmp_manager, synchro);
    main.setGUI(gui);
    capture_mgr.setGUI(gui);
    gui.waitForCreation();

    // Initial configuration
    gui.createFromXML(gui.getConfig().getProperty("initialobjects"));

    // Move the GUI to the top of the drawing order
    gui.showGUI();

    // merge events at startup
    background.informQueue("merge-1", gui);

    // Wait for the GUI to terminate
    gui.join();
    // The GUI is now closed
    log.info(config.getString("end"));

    // Stop every application thread
    config.setEnd();
    gui.end();
    background.end();
    capture_mgr.unRegisterAllListeners();

    // stop synchronizing
    synchro.end();
}

From source file:RSA.java

/** Create an instance that can both encrypt and decrypt. */
public RSA(int bits) {
    bitlen = bits;//from ww w.  ja  v  a  2  s.c  o m
    SecureRandom r = new SecureRandom();
    BigInteger p = new BigInteger(bitlen / 2, 100, r);
    BigInteger q = new BigInteger(bitlen / 2, 100, r);
    n = p.multiply(q);
    BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
    e = new BigInteger("3");
    while (m.gcd(e).intValue() > 1) {
        e = e.add(new BigInteger("2"));
    }
    d = e.modInverse(m);
}

From source file:com.apabi.r2k.common.security.util.NonceUtils.java

/**
 * SecureRandom?Integer.
 */
public static int randomInt() {
    return new SecureRandom().nextInt();
}

From source file:de.openflorian.crypt.CipherKeyGenerator.java

/**
 * Generate Cipher Secret<br/>//  w  w  w. ja va  2  s .  co m
 * <br/>
 * Secret is generated by Blowfish {@link KeyGenerator} and a system default
 * {@link SecureRandom} provider and Base64 encoded afterwards.
 * 
 * @return Base64 encoded {@link SecureRandom} generated encryption key
 * @throws GeneralSecurityException
 */
public static String generateKey() throws GeneralSecurityException {
    try {
        KeyGenerator gen = KeyGenerator.getInstance("Blowfish");
        gen.init(192, new SecureRandom());
        SecretKey key = gen.generateKey();

        return new String(new Base64().encode(key.getEncoded())).trim();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new GeneralSecurityException(e.getMessage(), e);
    }
}

From source file:com.axelor.apps.account.ebics.certificate.KeyUtil.java

/**
 * Generates a <code>KeyPair</code> in RSA format.
 *
 * @param keyLen - key size// w  w  w .  ja va2s.co m
 * @return KeyPair the key pair
 * @throws NoSuchAlgorithmException
 */
public static KeyPair makeKeyPair(int keyLen) throws NoSuchAlgorithmException {
    KeyPairGenerator keyGen;

    keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(keyLen, new SecureRandom());

    KeyPair keypair = keyGen.generateKeyPair();

    return keypair;

}