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:com.goodhustle.ouyaunitybridge.OuyaUnityActivity.java

public void requestPurchase(final String productId)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());
    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", productId);
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();
    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);//  w  w w  .j av a2s. c o m
    SecretKey key = new SecretKeySpec(keyBytes, "AES");
    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));
    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);
    Purchasable purchasable = new Purchasable(productId, Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));
    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, productId);
    }
    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(productId));
}

From source file:com.alfaariss.oa.engine.core.crypto.CryptoManager.java

private void readRandomConfig(Element eCryptoSection) throws CryptoException {
    //<random_generator algorithm="SHA1PRNG" provider="CryptixCrypto"/>
    Element eRandomSection = null;
    String sRandomAlgorithm = null;
    String sRandomProvider = null;

    try {/*from w w  w  . ja v  a  2  s  .  c om*/
        eRandomSection = _configManager.getSection(eCryptoSection, "random_generator");
        if (eRandomSection == null) {
            sRandomAlgorithm = DEFAULT_RANDOM_ALGORITHM;
            _logger.info("Could not retrieve 'random' config section. Using default algorithm and provider");
        } else //Encryption configured
        {
            //retrieve algorithm
            try {
                sRandomAlgorithm = _configManager.getParam(eRandomSection, "algorithm");
                if (sRandomAlgorithm == null) {
                    sRandomAlgorithm = DEFAULT_RANDOM_ALGORITHM;
                    _logger.info("Could not retrieve 'algorithm' config parameter. Using default algorithm");
                }
            } catch (ConfigurationException e) {
                _logger.error("Could not read 'algorithm' config parameter", e);
                throw new CryptoException(SystemErrors.ERROR_CONFIG_READ);
            }

            // retrieve provider
            try {
                sRandomProvider = _configManager.getParam(eRandomSection, "provider");
                if (sRandomProvider == null) {
                    _logger.info(
                            "Could not retrieve 'provider' config parameter. Using first suitable provider");
                }
            } catch (ConfigurationException e) {
                _logger.error("Could not read 'provider' config parameter", e);
                throw new CryptoException(SystemErrors.ERROR_CONFIG_READ);
            }
        }

        //Secure Random
        if (sRandomProvider == null)
            _secureRandom = SecureRandom.getInstance(sRandomAlgorithm);
        else
            _secureRandom = SecureRandom.getInstance(sRandomAlgorithm, sRandomProvider);

    } catch (CryptoException e) {
        throw e;
    } catch (NoSuchAlgorithmException e) {
        _logger.error("Invalid random algorithm", e);
        throw new CryptoException(SystemErrors.ERROR_INIT);
    } catch (NoSuchProviderException e) {
        _logger.error("Invalid random provider", e);
        throw new CryptoException(SystemErrors.ERROR_INIT);
    } catch (Exception e) {
        _logger.fatal("Internal error during configuration reading", e);
        throw new CryptoException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:pt.aptoide.backupapps.data.webservices.ManagerUploads.java

public static String generateBoundary() {
    try {/* w  w  w .j  a v a 2 s  .  c om*/
        // Create a secure random number generator
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

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

        int seedByteCount = 10;
        byte[] seed = sr.generateSeed(seedByteCount);

        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);

        return "***" + Long.toString(sr.nextLong()) + "***";

    } catch (NoSuchAlgorithmException e) {
    }
    return "*********";
}

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

private byte[] generateKeyData() {
    try {//from  ww w. j a  va  2s  .  com
        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:org.apache.hadoop.dfs.DataNode.java

static void setNewStorageID(DatanodeRegistration dnReg) {
    /* Return //from   w  w  w. j  a va2s . co m
     * "DS-randInt-ipaddr-currentTimeMillis"
     * It is considered extermely rare for all these numbers to match
     * on a different machine accidentally for the following 
     * a) SecureRandom(INT_MAX) is pretty much random (1 in 2 billion), and
     * b) Good chance ip address would be different, and
     * c) Even on the same machine, Datanode is designed to use different ports.
     * d) Good chance that these are started at different times.
     * For a confict to occur all the 4 above have to match!.
     * The format of this string can be changed anytime in future without
     * affecting its functionality.
     */
    String ip = "unknownIP";
    try {
        ip = DNS.getDefaultIP("default");
    } catch (UnknownHostException ignored) {
        LOG.warn("Could not find ip address of \"default\" inteface.");
    }

    int rand = 0;
    try {
        rand = SecureRandom.getInstance("SHA1PRNG").nextInt(Integer.MAX_VALUE);
    } catch (NoSuchAlgorithmException e) {
        LOG.warn("Could not use SecureRandom");
        rand = R.nextInt(Integer.MAX_VALUE);
    }
    dnReg.storageID = "DS-" + rand + "-" + ip + "-" + dnReg.getPort() + "-" + System.currentTimeMillis();
}

From source file:org.apache.jxtadoop.hdfs.server.datanode.DataNode.java

public static void setNewStorageID(DatanodeRegistration dnReg) {
    /* Return /* w w w .j  a v a2 s.c  om*/
     * "DS-randInt-ipaddr-currentTimeMillis"
     * It is considered extermely rare for all these numbers to match
     * on a different machine accidentally for the following 
     * a) SecureRandom(INT_MAX) is pretty much random (1 in 2 billion), and
     * b) Good chance ip address would be different, and
     * c) Even on the same machine, Datanode is designed to use different ports.
     * d) Good chance that these are started at different times.
     * For a confict to occur all the 4 above have to match!.
     * The format of this string can be changed anytime in future without
     * affecting its functionality.
     */
    String ip = "unknownIP";
    try {
        ip = DNS.getDefaultIP("default");
    } catch (UnknownHostException ignored) {
        LOG.warn("Could not find ip address of \"default\" inteface.");
    }

    int rand = 0;
    try {
        rand = SecureRandom.getInstance("SHA1PRNG").nextInt(Integer.MAX_VALUE);
    } catch (NoSuchAlgorithmException e) {
        LOG.warn("Could not use SecureRandom");
        rand = R.nextInt(Integer.MAX_VALUE);
    }
    dnReg.storageID = "DS-" + rand + "-" + ip + "-" + dnReg.getPeerId() + "-" + System.currentTimeMillis();
}

