Example usage for java.security SecureRandom setSeed

List of usage examples for java.security SecureRandom setSeed

Introduction

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

Prototype

@Override
public void setSeed(long seed) 

Source Link

Document

Reseeds this random object, using the eight bytes contained in the given long seed .

Usage

From source file:ubicrypt.core.UtilsTest.java

@Test
public void readIs() throws Exception {
    final SecureRandom rnd = new SecureRandom();
    rnd.setSeed(System.currentTimeMillis());
    final byte[] key = new byte[3 * (1 << 16)];
    rnd.nextBytes(key);/*from  w  w w. jav a 2s  .c  o  m*/

    final Path path = Files.createTempFile(TestUtils.tmp, "a", "b");
    Utils.write(path, new ByteArrayInputStream(key)).toBlocking().last();

    final byte[] bytes = IOUtils.toByteArray(Utils.readIs(path));
    final byte[] bytes2 = IOUtils.toByteArray(Files.newInputStream(path));
    assertThat(bytes.length).isEqualTo(bytes2.length);
    for (int i = 0; i < bytes.length; i++) {
        assertThat(bytes[i]).isEqualTo(bytes2[i]);
    }
}

From source file:org.apache.geronimo.crypto.ConfiguredEncryption.java

public ConfiguredEncryption(String location) throws IOException {
    File keyFile = new File(location);
    ObjectInputStream oin = null;
    if (keyFile != null) {
        if (keyFile.exists()) {
            FileInputStream fi = new FileInputStream(keyFile);
            try {
                oin = new ObjectInputStream(fi);
                spec = (SecretKeySpec) oin.readObject();
            } catch (ClassNotFoundException e) {
                log.error("Unable to read object or class not found: ", e);
            } finally {
                if (oin != null)
                    oin.close();//from  w  w  w .j a  v a 2 s.  com
                if (fi != null)
                    fi.close();
            }
        } else {
            SecureRandom random = new SecureRandom();
            random.setSeed(System.currentTimeMillis());
            byte[] bytes = new byte[16];
            random.nextBytes(bytes);
            spec = new SecretKeySpec(bytes, "AES");
            File dir = keyFile.getParentFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            if (!dir.exists() || !dir.isDirectory()) {
                throw new IllegalStateException("Could not create directory for secret key spec: " + dir);
            }
            FileOutputStream out = new FileOutputStream(keyFile);
            try {
                ObjectOutputStream oout = new ObjectOutputStream(out);
                try {
                    oout.writeObject(spec);
                    oout.flush();
                } finally {
                    oout.close();
                }
            } finally {
                out.close();
            }
            log.info("Generate a new configured encryption password: " + spec.getEncoded().toString());
        }
    }
}

From source file:com.snaplogic.snaps.uniteller.CustomUFSSecurityMgr.java

@Override
public String generatePassword() throws UFSSecurityMgrException {
    String id = null;//from www. java  2s.c om
    try {
        byte[] byteArr = new byte[256];
        SecureRandom secureRnd = SecureRandom.getInstance(ENC_ALG);
        secureRnd.setSeed(new Long(System.currentTimeMillis()).toString().getBytes());
        MessageDigest md = MessageDigest.getInstance(DS_ALG);
        secureRnd.nextBytes(byteArr);
        md.update(byteArr);
        md.update(new Long(System.currentTimeMillis()).toString().getBytes());
        byteArr = md.digest();
        id = Base64.encode(byteArr, 0, 12);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new UFSSecurityMgrException(e.getMessage());
    }
    return id;
}

From source file:org.alfresco.encryption.KeyStoreTests.java

public byte[] generateKeyData() throws NoSuchAlgorithmException {
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(System.currentTimeMillis());
    byte bytes[] = new byte[DESedeKeySpec.DES_EDE_KEY_LEN];
    random.nextBytes(bytes);/*from ww  w  .j  a v a 2 s .com*/
    return bytes;
}

From source file:org.globusonline.nexus.GlobusOnlineRestClient.java

private long generateNonce() {
    SecureRandom sr = null;
    try {//from w  w  w . j  a va  2  s.  com
        sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] bytes = new byte[1024 / 8];
        sr.nextBytes(bytes);
        int seedByteCount = 10;
        byte[] seed = sr.generateSeed(seedByteCount);
        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return sr.nextLong();
}

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  ww w  .  j a v a 2  s  . com
 * @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: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.
 * /* www  . 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:org.apache.usergrid.persistence.Schema.java

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
    keyGenerator.init(128, sr); // 192 and 256 bits may not be available
    SecretKey secretKey = keyGenerator.generateKey();
    return secretKey.getEncoded();
}

From source file:de.fhg.fokus.hss.server.zh.HSSzhOperationsImpl.java

/**
 * This method generates the authentication vectors sized by given paramter.
 * @return a list of Authentication vectors
 *//*from  ww w .j  av  a  2s .com*/
