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.intel.diceros.test.securerandom.DRNGTest.java

@Override
public void performTest() throws Exception {
    SecureRandom random = SecureRandom.getInstance("DRNG", "DC");
    random.nextDouble();/*  w w  w. j  a  v a2s .c  om*/
    byte[] bytes = new byte[65536];
    random.nextBytes(bytes);

    final int[] epsilon = bytes2Ints(bytes);
    testFrequency(epsilon);
    testBlockFrequency(epsilon, 10);
    testRuns(epsilon);
    testLongestRunOfOnes(epsilon);
    testRank(epsilon);
    testDiscreteFourierTransform(epsilon);
    testNonOverlappingTemplateMatching(epsilon, 4);
    testOverlappingTemplateMatchings(epsilon, 9);
    testUniversal(epsilon);
    testLinearComplexity(epsilon, 1000);
    testSerial(epsilon, 2);
    testApproximateEntropy(epsilon, 2);
    testCumulativeSums(epsilon);
    testRandomExcursions(epsilon);
    testRandomExcursionsVariant(epsilon);
}

From source file:org.latticesoft.util.common.CryptoHelper.java

public String encode(String input) {
    if (this.keyPair == null || input == null || input.length() == 0) {
        return "";
    }/*w  ww . j  a v a2  s .  c o m*/
    int index = 0;
    int diff = 0;
    StringBuffer sb = new StringBuffer();
    String algor = this.getInstanceAlgorithm();
    PublicKey pubKey = null;
    SecureRandom srand = null;
    Cipher rsaEnc = null;
    ByteArrayOutputStream baos = null;
    DataOutputStream dos = null;
    byte[] data = input.getBytes();
    int bufferSize = strength / 32;
    byte[] buffer = new byte[bufferSize];
    byte[] tmp = null;
    String output = null;

    try {
        pubKey = this.keyPair.getPublic();
        srand = SecureRandom.getInstance(this.secureRandomAlgorithm, this.secureRandomProviderName);
        rsaEnc = Cipher.getInstance(algor, this.providerName);
        rsaEnc.init(Cipher.ENCRYPT_MODE, pubKey, srand);

        baos = new ByteArrayOutputStream();
        dos = new DataOutputStream(baos);
        while (index < data.length) {
            diff = data.length - index;
            if (diff > buffer.length) {
                diff = buffer.length;
            }
            NumeralUtil.resetByteArray(buffer);
            System.arraycopy(data, index, buffer, 0, diff);
            tmp = rsaEnc.doFinal(buffer, 0, buffer.length);
            if (tmp != null) {
                dos.writeInt(tmp.length);
                dos.write(tmp);
                NumeralUtil.resetByteArray(tmp);
            }
            tmp = null;//*/
            index += diff;
        }
        output = NumeralUtil.toHexString(baos.toByteArray());
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error in encryption", e);
        }
    }
    return output;
}

From source file:org.wso2.carbon.identity.test.common.testng.utils.ReadCertStoreSampleUtil.java

public static KeyPair getSampleKeyPair() throws CertificateException, NoSuchAlgorithmException, IOException,
        InvalidKeyException, KeyStoreException, NoSuchProviderException, SignatureException {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "SHA1WithRSA");
    SecureRandom random = SecureRandom.getInstance("RSA", "SHA1WithRSA");
    keyGen.initialize(1024, random);/*from   w ww . j  ava2 s  .c o m*/
    KeyPair keypair = keyGen.generateKeyPair();
    return keypair;
}

From source file:netscape.security.pkcs.PKCS12Util.java

public PKCS12Util() throws Exception {
    random = SecureRandom.getInstance("pkcs11prng", "Mozilla-JSS");
}

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

private static SSLContext createEasySSLContext() {
    try {/*from   w ww  .  j  a va2s  .  co m*/
        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 EasyX509TrustManager(null) }, rng);
        return context;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new HttpClientError(e.toString());
    }
}

