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.texai.x509.X509Utils.java

/** Gets the secure random, and lazily initializes it.
 *
 * @return the initialized secure random
 *//*from  www  .j a va 2  s.  c o  m*/
public static SecureRandom getSecureRandom() {
    synchronized (secureRandom_lock) {
        if (secureRandom == null) {
            LOGGER.info("creating and seeding secure random");
            try {
                secureRandom = SecureRandom.getInstance("SHA1PRNG");
                secureRandom.nextInt();
            } catch (NoSuchAlgorithmException ex) {
                throw new TexaiException(ex);
            }
            secureRandom.nextInt();
        }
        return secureRandom;
    }
}

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

/**
 * ?.//from  w  w  w . j  a  v a2s . c  o 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.guillaumesoft.escapehellprison.PurchaseActivity.java

public void requestPurchase(final Product product)
        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", product.getIdentifier());
    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);//from  w  w w.  ja  va2 s  . co 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(product.getIdentifier());

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }
    mOuyaFacade.requestPurchase(this, purchasable, new PurchaseListener(product));
}

From source file:rapture.kernel.AdminApiImpl.java

private String generateSecureToken() {
    try {/*  ww  w.  j  ava2s  .com*/
        // get secure random
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte bytes[] = new byte[128];
        random.nextBytes(bytes);
        // get its digest
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] result = sha.digest(bytes);
        // encode to hex
        return (new Hex()).encodeHexString(result);
    } catch (NoSuchAlgorithmException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, e.getMessage());
    }
}

From source file:tv.ouya.sdk.UnityOuyaFacade.java

public void requestPurchase(final Product product)
        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", product.getIdentifier());
    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);//from  ww  w  .  j  a va2  s.  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(product.getIdentifier(),
            Base64.encodeToString(encryptedKey, Base64.NO_WRAP), Base64.encodeToString(ivBytes, Base64.NO_WRAP),
            Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }

    //custom-iap-code
    Log.i(LOG_TAG, "UnityOuyaFacade.requestPurchase(" + product.getIdentifier() + ")");
    UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog",
            "UnityOuyaFacade.requestPurchase(" + product.getIdentifier() + ")");

    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(product));
}

From source file:com.sonicle.webtop.core.sdk.UserProfile.java

private String generateSecretKey() throws NoSuchAlgorithmException {
    byte[] buffer = new byte[80 / 8];
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.nextBytes(buffer);/*from  w w  w  . j a v  a2s.c om*/
    byte[] secretKey = Arrays.copyOf(buffer, 80 / 8);
    byte[] encodedKey = new Base32().encode(secretKey);
    return new String(encodedKey);
}

From source file:tv.ouya.sample.IapSampleActivity.java

public void requestPurchase(final Product product)
        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", product.getIdentifier());
    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  a v  a2  s  .  co 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(product.getIdentifier(),
            Base64.encodeToString(encryptedKey, Base64.NO_WRAP), Base64.encodeToString(ivBytes, Base64.NO_WRAP),
            Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, product);
    }
    ouyaFacade.requestPurchase(purchasable, new PurchaseListener(product));
}

From source file:org.tolven.config.model.CredentialManager.java

private SecureRandom getSecureRandom() {
    //TODO: This may be better placed where it only gets created once for certain
    String algorithm = "SHA1PRNG";
    if (secureRandom == null) {
        try {//from   w w w. j a v  a 2  s . com
            secureRandom = SecureRandom.getInstance(algorithm);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException("Could not get an instance of SecureRandom using algorithm" + algorithm,
                    ex);
        }
    }
    return secureRandom;
}

From source file:com.tingtingapps.securesms.ConversationActivity.java

private void handleInviteLink() {
    try {/*w w w  . j  ava2 s. c o  m*/
        boolean a = SecureRandom.getInstance("SHA1PRNG").nextBoolean();
        if (a)
            composeText.appendInvite(
                    getString(R.string.ConversationActivity_get_with_it, "http://sgnl.link/1IvurmD"));
        else
            composeText.appendInvite(
                    getString(R.string.ConversationActivity_lets_use_this_to_chat, "http://sgnl.link/1CYCQQN"));
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }
}

From source file:org.apache.rahas.TrustUtil.java

/**
 * Create an ephemeral key// ww  w . ja v a  2s  .  c o m
 *
 * @return The generated ephemeral key
 * @throws TrustException
 */
protected byte[] generateEphemeralKey(byte[] reqEnt, byte[] respEnt, String algo, 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);
    }
}