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, SecureRandomParameters params)
        throws NoSuchAlgorithmException 

Source Link

Document

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

Usage

From source file:com.github.tojo.session.cookies.SessionInACookieDefaultImpl.java

@Override
public CookieValue encode(SessionData sessionData) throws CipherStrategyException {
    try {//from  w  ww  .  j av  a 2  s. c o  m
        // 1. create session id
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
        byte[] sessionId = new byte[SESSION_ID_LENGTH];
        secureRandom.nextBytes(sessionId);

        // 2. prefix session data with the session id
        byte[] dataWithSessionId = ArrayUtils.addAll(sessionId, sessionData.asBytes());

        // 3. calculate the cookie value
        CookieValue cookieValue = encryptSignAndEncode(dataWithSessionId);

        // 4. hit timeout strategy
        timeoutStrategy.issue(sessionData, cookieValue);

        return cookieValue;
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.offbynull.peernetic.common.identification.IdGenerator.java

/**
 * Constructs a {@link DefaultIdGenerator} using {@link SecureRandom} (with SUN / SHA1PRNG implementation).
 * @param limit maximum value the id generated can be
 * @throws NoSuchAlgorithmException thrown by {@link SecureRandom#getInstance(java.lang.String, java.lang.String) }
 * @throws NoSuchProviderException thrown by {@link SecureRandom#getInstance(java.lang.String, java.lang.String) }
 * @throws NullPointerException if any arguments are {@code null}
 * @throws IllegalArgumentException if limit is 0
 *//*  w w w . j a va 2 s  .  com*/
public IdGenerator(byte[] limit) throws NoSuchAlgorithmException, NoSuchProviderException {
    this(SecureRandom.getInstance("SHA1PRNG", "SUN"), limit);
}

From source file:org.apache.hadoop.crypto.JceAesCtrCryptoCodec.java

@Override
public void setConf(Configuration conf) {
    this.conf = conf;
    provider = conf.get(HADOOP_SECURITY_CRYPTO_JCE_PROVIDER_KEY);
    final String secureRandomAlg = conf.get(HADOOP_SECURITY_JAVA_SECURE_RANDOM_ALGORITHM_KEY,
            HADOOP_SECURITY_JAVA_SECURE_RANDOM_ALGORITHM_DEFAULT);
    try {//  ww  w  .  j  av  a2 s  . co m
        random = (provider != null) ? SecureRandom.getInstance(secureRandomAlg, provider)
                : SecureRandom.getInstance(secureRandomAlg);
    } catch (GeneralSecurityException e) {
        LOG.warn(e.getMessage());
        random = new SecureRandom();
    }
}

From source file:com.offbynull.voip.kademlia.State.java

public State(Address timerAddress, Address graphAddress, Address logAddress, byte[] seed1, byte[] seed2,
        Id baseId, KademliaParameters kademliaParameters, AddressTransformer addressTransformer) {
    Validate.notNull(timerAddress);/*from w  w  w.  j  ava2 s.  c  o  m*/
    Validate.notNull(graphAddress);
    Validate.notNull(logAddress);
    Validate.notNull(seed1);
    Validate.notNull(baseId);
    Validate.notNull(kademliaParameters);
    Validate.notNull(addressTransformer);
    Validate.isTrue(seed1.length >= IdGenerator.MIN_SEED_SIZE);
    Validate.isTrue(seed2.length >= IdGenerator.MIN_SEED_SIZE);
    this.timerAddress = timerAddress;
    this.graphAddress = graphAddress;
    this.logAddress = logAddress;
    idGenerator = new IdGenerator(seed1);

    try {
        secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new IllegalStateException(ex);
    }
    secureRandom.setSeed(seed2);

    this.baseId = baseId;
    this.router = new Router(baseId, kademliaParameters.getBranchStrategy().get(),
            kademliaParameters.getBucketStrategy().get());
    this.maxConcurrentRequestsPerFind = kademliaParameters.getMaxConcurrentRequestsPerFind();

    this.graphHelper = new GraphHelper(baseId, graphAddress, router);

    this.addressTransformer = addressTransformer;
}

From source file:org.apache.hadoop.hbase.io.crypto.aes.CommonsCryptoAES.java

public CommonsCryptoAES(CipherProvider provider) {
    super(provider);
    // The mode for Commons Crypto Ciphers
    cipherMode = provider.getConf().get(CIPHER_MODE_KEY, "AES/CTR/NoPadding");
    // Reads Commons Crypto properties from HBase conf
    props = readCryptoProps(provider.getConf());
    // RNG algorithm
    rngAlgorithm = provider.getConf().get(RNG_ALGORITHM_KEY, "SHA1PRNG");
    // RNG provider, null if default
    String rngProvider = provider.getConf().get(RNG_PROVIDER_KEY);
    try {/*  w w  w  .  j  av  a2s  . co  m*/
        if (rngProvider != null) {
            rng = SecureRandom.getInstance(rngAlgorithm, rngProvider);
        } else {
            rng = SecureRandom.getInstance(rngAlgorithm);
        }
    } catch (GeneralSecurityException e) {
        LOG.warn("Could not instantiate specified RNG, falling back to default", e);
        rng = new SecureRandom();
    }
}

From source file:org.apache.abdera.security.util.KeyHelper.java

public static KeyPair generateKeyPair(String type, int size, String provider)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(type, provider);
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", provider);
    keyGen.initialize(size, random);/*w  w w . j av a  2s  .  co m*/
    random.setSeed(System.currentTimeMillis());
    return keyGen.generateKeyPair();
}

From source file:org.apache.hadoop.hbase.io.crypto.aes.AES.java

public AES(CipherProvider provider) {
    super(provider);
    // The JCE mode for Ciphers
    cipherMode = provider.getConf().get(CIPHER_MODE_KEY, "AES/CTR/NoPadding");
    // The JCE provider, null if default
    cipherProvider = provider.getConf().get(CIPHER_PROVIDER_KEY);
    // RNG algorithm
    rngAlgorithm = provider.getConf().get(RNG_ALGORITHM_KEY, "SHA1PRNG");
    // RNG provider, null if default
    String rngProvider = provider.getConf().get(RNG_PROVIDER_KEY);
    try {/*  w w  w. ja  va  2s .  c om*/
        if (rngProvider != null) {
            rng = SecureRandom.getInstance(rngAlgorithm, rngProvider);
        } else {
            rng = SecureRandom.getInstance(rngAlgorithm);
        }
    } catch (GeneralSecurityException e) {
        LOG.warn("Could not instantiate specified RNG, falling back to default", e);
        rng = new SecureRandom();
    }
}

From source file:de.rrze.idmone.utils.jpwgen.RandomFactory.java

/**
 * Create a two pseudo random generator by utilizing the
 * <em>SecureRandom</em> class provided by SUN. Uses a two step procedure
 * for feeding the generator seed with two separate SecureRandom instances.
 * /*from  ww  w . j av a2s  .  c o  m*/
 * @see http 
 *      ://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html
 * 
 * @param algorithm
 *            The algorithm used for creating the pseudo random generator
 * @param provider
 *            the provider identifier
 * @return a seeded <em>SecureRandom</em>
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
private SecureRandom initSecureRandom(String algorithm, String provider)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    logger.debug("Initializing random with: " + algorithm + " : " + provider);
    if (provider == null)
        provider = PROVIDER_DEFAULT;

    // Create a secure random number generator
    SecureRandom sr = SecureRandom.getInstance(algorithm, provider);

    // Get 1024 random bits
    byte[] bytes = new byte[1024 / 8];
    sr.nextBytes(bytes);

    // Create two secure number generators with the same seed
    int seedByteCount = 10;
    byte[] seed = sr.generateSeed(seedByteCount);

    sr = SecureRandom.getInstance(algorithm, provider);
    sr.setSeed(seed);

    SecureRandom sr2 = SecureRandom.getInstance(algorithm, provider);
    sr2.setSeed(seed);
    return sr2;
}