From source file:common.DataNode.java

public static void setNewStorageID(DatanodeRegistration dnReg) {
    /* Return /*  w  w w.  ja v  a 2 s  .  c  o  m*/
     * "DS-randInt-ipaddr-currentTimeMillis"
     * It is considered extermely rare for all these numbers to match
     * on a different machine accidentally for the following 
     * a) SecureRandom(INT_MAX) is pretty much random (1 in 2 billion), and
     * b) Good chance ip address would be different, and
     * c) Even on the same machine, Datanode is designed to use different ports.
     * d) Good chance that these are started at different times.
     * For a confict to occur all the 4 above have to match!.
     * The format of this string can be changed anytime in future without
     * affecting its functionality.
     */
    String ip = "unknownIP";
    try {
        ip = DNS.getDefaultIP("default");
    } catch (UnknownHostException ignored) {
        LOG.warn("Could not find ip address of \"default\" inteface.");
    }

    int rand = 0;
    try {
        rand = SecureRandom.getInstance("SHA1PRNG").nextInt(Integer.MAX_VALUE);
    } catch (NoSuchAlgorithmException e) {
        LOG.warn("Could not use SecureRandom");
        rand = R.nextInt(Integer.MAX_VALUE);
    }
    dnReg.storageID = "DS-" + rand + "-" + ip + "-" + dnReg.getPort() + "-" + System.currentTimeMillis();
}

From source file:org.rhq.enterprise.server.core.CoreServerServiceImpl.java

private synchronized String generateAgentToken() {
    if (random == null) {
        try {/*w  ww.  ja  va 2s . c o m*/
            random = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Could not load SecureRandom algorithm", e);
        }
    }

    byte[] tokenBytes = new byte[50];
    random.nextBytes(tokenBytes);
    return Base64.encode(tokenBytes);
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey,
        X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider)
        throws CryptoException {

    try {// w  w  w .  j a v  a2s  .c  om
        List<X509Certificate> certList = new ArrayList<X509Certificate>();

        Collections.addAll(certList, certificateChain);

        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC")
                .build();
        JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce())
                .setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
        if (provider != null) {
            csb.setProvider(provider);
        }
        JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv);

        // remove cmsAlgorithmProtect for compatibility reasons
        SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]);
        final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator();
        sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() {
            @Override
            public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
                AttributeTable ret = sAttrGen.getAttributes(parameters);
                return ret.remove(CMSAttributes.cmsAlgorithmProtect);
            }
        }, sigGen.getUnsignedAttributeTableGenerator());

        CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator();
        dataGen.addSignerInfoGenerator(sigGen);
        dataGen.addCertificates(new JcaCertStore(certList));

        CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true);

        // now let TSA time-stamp the signature
        if (tsaUrl != null && !tsaUrl.isEmpty()) {
            signedData = addTimestamp(tsaUrl, signedData);
        }

        return signedData.getEncoded();
    } catch (Exception ex) {
        throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex);
    }
}

From source file:org.apache.rahas.impl.SAMLTokenIssuer.java

/**
 * Create an ephemeral key//from www . j a  v  a2  s.  c  om
 * 
 * @return The generated key as a byte array
 * @throws TrustException
 */
protected byte[] generateEphemeralKey(int keySize) throws TrustException {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] temp = new byte[keySize / 8];
        random.nextBytes(temp);
        return temp;
    } catch (Exception e) {
        throw new TrustException("Error in creating the ephemeral key", e);
    }
}