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:org.parosproxy.paros.network.SSLConnector.java

public SSLSocketFactory getTunnelSSLSocketFactory(String hostname) {

    //   SSLServerSocketFactory ssf = null;
    // set up key manager to do server authentication

    //   KeyStore ks;
    try {//from ww w  . j  a va2s  .co m
        SSLContext ctx = SSLContext.getInstance(SSL);
        // Normally "SunX509", "IbmX509"...
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        SslCertificateService scs = CachedSslCertifificateServiceImpl.getService();
        KeyStore ks = scs.createCertForHost(hostname);

        kmf.init(ks, SslCertificateService.PASSPHRASE);
        java.security.SecureRandom x = new java.security.SecureRandom();
        x.setSeed(System.currentTimeMillis());
        ctx.init(kmf.getKeyManagers(), null, x);

        SSLSocketFactory tunnelSSLFactory = createDecoratedServerSslSocketFactory(ctx.getSocketFactory());

        return tunnelSSLFactory;

    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException
            | KeyManagementException | InvalidKeyException | NoSuchProviderException | SignatureException
            | IOException e) {
        // Turn into RuntimeException. How to handle this error in a user
        // friendly way?
        throw new RuntimeException(e);
    }
}

From source file:org.pwsafe.passwordsafeswt.dialog.EditDialog.java

private String generatePassword() {
    final String BASE_LETTERS = String.valueOf(PassphraseUtils.LOWERCASE_CHARS);
    final String BASE_DIGITS = String.valueOf(PassphraseUtils.DIGIT_CHARS);
    final String BASE_LETTERS_EASY = "abcdefghjkmnpqrstuvwxyz"; //$NON-NLS-1$
    final String BASE_DIGITS_EASY = "23456789"; //$NON-NLS-1$
    final String BASE_SYMBOLS = "!@#$%^&*()"; //$NON-NLS-1$
    final StringBuilder pwSet = new StringBuilder();

    UserPreferences.reload(); // make sure we have a fresh copy
    final UserPreferences preferenceStore = UserPreferences.getInstance();

    final String passwordLengthStr = preferenceStore.getString(JpwPreferenceConstants.DEFAULT_PASSWORD_LENGTH);
    int passwordLength = 0;
    if (passwordLengthStr != null && passwordLengthStr.trim().length() > 0) {
        passwordLength = Integer.parseInt(passwordLengthStr);
    }/* w  w w  .ja  v  a2s  . com*/
    if (passwordLength <= 0)
        passwordLength = 8; // let's be sensible about this..

    final boolean useLowerCase = preferenceStore.getBoolean(JpwPreferenceConstants.USE_LOWERCASE_LETTERS);
    final boolean useUpperCase = preferenceStore.getBoolean(JpwPreferenceConstants.USE_UPPERCASE_LETTERS);
    final boolean useDigits = preferenceStore.getBoolean(JpwPreferenceConstants.USE_DIGITS);
    final boolean useSymbols = preferenceStore.getBoolean(JpwPreferenceConstants.USE_SYMBOLS);
    final boolean useEasyToRead = preferenceStore.getBoolean(JpwPreferenceConstants.USE_EASY_TO_READ);

    if (useLowerCase) {
        if (useEasyToRead) {
            pwSet.append(BASE_LETTERS_EASY.toLowerCase());
        } else {
            pwSet.append(BASE_LETTERS.toLowerCase());
        }
    }

    if (useUpperCase) {
        if (useEasyToRead) {
            pwSet.append(BASE_LETTERS_EASY.toUpperCase());
        } else {
            pwSet.append(BASE_LETTERS.toUpperCase());
        }
    }

    if (useDigits) {
        if (useEasyToRead) {
            pwSet.append(BASE_DIGITS_EASY);
        } else {
            pwSet.append(BASE_DIGITS);
        }
    }

    if (useSymbols) {
        pwSet.append(BASE_SYMBOLS);
    }

    final StringBuffer sb = new StringBuffer();
    if (pwSet.length() > 0) {
        final SecureRandom rand = new SecureRandom();
        rand.setSeed(System.currentTimeMillis());
        for (int i = 0; i < passwordLength; i++) {
            final int randOffset = rand.nextInt(pwSet.length());
            sb.append(pwSet.charAt(randOffset));
        }
    } else {
        sb.append(Messages.getString("EditDialog.MessageMustEditOptions")); //$NON-NLS-1$
    }

    return sb.toString();

}

