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:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

private String generateNewKeyStorePassword() {
    String manualKeyStorePassword = super.getKeyStorePassword();
    if (manualKeyStorePassword != null && manualKeyStorePassword.length() > 0) {
        return manualKeyStorePassword;
    }//from  w  ww  .j  av  a 2 s. co  m
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        final int start = 32;
        final int end = 126;
        final int range = end - start;
        char[] passwd = new char[PASSWORD_LENGTH];
        for (int i = 0; i < PASSWORD_LENGTH; i++) {
            passwd[i] = (char) (random.nextInt(range) + start);
        }
        return new String(passwd);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Error creating random password", e);
    }
}

From source file:com.cloud.consoleproxy.AgentHookBase.java

@Override
public void startAgentHttpHandlerInVM(StartupProxyCommand startupCmd) {
    StartConsoleProxyAgentHttpHandlerCommand cmd = null;

    try {/*from   w ww. j a  v a  2 s .  com*/
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

        byte[] randomBytes = new byte[16];
        random.nextBytes(randomBytes);
        String storePassword = Base64.encodeBase64String(randomBytes);

        byte[] ksBits = null;
        String consoleProxyUrlDomain = _configDao.getValue(Config.ConsoleProxyUrlDomain.key());
        if (consoleProxyUrlDomain == null || consoleProxyUrlDomain.isEmpty()) {
            s_logger.debug(
                    "SSL is disabled for console proxy based on global config, skip loading certificates");
        } else {
            ksBits = _ksMgr.getKeystoreBits(ConsoleProxyManager.CERTIFICATE_NAME,
                    ConsoleProxyManager.CERTIFICATE_NAME, storePassword);
            //ks manager raises exception if ksBits are null, hence no need to explicltly handle the condition
        }

        cmd = new StartConsoleProxyAgentHttpHandlerCommand(ksBits, storePassword);
        cmd.setEncryptorPassword(getEncryptorPassword());

        HostVO consoleProxyHost = findConsoleProxyHost(startupCmd);

        assert (consoleProxyHost != null);
        if (consoleProxyHost != null) {
            Answer answer = _agentMgr.send(consoleProxyHost.getId(), cmd);
            if (answer == null || !answer.getResult()) {
                s_logger.error(
                        "Console proxy agent reported that it failed to execute http handling startup command");
            } else {
                s_logger.info("Successfully sent out command to start HTTP handling in console proxy agent");
            }
        }
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("Unexpected exception in SecureRandom Algorithm selection ", e);
    } catch (AgentUnavailableException e) {
        s_logger.error("Unable to send http handling startup command to the console proxy resource for proxy:"
                + startupCmd.getProxyVmId(), e);
    } catch (OperationTimedoutException e) {
        s_logger.error(
                "Unable to send http handling startup command(time out) to the console proxy resource for proxy:"
                        + startupCmd.getProxyVmId(),
                e);
    } catch (OutOfMemoryError e) {
        s_logger.error("Unrecoverable OutOfMemory Error, exit and let it be re-launched");
        System.exit(1);
    } catch (Exception e) {
        s_logger.error(
                "Unexpected exception when sending http handling startup command(time out) to the console proxy resource for proxy:"
                        + startupCmd.getProxyVmId(),
                e);
    }
}

From source file:pro.hirooka.streaming_server_for_multiple_platforms.Encrypter.java

static Key makeKey(int keyBit) throws NoSuchAlgorithmException {

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    SecureRandom rd = SecureRandom.getInstance("SHA1PRNG");
    kg.init(keyBit, rd);/*from  w w  w. j  a v  a 2s  . co m*/
    Key key = kg.generateKey();
    return key;

}

From source file:tv.ouya.sample.game.OptionsActivity.java