From source file:eu.bittrade.libs.steemj.util.KeyGenerator.java

/**
 * Generate a new brain key.// w  w w . j  av  a 2 s .  c o  m
 * 
 * <b>Notice</b> that this method uses the SecureRandom.getInstanceStrong()
 * method to generate random numbers. The algorithm used by this method can
 * be changed by configuring the {@code
 * securerandom.strongAlgorithms} {@link Security} property.
 * 
 * @return The generated brain key.
 * @throws SteemKeyHandlingException
 *             If the algorithm used by the random generator is not
 *             supported on your platform.
 */
public static String suggestBrainKey() throws SteemKeyHandlingException {
    ArrayList<String> brainKeyParts = new ArrayList<>();

    try {
        for (int i = 0; i < BRAIN_KEY_WORD_COUNT; i++) {
            brainKeyParts.add(BrainkeyDictionaryManager.getInstance().getBrainKeyDictionary()[SecureRandom
                    .getInstance("SHA1PRNG", "SUN")
                    .nextInt(BrainkeyDictionaryManager.getInstance().getBrainKeyDictionary().length - 1)]
                            .toUpperCase());
        }
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new SteemKeyHandlingException(
                "The algorithm used to provide a strong random number is not available on your system.", e);
    }

    return StringUtils.join(brainKeyParts, " ");
}

From source file:org.torproject.collector.bridgedescs.SanitizedBridgesWriter.java

@Override
protected void startProcessing() throws ConfigurationException {

    outputPathName = Paths.get(config.getPath(Key.OutputPath).toString(), BRIDGE_DESCRIPTORS).toString();
    recentPathName = Paths.get(config.getPath(Key.RecentPath).toString(), BRIDGE_DESCRIPTORS).toString();
    File bridgeDirectoriesDirectory = config.getPath(Key.BridgeLocalOrigins).toFile();
    File sanitizedBridgesDirectory = new File(outputPathName);
    File statsDirectory = config.getPath(Key.StatsPath).toFile();

    if (bridgeDirectoriesDirectory == null || sanitizedBridgesDirectory == null || statsDirectory == null) {
        throw new ConfigurationException(
                "BridgeSnapshotsDirectory, " + "SanitizedBridgesWriteDirectory, StatsPath should be set. "
                        + "Please, edit the 'collector.properties' file.");
    }// ww w.jav a  2  s.  c  o  m

    /* Memorize argument values. */
    this.bridgeDirectoriesDirectory = bridgeDirectoriesDirectory;
    this.sanitizedBridgesDirectory = sanitizedBridgesDirectory;
    this.replaceIpAddressesWithHashes = config.getBool(Key.ReplaceIpAddressesWithHashes);
    SimpleDateFormat rsyncCatFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    rsyncCatFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    this.rsyncCatString = rsyncCatFormat.format(System.currentTimeMillis());

    /* Initialize secure random number generator if we need it. */
    if (this.replaceIpAddressesWithHashes) {
        try {
            this.secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
        } catch (GeneralSecurityException e) {
            logger.warn("Could not initialize secure "
                    + "random number generator! Not calculating any IP address " + "hashes in this execution!",
                    e);
            this.persistenceProblemWithSecrets = true;
        }
    }

    /* Read hex-encoded secrets for replacing IP addresses with hashes
     * from disk. */
    this.secretsForHashingIpAddresses = new TreeMap<String, byte[]>();
    this.bridgeIpSecretsFile = new File(statsDirectory, "bridge-ip-secrets");
    if (this.bridgeIpSecretsFile.exists()) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(this.bridgeIpSecretsFile));
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if ((line.length() != ("yyyy-MM,".length() + 31 * 2)
                        && line.length() != ("yyyy-MM,".length() + 50 * 2)
                        && line.length() != ("yyyy-MM,".length() + 83 * 2)) || parts.length != 2) {
                    logger.warn(
                            "Invalid line in bridge-ip-secrets file " + "starting with '" + line.substring(0, 7)
                                    + "'! " + "Not calculating any IP address hashes in this " + "execution!");
                    this.persistenceProblemWithSecrets = true;
                    break;
                }
                String month = parts[0];
                byte[] secret = Hex.decodeHex(parts[1].toCharArray());
                this.secretsForHashingIpAddresses.put(month, secret);
            }
            br.close();
            if (!this.persistenceProblemWithSecrets) {
                logger.debug("Read " + this.secretsForHashingIpAddresses.size() + " secrets for "
                        + "hashing bridge IP addresses.");
            }
        } catch (DecoderException e) {
            logger.warn("Failed to decode hex string in " + this.bridgeIpSecretsFile
                    + "! Not calculating any IP " + "address hashes in this execution!", e);
            this.persistenceProblemWithSecrets = true;
        } catch (IOException e) {
            logger.warn("Failed to read " + this.bridgeIpSecretsFile + "! Not calculating any IP "
                    + "address hashes in this execution!", e);
            this.persistenceProblemWithSecrets = true;
        }
    }

    long limitBridgeSanitizingInterval = config.getInt(Key.BridgeDescriptorMappingsLimit);

    /* If we're configured to keep secrets only for a limited time, define
     * the cut-off day and time. */
    if (limitBridgeSanitizingInterval >= 0L) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        this.bridgeSanitizingCutOffTimestamp = formatter
                .format(System.currentTimeMillis() - 24L * 60L * 60L * 1000L * limitBridgeSanitizingInterval);
    } else {
        this.bridgeSanitizingCutOffTimestamp = "1999-12-31 23:59:59";
    }

    // Prepare bridge descriptor parser
    BridgeDescriptorParser bdp = new BridgeDescriptorParser(this);

    // Import bridge descriptors
    new BridgeSnapshotReader(bdp, this.bridgeDirectoriesDirectory, statsDirectory);

    // Finish writing sanitized bridge descriptors to disk
    this.finishWriting();

    this.checkStaleDescriptors();

    this.cleanUpRsyncDirectory();
}