From source file:com.facebook.LinkBench.LinkBenchDriver.java

/**
 * Create a new random number generated, optionally seeded to a known
 * value from the config file.  If seed value not provided, a seed
 * is chosen.  In either case the seed is logged for later reproducibility.
 * @param props//from   ww  w.ja va 2s .  co  m
 * @param configKey config key for the seed value
 * @return
 */
private Random createMasterRNG(Properties props, String configKey) {
    long seed;
    if (props.containsKey(configKey)) {
        seed = ConfigUtil.getLong(props, configKey);
        logger.info("Using configured random seed " + configKey + "=" + seed);
    } else {
        seed = System.nanoTime() ^ (long) configKey.hashCode();
        logger.info("Using random seed " + seed + " since " + configKey + " not specified");
    }

    SecureRandom masterRandom;
    try {
        masterRandom = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        logger.warn("SHA1PRNG not available, defaulting to default SecureRandom" + " implementation");
        masterRandom = new SecureRandom();
    }
    masterRandom.setSeed(ByteBuffer.allocate(8).putLong(seed).array());

    // Can be used to check that rng is behaving as expected
    logger.debug("First number generated by master " + configKey + ": " + masterRandom.nextLong());
    return masterRandom;
}

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

private byte[] generateKeyData() {
    try {/*w  w  w.j  ava  2s .co m*/
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
        byte bytes[] = new byte[DESedeKeySpec.DES_EDE_KEY_LEN];
        random.nextBytes(bytes);
        return bytes;
    } catch (Exception e) {
        throw new RuntimeException("Unable to generate secret key", e);
    }
}

From source file:com.feilong.tools.security.symmetric.SymmetricEncryption.java

/**
 * ?.//  w  w  w .j  a v  a  2 s. co m
 * 
 * @param _keyString
 *            
 * @return Key
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @see <a href="http://blog.csdn.net/hbcui1984/article/details/5753083">Linux?AES</a>
 * @see KeyGenerator
 * @see SecureRandom
 */
private Key getKey(String _keyString) throws NoSuchAlgorithmException {
    // KeyGenerator ????????? KeyGenerator ??
    KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);

    // SHA1PRNG: It is just ensuring the random number generated is as close to "truly random" as possible.
    // Easily guessable random numbers break encryption.

    // ???? (RNG) ???
    //TODO
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");

    // SecureRandom??getInstance?setSeed
    //  :windowslinux?
    // javax.crypto.BadPaddingException: Given final block not properly padded
    secureRandom.setSeed(_keyString.getBytes());

    keyGenerator.init(secureRandom);

    Key _key = keyGenerator.generateKey();
    keyGenerator = null;
    return _key;
}

From source file:com.basho.riak.pbc.RiakClient.java

/**
 * helper method to use a reasonable default client id
 * beware, it caches the client id. If you call it multiple times on the same client
 * you get the *same* id (not good for reusing a client with different ids)
 * /*from w  w  w  . j  a  v a 2  s. c  o  m*/
 * @throws IOException
 */
public void prepareClientID() throws IOException {
    Preferences prefs = Preferences.userNodeForPackage(RiakClient.class);

    String clid = prefs.get("client_id", null);
    if (clid == null) {
        SecureRandom sr;
        try {
            sr = SecureRandom.getInstance("SHA1PRNG");
            // Not totally secure, but doesn't need to be
            // and 100% less prone to 30 second hangs on linux jdk5
            sr.setSeed(UUID.randomUUID().getLeastSignificantBits() + new Date().getTime());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] data = new byte[6];
        sr.nextBytes(data);
        clid = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1);
        prefs.put("client_id", clid);
        try {
            prefs.flush();
        } catch (BackingStoreException e) {
            throw new IOException(e.toString());
        }
    }

    setClientID(clid);
}

