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:com.cfs.util.AESCriptografia.java

public String gerarChaveRandomica() {
    String chave = null;/*w w  w  .  j av a2s  .c  o  m*/
    try {
        /* Cria o gerador de chaves */
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        /* Inicializa o gerador de chaves */
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        /* Cria uma chave */
        SecretKey key = keygen.generateKey();
        /* Captura a chave na forma de bytes */
        byte[] buffer = key.getEncoded();
        /* Codifica a chave gerada */
        byte[] chaveGerada = Base64.encodeBase64(buffer);
        /* Converte a chave para texto */
        chave = new String(chaveGerada, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    /* Retorna a chave */
    return chave;
}

From source file:ch.itemis.xdocker.lib.TestDockerClient.java

@Test
public void execStart() throws Exception {
    String containerName = "generated_serano" + new SecureRandom().nextInt();
    CreateContainerResponse container = dockerClient.createContainerCmd("busybox").withCmd("ls")
            .withName(containerName).exec();
    assertNotNull(container);//from w  w  w .  java2s. c o  m
    assertNotNull(container.getId());

    InputStream response = dockerClient.execStartCmd(container.getId()).exec(null);
    assertNotNull(response);

    List<String> res = IOUtils.readLines(response);
    for (String string : res) {
        System.out.println(string);
    }
}

From source file:org.sample.TimeController.java

@RequestMapping(method = RequestMethod.GET, value = { "/tick" })
public ModelAndView get() throws Exception {
    Connection connection = jmsFactory.createConnection();
    Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    SecureRandom srandom = new SecureRandom();
    String rand = new BigInteger(176, srandom).toString(32);
    String q = Long.toString(System.currentTimeMillis()) + "-" + rand;
    Destination destination = jmsSession.createQueue(q);

    Timer timer = new Timer();
    long delay = 1 * 1000;
    timer.schedule(new TickTask(jmsSession, destination), 0, delay);

    ModelAndView mav = new ModelAndView("client");
    mav.addObject("queue", destination.toString());
    return mav;//w w w .  ja  v a 2  s .c o  m
}

From source file:com.zimbra.cs.account.TrustedTokenKey.java

TrustedTokenKey(long version, byte[] key) throws ServiceException {
    mVersion = version;//from   w  w  w .  ja  v  a  2 s .  co  m
    mCreated = System.currentTimeMillis();
    if (key != null) {
        mKey = key;
    } else {
        SecureRandom random = new SecureRandom();
        mKey = new byte[KEY_SIZE_BYTES];
        random.nextBytes(mKey);
    }
}

From source file:client.lib.Client.java

public Client() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            X509Certificate[] myTrustedAnchors = new X509Certificate[0];
            return myTrustedAnchors;
        }/* www  .  j ava 2  s .c  om*/

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());

    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    http2Client = new OkHttpClient();
    http2Client.setSslSocketFactory(sslSocketFactory);
    http2Client.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    httpClient = http2Client.clone();

    httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
    http2Client.setProtocols(Arrays.asList(Protocol.HTTP_2));
}

From source file:RSA.java

/** Generate a new public and private key set. */
public synchronized void generateKeys() {
    SecureRandom r = new SecureRandom();
    BigInteger p = new BigInteger(bitlen / 2, 100, r);
    BigInteger q = new BigInteger(bitlen / 2, 100, r);
    n = p.multiply(q);/*ww w. j a  v a2s.com*/
    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.cloud.utils.crypt.RSAHelper.java

public static String encryptWithSSHPublicKey(String sshPublicKey, String content) {
    String returnString = null;//www .  java  2  s  .  co  m
    try {
        RSAPublicKey publicKey = readKey(sshPublicKey);
        Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey, new SecureRandom());
        byte[] encrypted = cipher.doFinal(content.getBytes());
        returnString = Base64.encodeBase64String(encrypted);
    } catch (Exception e) {
    }

    return returnString;
}

From source file:com.zimbra.cs.account.ExtAuthTokenKey.java

ExtAuthTokenKey(long version, byte[] key) throws ServiceException {
    this.version = version;
    created = System.currentTimeMillis();
    if (key != null) {
        this.key = key;
    } else {//from ww  w .  j  a  v  a 2 s  .  co m
        SecureRandom random = new SecureRandom();
        this.key = new byte[KEY_SIZE_BYTES];
        random.nextBytes(this.key);
    }
}

From source file:com.voa.weixin.utils.HttpUtils.java

/**
 * httpspost?//from   ww w . j  av  a 2 s . com
 * 
 * @param url
 * @param param
 * @return
 * @throws Exception
 */
private static String doHttps(String url, String param, String method) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;
    String rsp = null;
    byte[] content = param.getBytes("utf-8");
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), method, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
        } catch (Exception e) {
            throw e;
        }
        try {
            out = conn.getOutputStream();
            if (StringUtils.isNotBlank(param))
                out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            throw e;
        }

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

    return rsp;
}

From source file:net.jarcec.sqoop.data.gen.mr.GeneratorMapper.java

@Override
protected void map(LongWritable key, LongWritable value, Context context)
        throws IOException, InterruptedException {
    long from = key.get();
    long to = value.get();

    random = new SecureRandom();
    decimal = new DecimalFormat("###.###");
    date = new SimpleDateFormat("yyyy-MM-dd");
    time = new SimpleDateFormat("HH:mm:ss");
    datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String[] types = context.getConfiguration().get(Constants.TYPES).split(",");
    String[] values = new String[types.length];

    for (long i = from; i < to; i++) {
        context.progress();/*from   www. ja va 2s  . c o  m*/

        int y = 0;
        for (String type : types) {

            if ("id".equals(type)) {
                values[y] = String.valueOf(i);
            } else if ("s50".equals(type)) {
                values[y] = generateString(50);
            } else if ("i".equals(type)) {
                values[y] = generateInteger();
            } else if ("f".equals(type)) {
                values[y] = generateFloat(250, 31);
            } else if ("d".equals(type)) {
                values[y] = generateDate();
            } else if ("t".equals(type)) {
                values[y] = generateTime();
            } else if ("dt".equals(type)) {
                values[y] = generateDateTime();
            } else if ("s255".equals(type)) {
                values[y] = generateString(255);
            } else {
                throw new RuntimeException("Unknown type: " + type);
            }

            y++;
        }

        context.write(new Text(StringUtils.join(values, ",")), NullWritable.get());
    }
}