From source file:de.pawlidi.openaletheia.utils.CipherUtils.java

/**
 * // w w w.  java 2s .com
 * @return
 */
public static KeyPair generateKeyPair() {
    KeyPairGenerator generator = null;
    SecureRandom secureRandom = null;
    try {
        generator = KeyPairGenerator.getInstance(CIPHER_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Could not generate key", e);
    }
    try {
        secureRandom = SecureRandom.getInstance(RANDOM_NUMBER_GENERATOR_ALGORITHM, "SUN");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        // ignore exception
    }
    if (secureRandom == null) {
        generator.initialize(2048);
    } else {
        generator.initialize(2048, secureRandom);
    }
    return generator.generateKeyPair();
}

From source file:org.iavante.sling.commons.services.impl.EncryptionServiceImpl.java

/**
 * Make a keypair (public for encryption and private for decrypt) with
 * RSA_KeySize bits size/*from   ww  w  . ja  va2 s.c  o  m*/
 * 
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
private void makeKey() throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    // Initialize the Key-Pair Generator
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    kpg.initialize(defaultRsaKeySize, random);
    keyPair = kpg.generateKeyPair();
}

From source file:com.joyent.manta.client.crypto.AbstractAesCipherDetails.java

/**
 * This method attempts to find our first choice for a source of a source
 * of entropy and then chooses the default if that choice is not available.
 *
 * @return specific implementation of {@link SecureRandom}
 *///from   ww w.j a v  a 2 s  .  com
private static SecureRandom findSecureRandomImplementation() {
    // First we attempt to a non-blocking source of entropy that typically
    // reads from /dev/urandom
    try {
        return SecureRandom.getInstance("NativePRNGNonBlocking", "SUN");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        // We are here if we were unable to load that source of entropy
        // so we go with the default value
        return new SecureRandom();
    }
}