From source file:de.rrze.idmone.utils.jidgen.random.RandomFactory.java

/**
 * Create a two pseudo random generator by utilizing the
 * <em>SecureRandom</em> class provided by SUN. Uses a two step procedure
 * for feeding the generator seed with two separate SecureRandom instances.
 * /*from  w  ww .j a  v  a  2 s.  c  om*/
 * @see http://java.sun.com/j2se/1.4.2/docs/api/java/security/SecureRandom.html
 * 
 * @param algorithm
 *            The algorithm used for creating the pseudo random generator
 * @param provider
 *            the provider identifier
 * @return a seeded <em>SecureRandom</em>
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
private SecureRandom initSecureRandom(String algorithm, String provider)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    logger.debug(Messages.getString("RandomFactory.INIT") + algorithm + " : " + provider);
    if (provider == null)
        provider = PROVIDER_DEFAULT;

    // Create a secure random number generator
    SecureRandom sr = SecureRandom.getInstance(algorithm, provider);

    // Get 1024 random bits
    byte[] bytes = new byte[1024 / 8];
    sr.nextBytes(bytes);

    // Create two secure number generators with the same seed
    int seedByteCount = 10;
    byte[] seed = sr.generateSeed(seedByteCount);

    sr = SecureRandom.getInstance(algorithm, provider);
    sr.setSeed(seed);

    SecureRandom sr2 = SecureRandom.getInstance(algorithm, provider);
    sr2.setSeed(seed);
    return sr2;
}

From source file:org.lockss.util.urlconn.PermissiveSSLProtocolSocketFactory.java

private static SSLContext createPermissiveSSLContext() {
    try {//www .  j  a v a 2 s  .  c  om
        LockssDaemon daemon = LockssDaemon.getLockssDaemon();
        SecureRandom rng;
        if (daemon.isDaemonRunning()) {
            RandomManager rmgr = daemon.getRandomManager();
            rng = rmgr.getSecureRandom();
        } else {
            rng = SecureRandom.getInstance(RandomManager.DEFAULT_SECURE_RANDOM_ALGORITHM,
                    RandomManager.DEFAULT_SECURE_RANDOM_PROVIDER);
        }
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new PermissiveX509TrustManager(null) }, rng);
        return context;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new HttpClientError(e.toString());
    }
}