From source file:de.burlov.amazon.s3.dirsync.DirSync.java

/**
 * //from   w w  w.  j  a v a  2s . co m
 * @param autocreate
 *        'true' wenn fehlende Index/bucket automatisch erstellt werden sollen
 * @throws DirSyncException
 */
private void connect(boolean autocreate) throws DirSyncException {
    if (mainIndex != null) {
        return;
    }
    boolean bucketExists = false;
    try {
        bucketExists = s3Service.isBucketAccessible(bucket);
    } catch (S3ServiceException e1) {
        throw new DirSyncException("Internal error: " + e1.getMessage());
    }
    if (!bucketExists) {
        if (autocreate) {
            /*
             * In 'up' Modus benoetigte Bucket erstellen falls er noch nicht vorhanden ist
             */
            try {
                s3Service.createBucket(bucket, location);
            } catch (S3ServiceException e2) {
                throw new DirSyncException(
                        "Creating bucket '" + bucket + "' failed: " + e2.getLocalizedMessage());
            }
        } else {
            throw new DirSyncException("Bucket not found: " + bucket);
        }
    }
    try {
        mainIndex = (MainIndex) downloadObject(getMainIndexKey(), pbeKey);
    } catch (IOException e) {
        /*
         * Lesen des Indexes fehlgeschlagen, falsches Passwort?
         */
        throw new DirSyncException("Reading main index failed. Are password and S3 login data valid?", e);
    }
    if (mainIndex == null) {
        if (autocreate) {
            /*
             * Noch keine Daten auf dem Server
             */
            mainIndex = new MainIndex();
            /*
             * Schluessel fuer Datenverschluesselung generieren
             */
            SecureRandom srnd = new SecureRandom();
            srnd.setSeed(pbeKey);
            byte[] dataKey = new byte[32];
            srnd.nextBytes(dataKey);
            mainIndex.setEncryptionKey(dataKey);
        } else {
            /*
             * Kein Index gefunden, also keine Daten zum Runterladen
             */
            throw new DirSyncException("No data found");
        }
    }
}

From source file:org.ejbca.util.CertTools.java

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException,
        IllegalStateException, NoSuchProviderException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be 
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;/*from  www .j  a v a2s . c o m*/
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);
    certgen.setSerialNumber(new java.math.BigInteger(serno).abs());
    certgen.setNotBefore(firstDate);
    certgen.setNotAfter(lastDate);
    certgen.setSignatureAlgorithm(sigAlg);
    certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));
    certgen.setIssuerDN(CertTools.stringToBcX509Name(dn));
    certgen.setPublicKey(publicKey);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);
    }

    X509Certificate selfcert = certgen.generate(privKey, provider);

    return selfcert;
}

From source file:org.cesecore.util.CertTools.java

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage,
        Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder,
        List<Extension> additionalExtensions)
        throws CertificateParsingException, IOException, OperatorCreationException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from ww w  .  j  a  v a2s.  c  om
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("RSA was not a known algorithm", e);
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            final String algo = ecpk.getAlgorithm();
            if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
                try {
                    publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECGOST3410 was not a known algorithm", e);
                }
            } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
                try {
                    publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("DSTU4145 was not a known algorithm", e);
                }
            } else {
                try {
                    publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("EC was not a known algorithm", e);
                }
            }
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA1PRNG was not a known algorithm", e);
    }
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e);
    }
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
            CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate,
            CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA || keyusage != 0) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }

    if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        if (privateKeyNotBefore != null) {
            v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore)));
        }
        if (privateKeyNotAfter != null) {
            v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter)));
        }
        certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v));
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {

            ASN1InputStream sAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream aAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) sAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) aAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                sAsn1InputStream.close();
                aAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    // Add any additional
    if (additionalExtensions != null) {
        for (final Extension extension : additionalExtensions) {
            certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue());
        }
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}