private void requestPurchase(final Options.Level level)
        throws GeneralSecurityException, JSONException, UnsupportedEncodingException {
    final String productId = getProductIdForLevel(level);

    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.ja  v  a2  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(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);
    }
    mOuyaFacade.requestPurchase(purchasable, new OuyaResponseListener<String>() {
        @Override
        public void onSuccess(String result) {
            String responseProductId;
            try {
                OuyaEncryptionHelper helper = new OuyaEncryptionHelper();

                JSONObject response = new JSONObject(result);
                String responseUUID = helper.decryptPurchaseResponse(response, mPublicKey);
                synchronized (mOutstandingPurchaseRequests) {
                    responseProductId = mOutstandingPurchaseRequests.remove(responseUUID);
                }
                if (responseProductId == null || !responseProductId.equals(productId)) {
                    onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS,
                            "Purchased product is not the same as purchase request product", Bundle.EMPTY);
                    return;
                }
            } catch (JSONException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (ParseException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (IOException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (GeneralSecurityException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            }

            if (responseProductId.equals(getProductIdForLevel(level))) {
                setNeedsPurchaseText(levelToRadioButton.get(level), false);
                Toast.makeText(OptionsActivity.this, "Level purchased!", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(int errorCode, String errorMessage, Bundle optionalData) {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this,
                    "Error making purchase!\n\nError " + errorCode + "\n" + errorMessage + ")",
                    Toast.LENGTH_LONG).show();

        }

        @Override
        public void onCancel() {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this, "You cancelled the purchase!", Toast.LENGTH_LONG).show();
        }
    });
}

From source file:org.wso2.carbon.user.core.util.UserCoreUtil.java

/**
 * This method generates a random password that adhere to most of the password policies defined
 * by various LDAPs such as AD, ApacheDS 2.0 etc
 *
 * @param username/*  w  ww  .j  a v  a  2s  .c om*/
 * @param length
 * @return password
 * @throws UserStoreException
 */
public static String getPolicyFriendlyRandomPassword(String username, int length) throws UserStoreException {

    if (length < 8 || length > 50) {
        length = 12;
    }

    // Avoiding admin, administrator, root, wso2, carbon to be a password
    char[] chars = { 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'N', 'P', 'Q', 'U', 'V', 'W', 'X', 'Y', 'Z', 'e', 'f',
            'g', 'h', 'j', 'k', 'l', 'n', 'p', 'q', 'u', 'v', 'w', 'x', 'y', 'z', '~', '!', '@', '#', '$', '%',
            '^', '&', '*', '_', '-', '+', '=', };

    char[] invalidChars = username.toCharArray();
    StringBuffer passwordFeed = new StringBuffer();

    // now we are going filter characters in the username
    for (char invalidCha : invalidChars) {
        for (char cha : chars) {
            if (cha != invalidCha)
                passwordFeed.append(cha);
        }
    }

    // the password generation
    String passwordChars = passwordFeed.toString();
    char[] password = new char[length];
    String randomNum = null;

    try {
        // the secure random
        SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
        for (int i = 0; i < length; i++) {
            password[i] = passwordChars.charAt(prng.nextInt(passwordFeed.length()));
        }
        randomNum = new Integer(prng.nextInt()).toString();

    } catch (NoSuchAlgorithmException e) {
        String errorMessage = "Error while creating the random password for user : " + username;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }

    return new String(password).concat(randomNum);
}

From source file:org.tolven.gatekeeper.CertificateHelper.java

private SecureRandom getSecureRandom() {
    //TODO: This may be better placed where it only gets created once for certain
    if (secureRandom == null)
        try {/*from  w w w.  j  av a 2  s  .co  m*/
            secureRandom = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException("Could not obtain a SecureRandom instance", ex);
        }
    return secureRandom;
}

From source file:utils.Hash.java

/**
 * Creates a psedorandom base64 string/*from ww  w  . j av  a 2  s.c  om*/
 * @return Random String
 */
public static String randomBase64String() {
    String result = new String();
    try {
        byte byteArray[] = new byte[256];
        SecureRandom psn1 = SecureRandom.getInstance("SHA1PRNG");

        Base64 base64 = new Base64();
        psn1.setSeed(psn1.nextLong());
        psn1.nextBytes(byteArray);
        result = new String(byteArray, Charset.forName("US-ASCII"));
        result = base64.encode(thisString(thisString(byteArray.toString())).getBytes()).toString();
        log.debug("Generated String = " + result);
    } catch (Exception e) {
        log.error("Random Number Error : " + e.toString());
    }
    return result;
}

From source file:org.sakaiproject.nakamura.auth.trusted.TokenStore.java

/**
 * @throws NoSuchAlgorithmException// w  w  w.  j  av a2 s.  c o  m
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws IllegalStateException
 *
 */
public TokenStore() throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException,
        UnsupportedEncodingException {
    random = SecureRandom.getInstance(SHA1PRNG);
    // warm up the crypto API
    Mac m = Mac.getInstance(HMAC_SHA1);
    byte[] b = new byte[20];
    random.nextBytes(b);
    SecretKey secretKey = new SecretKeySpec(b, HMAC_SHA1);
    m.init(secretKey);
    m.update(UTF_8.getBytes(UTF_8));
    m.doFinal();
    this.tokenFile = new File(DEFAULT_TOKEN_FILE);
    tmpTokenFile = new File(DEFAULT_TOKEN_FILE + ".tmp");

}

From source file:uk.ac.cam.cl.dtg.segue.auth.SegueLocalAuthenticator.java

/**
 * Helper method to generate a base64 encoded salt.
 * // w w w . j  ava2 s  .  com
 * @return generate a base64 encoded secure salt.
 * @throws NoSuchAlgorithmException
 *             - problem locating the algorithm.
 */
private static String generateSalt() throws NoSuchAlgorithmException {
    SecureRandom sr = SecureRandom.getInstance(SALTING_ALGORITHM);

    byte[] salt = new byte[SALT_SIZE];
    sr.nextBytes(salt);

    return new String(Base64.encodeBase64(salt));
}

From source file:de.fhg.fokus.hss.server.zh.HSSzhOperationsImpl.java

/**
 * This method generates the authentication vectors sized by given paramter.
 * @return a list of Authentication vectors
 *//*from   w  w w. ja va 2s  . co  m*/
public ArrayList generateAuthenticationVectors() {
    LOGGER.debug("entering");

    ArrayList vectorList = null;
    try {

        vectorList = new ArrayList(numberAuthItems.intValue());

        HexCoDec codec;
        codec = new HexCoDec();
        byte[] secretKey = codec.decode(impi.getSkey());
        byte[] amf = codec.decode(impi.getAmf());

        // op and generate opC   
        byte[] op = codec.decode(impi.getOperatorId());
        byte[] opC = Milenage.generateOpC(secretKey, op);

        String authScheme = impi.getAuthScheme();
        Inet4Address ip = impi.getIP();
        byte[] sqn = codec.decode(impi.getSqn());

        if (authScheme.equalsIgnoreCase("Digest-MD5")) {
            // Authentication Scheme is Digest-MD5
            LOGGER.debug("Auth-Scheme is Digest-MD5");
            SecureRandom randomAccess = SecureRandom.getInstance("SHA1PRNG");

            for (long ix = 0; ix < numberAuthItems; ix++) {
                byte[] randBytes = new byte[16];
                randomAccess.setSeed(System.currentTimeMillis());
                randomAccess.nextBytes(randBytes);

                secretKey = codec.decodePassword(impi.getSkey()).getBytes();

                AuthenticationVector aVector = new AuthenticationVector(authScheme, randBytes, secretKey);
                vectorList.add(aVector);
            }
            impi.setSqn(codec.encode(sqn));
            HibernateUtil.getCurrentSession().update(impi);
        } else if (authScheme.equalsIgnoreCase("Digest-AKAv1-MD5")
                || authScheme.equalsIgnoreCase("Digest-AKAv2-MD5")) {
            // We have AKAv1 or AKAv2
            LOGGER.debug("Auth-Scheme is Digest-AKA");

            for (long ix = 0; ix < numberAuthItems; ix++) {
                sqn = DigestAKA.getNextSQN(sqn, HSSProperties.IND_LEN);
                byte[] copySqnHe = new byte[6];
                int k = 0;
                for (int i = 0; i < 6; i++, k++) {
                    copySqnHe[k] = sqn[i];
                }

                vectorList.add(DigestAKA.getAuthenticationVector(authScheme, secretKey, opC, amf, copySqnHe));
            }
            impi.setSqn(codec.encode(sqn));
            HibernateUtil.getCurrentSession().update(impi);
        }

    } catch (NoSuchAlgorithmException e) {
        LOGGER.error(this, e);
    } catch (InvalidKeyException e) {
        LOGGER.error(this, e);
    } catch (Exception e) {
        // Check impi
        if (impi.getAmf() == null) {
            throw new NullPointerException("Missing AMF value.");
        }

        if (impi.getSkey() == null) {
            throw new NullPointerException("Missing Secret Key value.");
        }

        if (impi.getAuthScheme() == null) {
            throw new NullPointerException("Missing Authentication Scheme.");
        }

        if (impi.getOperatorId() == null) {
            throw new NullPointerException("Missing Operator ID.");
        }
    }

    LOGGER.debug("exiting");
    return vectorList;
}