Tabnine Logo
SecureRandom
Code IndexAdd Tabnine to your IDE (free)

How to use
SecureRandom
in
java.security

Best Java code snippets using java.security.SecureRandom (Showing top 20 results out of 22,473)

Refine searchRefine arrow

  • SSLContext
  • HttpsURLConnection
  • Random
  • BigInteger
  • IvParameterSpec
  • KeyStore
  • TrustManagerFactory
  • KeyManagerFactory
  • URL
  • AlgorithmParameters
origin: square/okhttp

 private static SSLContext sslContext(String keystoreFile, String password)
   throws GeneralSecurityException, IOException {
  KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
  try (InputStream in = new FileInputStream(keystoreFile)) {
   keystore.load(in, password.toCharArray());
  }
  KeyManagerFactory keyManagerFactory =
    KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keystore, password.toCharArray());

  TrustManagerFactory trustManagerFactory =
    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keystore);

  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(
    keyManagerFactory.getKeyManagers(),
    trustManagerFactory.getTrustManagers(),
    new SecureRandom());

  return sslContext;
 }
}
origin: spring-projects/spring-framework

public AlternativeJdkIdGenerator() {
  SecureRandom secureRandom = new SecureRandom();
  byte[] seed = new byte[8];
  secureRandom.nextBytes(seed);
  this.random = new Random(new BigInteger(seed).longValue());
}
origin: pentaho/pentaho-kettle

/**
 * Constructor. Initializes random generator, attempting first to use SecureRandom, then failing over to Random.
 */
public UUID4Util() {
 try {
  random = SecureRandom.getInstance( "SHA1PRNG", "SUN" );
 } catch ( Exception e ) {
  random = new Random();
 }
}
origin: springside/springside4

/**
 * 使用性能更好的SHA1PRNG, Tomcat的sessionId生成也用此算法.
 * 
 * 但JDK7中,需要在启动参数加入 -Djava.security=file:/dev/./urandom (中间那个点很重要)
 * 
 * 详见:《SecureRandom的江湖偏方与真实效果》http://calvin1978.blogcn.com/articles/securerandom.html
 */
public static SecureRandom secureRandom() {
  try {
    return SecureRandom.getInstance("SHA1PRNG");
  } catch (NoSuchAlgorithmException e) {// NOSONAR
    return new SecureRandom();
  }
}
origin: alibaba/nacos

  @Override
  public void run() {
    SecureRandom random = new SecureRandom(); // Get the real random seed from /dev/random
    queue.add(random.nextLong());
  }
};
origin: stackoverflow.com

KeyStore clientStore = KeyStore.getInstance("PKCS12");
   clientStore.load(new FileInputStream("test.p12"), "testPass".toCharArray());
   KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
   kmf.init(clientStore, "testPass".toCharArray());
   KeyManager[] kms = kmf.getKeyManagers();
   KeyStore trustStore = KeyStore.getInstance("JKS");
   trustStore.load(new FileInputStream("cacerts"), "changeit".toCharArray());
   TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
   tmf.init(trustStore);
   TrustManager[] tms = tmf.getTrustManagers();
   SSLContext sslContext = null;
   sslContext = SSLContext.getInstance("TLS");
   sslContext.init(kms, tms, new SecureRandom());
   HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
   URL url = new URL("https://www.testurl.com");
   HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
