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) throws NoSuchAlgorithmException 

Source Link

Document

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

Usage

From source file:org.apache.lucene.gdata.storage.IDGenerator.java

/** 
 * Constructs a new ID generator. with a fixed capacity of prebuild ids. The 
 * default capacity is 10. Every given parameter less than 10 will be 
 * ignored. //from w  ww. ja v a  2 s  .  c  om
 *  
 * @param capacity - 
 *            capacity of the prebuild id queue 
 * @throws NoSuchAlgorithmException - 
 *             if the algorithm does not exist 
 */
public IDGenerator(int capacity) throws NoSuchAlgorithmException {

    this.secureRandom = SecureRandom.getInstance("SHA1PRNG");
    this.mdigest = MessageDigest.getInstance("SHA-1");
    this.blockingQueue = new ArrayBlockingQueue<String>(
            (capacity < DEFAULT_CAPACITY ? DEFAULT_CAPACITY : capacity), false);
    startIDProducer();

}

From source file:com.networknt.utility.HashUtil.java

private static String getSalt() throws NoSuchAlgorithmException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    byte[] salt = new byte[16];
    sr.nextBytes(salt);/*from w  w w. jav  a  2s  .  c  om*/
    return Arrays.toString(salt);
}

From source file:org.zanata.dao.AccountDAO.java

public static String createSaltedApiKey(String username) {
    try {/* w ww . ja va 2s. c  o m*/
        byte[] salt = new byte[16];
        SecureRandom.getInstance("SHA1PRNG").nextBytes(salt);
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] name = username.getBytes("UTF-8");

        // add salt
        byte[] salted = new byte[name.length + salt.length];
        System.arraycopy(name, 0, salted, 0, name.length);
        System.arraycopy(salt, 0, salted, name.length, salt.length);

        // generate md5 digest
        md5.reset();
        byte[] digest = md5.digest(salted);

        return new String(PasswordUtil.encodeHex(digest));

    } catch (Exception exc) {
        throw new RuntimeException(exc);
    }

}

From source file:info.guardianproject.cacert.CustomTrust.java

public CustomTrust(Context context, int rawResource, String password) throws IOException, KeyStoreException,
        KeyManagementException, NoSuchAlgorithmException, CertificateException {

    // Setup the SSL context to use the truststore
    ssl_ctx = SSLContext.getInstance("TLS");

    // Setup truststore
    KeyStore ksCACert = KeyStore.getInstance("BKS");
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    InputStream trustStoreStream = context.getResources().openRawResource(rawResource);
    ksCACert.load(trustStoreStream, password.toCharArray());

    //init factory with custom cacert
    trustManagerFactory.init(ksCACert);/*from www . ja  v  a2s  .  c  om*/
    Log.d("SSL", "CACerts " + ksCACert.size());
    Log.d("SSL", "trustManagerFactory " + trustManagerFactory.getTrustManagers().length);

    // Setup client keystore
    /*
    KeyStore keyStore = KeyStore.getInstance("BKS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    InputStream keyStoreStream = context.getResources().openRawResource(R.raw.clientkeystore);
    keyStore.load(keyStoreStream, "testtest".toCharArray());
    keyManagerFactory.init(keyStore, "testtest".toCharArray());
    Log.d("SSL", "Key " + keyStore.size());
            
    Log.d("SSL", "keyManagerFactory " + keyManagerFactory.getKeyManagers().length);
    */

    //nothing implemented yet
    SecureRandom secRand = SecureRandom.getInstance(RANDOM_ALGORITHM);

    ssl_ctx.init(null, trustManagerFactory.getTrustManagers(), secRand);

    socketFactory = (SSLSocketFactory) ssl_ctx.getSocketFactory();

}

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

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

From source file:org.chililog.server.common.CryptoUtils.java

/**
 * <p>//ww  w . j a  va  2  s  .c  om
 * From a password, a number of iterations and a salt, returns the corresponding hash. For convenience, the salt is
 * stored within the hash.
 * </p>
 * 
 * <p>
 * This convention is used: <code>base64(hash(plainTextValue + salt)+salt)</code>
 * </p>
 * 
 * @param plainTextValue
 *            String The password to encrypt
 * @param salt
 *            byte[] The salt. If null, one will be created on your behalf.
 * @return String The hash password
 * @throws ChiliLogException
 *             if SHA-512 is not supported or UTF-8 is not a supported encoding algorithm
 */
public static String createSHA512Hash(String plainTextValue, byte[] salt) throws ChiliLogException {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        // Salt generation 64 bits long
        salt = new byte[8];
        random.nextBytes(salt);

        return createSHA512Hash(plainTextValue, salt, true);
    } catch (Exception ex) {
        throw new ChiliLogException(ex, "Error attempting to hash passwords. " + ex.getMessage());
    }
}

From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return//from w w w . j a  v a 2  s.  c  o  m
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Security.addProvider(new BouncyCastleProvider());
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifier(pubKey.getEncoded()));
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth,
                KeyPurposeId.anyExtendedKeyUsage };
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE,
                new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

From source file:org.apache.cloudstack.framework.security.keys.KeysManagerImpl.java

private static String getBase64EncodedRandomKey(int nBits) {
    SecureRandom random;/*from  w ww .j a  v a2s  .  c om*/
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
        byte[] keyBytes = new byte[nBits / 8];
        random.nextBytes(keyBytes);
        return Base64.encodeBase64URLSafeString(keyBytes);
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("Unhandled exception: ", e);
    }
    return null;
}

From source file:com.sk89q.craftapi.streaming.StreamingServerClient.java

/**
 * Construct the instance./*from w  w  w  .  j  av a 2  s .c om*/
 * 
 * @param server
 * @param socket
 */
public StreamingServerClient(StreamingServer server, Socket socket) throws Throwable {
    this.server = server;
    this.socket = socket;

    random = SecureRandom.getInstance("SHA1PRNG");
    challenge = new byte[32];
    random.nextBytes(challenge);

    InputStreamReader inReader = new InputStreamReader(socket.getInputStream(), "utf-8");
    in = new BufferedReader(inReader);
    out = new PrintStream(socket.getOutputStream(), true, "utf-8");
}

From source file:piecework.security.concrete.ExampleBouncyCastleEncryptionService.java

@PostConstruct
public void init() throws GeneralSecurityException, UnsupportedEncodingException {
    String encryptionPseudoRandomGenerator = environment.getProperty("encryption.pseudorandom.generator");
    if (StringUtils.isNotEmpty(encryptionPseudoRandomGenerator))
        this.random = SecureRandom.getInstance(encryptionPseudoRandomGenerator);
    else/*  w w w  . j a va 2  s .c om*/
        this.random = new SecureRandom();

    String seed = environment.getProperty("encryption.key.seed");
    if (StringUtils.isNotEmpty(seed))
        this.random.setSeed(Base64.decode(seed.getBytes("UTF-8")));
}