public ArrayList generateAuthenticationVectors() {
    LOGGER.debug("entering");

    ArrayList vectorList = null;
    try {

        vectorList = new ArrayList(numberAuthItems.intValue());

        HexCoDec codec;
        codec = new HexCoDec();
        byte[] secretKey = codec.decode(impi.getSkey());
        byte[] amf = codec.decode(impi.getAmf());

        // op and generate opC   
        byte[] op = codec.decode(impi.getOperatorId());
        byte[] opC = Milenage.generateOpC(secretKey, op);

        String authScheme = impi.getAuthScheme();
        Inet4Address ip = impi.getIP();
        byte[] sqn = codec.decode(impi.getSqn());

        if (authScheme.equalsIgnoreCase("Digest-MD5")) {
            // Authentication Scheme is Digest-MD5
            LOGGER.debug("Auth-Scheme is Digest-MD5");
            SecureRandom randomAccess = SecureRandom.getInstance("SHA1PRNG");

            for (long ix = 0; ix < numberAuthItems; ix++) {
                byte[] randBytes = new byte[16];
                randomAccess.setSeed(System.currentTimeMillis());
                randomAccess.nextBytes(randBytes);

                secretKey = codec.decodePassword(impi.getSkey()).getBytes();

                AuthenticationVector aVector = new AuthenticationVector(authScheme, randBytes, secretKey);
                vectorList.add(aVector);
            }
            impi.setSqn(codec.encode(sqn));
            HibernateUtil.getCurrentSession().update(impi);
        } else if (authScheme.equalsIgnoreCase("Digest-AKAv1-MD5")
                || authScheme.equalsIgnoreCase("Digest-AKAv2-MD5")) {
            // We have AKAv1 or AKAv2
            LOGGER.debug("Auth-Scheme is Digest-AKA");

            for (long ix = 0; ix < numberAuthItems; ix++) {
                sqn = DigestAKA.getNextSQN(sqn, HSSProperties.IND_LEN);
                byte[] copySqnHe = new byte[6];
                int k = 0;
                for (int i = 0; i < 6; i++, k++) {
                    copySqnHe[k] = sqn[i];
                }

                vectorList.add(DigestAKA.getAuthenticationVector(authScheme, secretKey, opC, amf, copySqnHe));
            }
            impi.setSqn(codec.encode(sqn));
            HibernateUtil.getCurrentSession().update(impi);
        }

    } catch (NoSuchAlgorithmException e) {
        LOGGER.error(this, e);
    } catch (InvalidKeyException e) {
        LOGGER.error(this, e);
    } catch (Exception e) {
        // Check impi
        if (impi.getAmf() == null) {
            throw new NullPointerException("Missing AMF value.");
        }

        if (impi.getSkey() == null) {
            throw new NullPointerException("Missing Secret Key value.");
        }

        if (impi.getAuthScheme() == null) {
            throw new NullPointerException("Missing Authentication Scheme.");
        }

        if (impi.getOperatorId() == null) {
            throw new NullPointerException("Missing Operator ID.");
        }
    }

    LOGGER.debug("exiting");
    return vectorList;
}

From source file:org.parosproxy.paros.network.SSLConnector.java

public SSLSocketFactory getClientSocketFactory(String type) {
    // Trust all invalid server certificate
    TrustManager[] trustMgr = new TrustManager[] { new RelaxedX509TrustManager() };

    try {/*  w ww.j  a v  a2 s.  c  om*/
        SSLContext sslContext = SSLContext.getInstance(type);
        java.security.SecureRandom x = new java.security.SecureRandom();
        x.setSeed(System.currentTimeMillis());
        if (relaxedTrust) {
            sslContext.init(null, trustMgr, x);
        } else {
            sslContext.init(null, null, x);
        }
        clientSSLSockFactory = createDecoratedClientSslSocketFactory(sslContext.getSocketFactory());
        HttpsURLConnection.setDefaultSSLSocketFactory(clientSSLSockFactory);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    return clientSSLSockFactory;

}