origin: knowm/XChange

 SSLContext sslContext = SSLContext.getInstance("TLS");
 X509TrustManager[] xtmArray = new X509TrustManager[] {xtm};
 sslContext.init(null, xtmArray, new java.security.SecureRandom());
 HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
 HttpsURLConnection.setDefaultHostnameVerifier(hnv);
 HttpsURLConnection httpsUrlConn = (HttpsURLConnection) (new URL(serverUrl)).openConnection();
 httpsUrlConn.setRequestMethod("POST");
 conn = httpsUrlConn;
} else {
 URL url = new URL(serverUrl);
 conn = url.openConnection();
origin: wuyouzhuguli/FEBS-Shiro

String urlNameString = url + "?" + param;
try {
  SSLContext sc = SSLContext.getInstance(SSL);
  sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
  URL console = new URL(urlNameString);
  HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
  conn.setRequestProperty(ACCEPT, "*/*");
  conn.setRequestProperty(CONNECTION, CONNECTION_VALUE);
  conn.setRequestProperty(USER_AGENT, USER_AGENT_VALUE);
  conn.setRequestProperty(ACCEPT_CHARSET, UTF8);
  conn.setRequestProperty(CONTENTTYPE, UTF8);
  conn.setDoInput(true);
  conn.setSSLSocketFactory(sc.getSocketFactory());
  conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
  conn.connect();
origin: jmdhappy/xxpay-master

public static byte[] httpsRequestByte(String requestUrl, String requestMethod, String outputStr) {
  try {
    TrustManager[] tm = { new JEEWeiXinX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL url = new URL(requestUrl);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setSSLSocketFactory(ssf);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod(requestMethod);
origin: square/okhttp

private void processHandshakeFailure(Socket raw) throws Exception {
 SSLContext context = SSLContext.getInstance("TLS");
 context.init(null, new TrustManager[] {UNTRUSTED_TRUST_MANAGER}, new SecureRandom());
 SSLSocketFactory sslSocketFactory = context.getSocketFactory();
 SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(
   raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
 try {
  socket.startHandshake(); // we're testing a handshake failure
  throw new AssertionError();
 } catch (IOException expected) {
 }
 socket.close();
}
origin: stackoverflow.com

SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
URL url = new URL("https://mms.nw.ru");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new HostnameVerifier() {
  @Override
  public boolean verify(String arg0, SSLSession arg1) {
origin: google/data-transfer-project

private SSLSocketFactory getSocketFactory() throws GeneralSecurityException, IOException {
 KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
 KeyStore keyStore = KeyStore.getInstance("PKCS12");
 InputStream keyInput = new FileInputStream(pathToPkcs12File);
 keyStore.load(keyInput, password.toCharArray());
 keyInput.close();
 keyManagerFactory.init(keyStore, password.toCharArray());
 SSLContext context = SSLContext.getInstance("TLS");
 context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
 return context.getSocketFactory();
}
origin: TommyLemon/APIJSON

try {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  keyStore.load(null);
  int index = 0;
  for (InputStream certificate : certificates) {
  SSLContext sslContext = SSLContext.getInstance("TLS");
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStore);
  sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), new SecureRandom());
  SSLSocketFactory socketFactory = sslContext.getSocketFactory();
  return socketFactory;
} catch (Exception e) {
origin: stackoverflow.com

 import java.security.SecureRandom;
import java.math.BigInteger;

public final class SessionIdentifierGenerator {
 private SecureRandom random = new SecureRandom();

 public String nextSessionId() {
  return new BigInteger(130, random).toString(32);
 }
}
origin: ltsopensource/light-task-scheduler

private static HttpURLConnection getConnection(URL url, String method, String ctype, Map<String, String> headerMap) throws IOException {
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  if (conn instanceof HttpsURLConnection) {
    HttpsURLConnection connHttps = (HttpsURLConnection) conn;
    if (ignoreSSLCheck) {
      try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[]{new TrustAllTrustManager()}, new SecureRandom());
        connHttps.setSSLSocketFactory(ctx.getSocketFactory());
        connHttps.setHostnameVerifier(new HostnameVerifier() {
          public boolean verify(String hostname, SSLSession session) {
            return true;
origin: stackoverflow.com

 OkHttpClient client = new OkHttpClient();
KeyStore keyStore = readKeyStore(); //your method to obtain KeyStore
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "keystore_pass".toCharArray());
sslContext.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(), new SecureRandom());
client.setSslSocketFactory(sslContext.getSocketFactory());
origin: wildfly/wildfly

private Random getRandom() {
  if (useSecureRandom) {
    return new SecureRandom();
  } else {
    return new Random();
  }
}
origin: apache/nifi

  trustStore.load(trustStoreStream, truststorePasswd);
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
final SSLContext ctx = SSLContext.getInstance(protocol);
ctx.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());
origin: stackoverflow.com

 static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static SecureRandom rnd = new SecureRandom();

String randomString( int len ){
  StringBuilder sb = new StringBuilder( len );
  for( int i = 0; i < len; i++ ) 
   sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
  return sb.toString();
}
origin: springside/springside4

@Test
public void getRandom() {
  System.out.println(RandomUtil.secureRandom().nextInt());
  System.out.println(RandomUtil.threadLocalRandom().nextInt());
}
java.securitySecureRandom

Javadoc

This class generates cryptographically secure pseudo-random numbers. It is best to invoke SecureRandom using the default constructor. This will provide an instance of the most cryptographically strong provider available:
SecureRandom sr = new SecureRandom(); 
byte[] output = new byte[16]; 
sr.nextBytes(output);

The default algorithm is defined by the first SecureRandomSpiprovider found in the installed security providers. Use Securityto install custom SecureRandomSpi providers.

Note that the output of a SecureRandom instance should never be relied upon to be deterministic. For deterministic output from a given input, see MessageDigest which provides one-way hash functions. For deriving keys from passwords, see javax.crypto.SecretKeyFactory.

Seeding SecureRandom may be insecure

A seed is an array of bytes used to bootstrap random number generation. To produce cryptographically secure random numbers, both the seed and the algorithm must be secure.

By default, instances of this class will generate an initial seed using an internal entropy source, such as /dev/urandom. This seed is unpredictable and appropriate for secure use.

Using the #SecureRandom(byte[]) or calling #setSeed may completely replace the cryptographically strong default seed causing the instance to return a predictable sequence of numbers unfit for secure use. Due to variations between implementations it is not recommended to use setSeed at all.

Most used methods

  • <init>
    Constructs a new seeded SecureRandom that uses the default algorithm. Seeding SecureRandom may be in
  • nextBytes
  • getInstance
  • nextInt
  • nextLong
  • setSeed
    Seeds this SecureRandom instance with the specified seed. Seeding SecureRandom may be insecure.
  • generateSeed
    Generates and returns the specified number of seed bytes, computed using the seed generation algorit
  • nextDouble
  • getProvider
    Returns the provider associated with this SecureRandom.
  • getAlgorithm
    Returns the name of the algorithm of this SecureRandom.
  • nextBoolean
  • getSeed
    Generates and returns the specified number of seed bytes, computed using the seed generation algorit
  • nextBoolean,
  • getSeed,
  • nextFloat,
  • getInstanceStrong,
  • ints,
  • nextGaussian,
  • doubles,
  • longs,
  • next

Popular in Java

  • Making http post requests using okhttp
  • getApplicationContext (Context)
  • startActivity (Activity)
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • Table (com.google.common.collect)
    A collection that associates an ordered pair of keys, called a row key and a column key, with a sing
  • HttpServer (com.sun.net.httpserver)
    This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number a
  • Thread (java.lang)
    A thread is a thread of execution in a program. The Java Virtual Machine allows an application to ha
  • DecimalFormat (java.text)
    A concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features desig
  • Collections (java.util)
    This class consists exclusively of static methods that operate on or return collections. It contains
  • Table (org.hibernate.mapping)
    A relational table
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now