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:pplabmed.controller.userController.java

@RequestMapping(value = "/NuevoUsuario.htm", method = RequestMethod.POST)
public String InsertNuevoUsuario(Model m, HttpServletRequest request, @RequestParam("Nombre") String nombre,
        @RequestParam("Correo") String correo, @RequestParam("Area") int area,
        @RequestParam("Estado") String estado, @RequestParam("WebApp") boolean web,
        @RequestParam("MobileApp") boolean mobile, @RequestParam("asignados") String asignados) {

    SecureRandom random = new SecureRandom();
    String passw = new BigInteger(130, random).toString(32).substring(0, 6).toUpperCase();
    UsuarioDAO usuario = new UsuarioDAO();
    boolean estadoU = true;

    if (estado.equals("Inactivo"))
        estadoU = false;//from w w w.j a  v  a2  s .  com

    String num = usuario.AgregarUsuario(nombre, correo, area, estadoU, web, mobile, 0, "", passw);

    UsuarioPorPerfilDAO usxp = new UsuarioPorPerfilDAO();
    usxp.AgregarUsuarioPorPerfil(asignados, Integer.valueOf(num), 0, "");

    EnviarCorreo enviocorreo = new EnviarCorreo();
    String mensajeCorreo = "<p style='font-family: Verdana, sans-serif;text-align: center;font-size:25px; '>Bienvenido al sistema PIF Patologa</p>"
            + "<div style='font-family: Arial, Helvetica, sans-serif;font-size:16px;text-align: justify;'><br/>"
            + "Hola " + nombre
            + ", te damos la bienvenida a tu nuevo asistente de laboratorio, acontinuacin te adjuntamos tus credenciales nuevas: <br/>"
            + "<ul style='list-style-type:disc'>" + "  <li>Usuario: " + correo + "</li>" + "  <li>Contrasea: "
            + passw + "</li>" + "</ul><br/>"
            + "Esperamos que le saque el mejor provecho a esta nueva plataforma.<br/></div>";

    enviocorreo.send_mail(correo, "", "Bienvenido a PIF Patologa", mensajeCorreo);

    return "principal";
}

From source file:org.apache.hadoop.gateway.jetty.JettyHttpsTest.java

@Test
public void testHttps() throws Exception {
    int port = jetty.getConnectors()[0].getLocalPort();
    String url = "https://localhost:" + port + "/";

    System.out.println("Jetty HTTPS listenting on port " + port + ". Press any key to continue.");
    System.in.read();/*from  w w w. j a v a2s  .  c  o m*/

    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManager[] keyManagers = createKeyManagers("jks", "target/test-classes/client-keystore.jks", "horton");
    TrustManager[] trustManagers = createTrustManagers("jks", "target/test-classes/client-truststore.jks",
            "horton");
    ctx.init(keyManagers, trustManagers, new SecureRandom());

    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    SchemeRegistry schemes = new SchemeRegistry();
    schemes.register(new Scheme("https", port, socketFactory));
    ClientConnectionManager cm = new BasicClientConnectionManager(schemes);

    HttpClient client = new DefaultHttpClient(cm);

    HttpGet get = new HttpGet(url);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    client.execute(get).getEntity().writeTo(buffer);
    assertThat(buffer.toString(), equalTo("<html>Hello!</html>"));
}

From source file:jp.go.nict.langrid.management.web.utility.StringUtil.java

/**
 * //w  w  w.j  a v a  2  s .c o  m
 * 
 */
public static String randomPassword(int size) {
    SecureRandom random = new SecureRandom();
    char[] pass = new char[size];
    for (int k = 0; k < pass.length; k++) {
        switch (random.nextInt(3)) {
        case 0: // 'a' - 'z'
            pass[k] = (char) (97 + random.nextInt(26));
            break;
        case 1: // 'A' - 'Z'
            pass[k] = (char) (65 + random.nextInt(26));
            break;
        case 2: // '0' - '9'
            pass[k] = (char) (48 + random.nextInt(10));
            break;
        default:
            pass[k] = 'a';
        }
    }
    return new String(pass);
}

From source file:be.agiv.security.client.SecureConversationClient.java

/**
 * Main constructor. The given location is the same as where the actual
 * business web service is running./*from   w  w  w. j  a  v  a 2 s. c om*/
 * 
 * @param location
 *            the location of the WS-SecureConversation enabled web service.
 */
public SecureConversationClient(String location) {
    this.location = location;
    SecurityTokenService_Service service = SecurityTokenServiceFactory.getInstance();
    this.port = service.getSecurityTokenServicePort();
    BindingProvider bindingProvider = (BindingProvider) this.port;
    bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, location);

    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    this.wsTrustHandler = new WSTrustHandler();
    handlerChain.add(this.wsTrustHandler);
    this.wsAddressingHandler = new WSAddressingHandler();
    handlerChain.add(this.wsAddressingHandler);
    this.wsSecurityHandler = new WSSecurityHandler();
    handlerChain.add(this.wsSecurityHandler);
    handlerChain.add(new LoggingHandler());
    binding.setHandlerChain(handlerChain);

    this.objectFactory = new ObjectFactory();
    this.wssObjectFactory = new be.agiv.security.jaxb.wsse.ObjectFactory();

    this.secureRandom = new SecureRandom();
    this.secureRandom.setSeed(System.currentTimeMillis());
}

From source file:org.sickbeard.SickBeard.java

public SickBeard(String hostname, String port, String api, boolean https, String extraPath, String user,
        String password, boolean trustAll, String trustMe) {
    this.hostname = hostname;
    this.port = port;
    this.extraPath = "/" + extraPath + "/";
    this.path = this.extraPath + "/api/" + api + "/";
    try {/*w  ww  .j  av  a2  s .  c o  m*/
        this.https = https;
        this.scheme = https ? "https" : "http";

        Authenticator.setDefault(new SickAuthenticator(user, password, hostname));
        HostnameVerifier verifier;
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (Exception e) {
        ;
    }
    /***********************************************************
     * ANDROID SPECIFIC START                                  *
     ***********************************************************/
    // start a AsyncTask to try and find the actual api version number
    AsyncTask<Void, Void, CommandsJson> task = new AsyncTask<Void, Void, CommandsJson>() {
        @Override
        protected CommandsJson doInBackground(Void... arg0) {
            try {
                return SickBeard.this.sbGetCommands();
            } catch (Exception e) {
                Log.e("SickBeard", e.getMessage(), e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(CommandsJson result) {
            // do nothing because this is a network error
            if (result == null)
                return;
            try {
                // if we get a version use it
                SickBeard.this.apiVersion = Integer.valueOf(result.api_version);
            } catch (NumberFormatException e) {
                // 2 was the odd float so assume its 2 if we cant get an int
                SickBeard.this.apiVersion = 2;
            }
        }
    };
    task.execute();
    /***********************************************************
     * ANDROID SPECIFIC END                                    *
     ***********************************************************/
}

From source file:com.ery.estorm.zk.RecoverableZooKeeper.java

public RecoverableZooKeeper(String quorumServers, int sessionTimeout, Watcher watcher, int maxRetries,
        int retryIntervalMillis, String identifier) throws IOException {
    // TODO: Add support for zk 'chroot'; we don't add it to the
    // quorumServers String as we should.
    this.zk = new ZooKeeper(quorumServers, sessionTimeout, watcher);
    this.retryCounterFactory = new RetryCounterFactory(maxRetries, retryIntervalMillis);

    if (identifier == null || identifier.length() == 0) {
        // the identifier = processID@hostName
        identifier = ManagementFactory.getRuntimeMXBean().getName();
    }/*from w  w w.j ava  2 s  .c  o m*/
    LOG.info("Process identifier=" + identifier + " connecting to ZooKeeper ensemble=" + quorumServers);
    this.identifier = identifier;
    this.id = Bytes.toBytes(identifier);

    this.watcher = watcher;
    this.sessionTimeout = sessionTimeout;
    this.quorumServers = quorumServers;
    salter = new SecureRandom();
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout,
        int readTimeout) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;/*w w w. ja  v  a2  s. c o m*/
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            //SSLContext.setDefault(ctx);
            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setSSLSocketFactory(ctx.getSocketFactory());

            conn.setRequestProperty("Cookie", cookieStr);
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:graphene.util.crypto.PasswordHash.java

/**
 * Returns a salted PBKDF2 hash of the password.
 * /*from   ww  w  . j a v a 2 s  . c  om*/
 * @param password
 *            the password to hash
 * @return a salted PBKDF2 hash of the password
 */
public String createHash(final char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Generate a random salt
    final SecureRandom random = new SecureRandom();
    final byte[] salt = new byte[SALT_BYTE_SIZE];
    random.nextBytes(salt);

    // Hash the password
    final byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
    // format iterations:salt:hash
    return PBKDF2_ITERATIONS + ":" + toEncoding(salt) + ":" + toEncoding(hash);
}

From source file:learn.encryption.ssl.SSLContext_Https.java

public static SSLContext getSSLContext2(String servercerfile, String clientkeyStore, String clientPass) {
    if (sslContext != null) {
        return sslContext;
    }// w  ww .j  a v a  2  s.  c  om
    try {
        // ??, ??assets
        //InputStream inputStream = App.getInstance().getAssets().open("serverkey.cer");
        InputStream inputStream = new FileInputStream(new File(servercerfile));
        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
        Certificate cer = cerFactory.generateCertificate(inputStream);
        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");//eclipse?jksandroidPKCS12??
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trust", cer);

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        sslContext = SSLContext.getInstance("TLS");

        //?clientKeyStore(android??bks)
        //KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        KeyStore clientKeyStore = KeyStore.getInstance("jks");
        //clientKeyStore.load(App.getInstance().getAssets().open("clientkey.bks"), "123456".toCharArray());
        clientKeyStore.load(new FileInputStream(new File(clientkeyStore)), clientPass.toCharArray());

        // ?clientKeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, clientPass.toCharArray());

        // ?SSLContext  trustManagerFactory.getTrustManagers()
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());//new TrustManager[]{trustManagers}??
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

private static KeyPair generateECDSAKeyPair()
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    ECGenParameterSpec ecSpec = new ECGenParameterSpec("P-256");

    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, new SecureRandom());
    KeyPair pair = g.generateKeyPair();
    return pair;//  w ww. j av a 2 s  . co m
}