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.cloudstack.api.command.LdapImportUsersCmd.java

private String generatePassword() throws ServerApiException {
    try {/*from   ww  w.ja  va  2 s  . c o  m*/
        final SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
        final byte bytes[] = new byte[20];
        randomGen.nextBytes(bytes);
        return new String(Base64.encode(bytes), "UTF-8");
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to generate random password");
    }
}

From source file:wssec.TestWSSecurityNewSCT.java

public void testSCTKDKTEncryptSign() {
    try {//from w ww . j av  a  2s  .c  om
        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
        Document doc = unsignedEnvelope.getAsDocument();
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);

        WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
        sctBuilder.prepare(doc, crypto);

        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] tempSecret = new byte[16];
        random.nextBytes(tempSecret);

        // Store the secret
        this.secrets.put(sctBuilder.getIdentifier(), tempSecret);

        String tokenId = sctBuilder.getSctId();

        // Derived key encryption
        WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
        encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
        encrBuilder.setExternalKey(tempSecret, tokenId);
        encrBuilder.build(doc, secHeader);

        // Derived key signature
        WSSecDKSign sigBuilder = new WSSecDKSign();
        sigBuilder.setExternalKey(tempSecret, tokenId);
        sigBuilder.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
        sigBuilder.build(doc, secHeader);

        sctBuilder.prependSCTElementToHeader(doc, secHeader);

        if (LOG.isDebugEnabled()) {
            String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
            LOG.debug(outputString);
        }

        verify(doc);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:utils.Hash.java

/**
 * Generates a small psedorandom string/* ww w .  j av  a  2  s  .c  o  m*/
 * @return Random String
 */
public static String smallRandomString() {
    String result = new String();
    try {
        byte byteArray[] = new byte[4];
        SecureRandom psn1 = SecureRandom.getInstance("SHA1PRNG");
        psn1.setSeed(psn1.nextLong());
        psn1.nextBytes(byteArray);
        BigInteger bigInt = new BigInteger(byteArray);
        result = bigInt.toString();
        log.debug("Generated String = " + result);

    } catch (Exception e) {
        log.error("Random Number Error : " + e.toString());
    }
    return result;
}

From source file:net.mybox.mybox.Common.java

/**
 * Generate a random salt value to be used for encrypting a password
 * @return//from  www  . j a  v  a  2  s  .  c o m
 */
public static String generateSalt() throws NoSuchAlgorithmException {

    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

    byte[] bSalt = new byte[8];
    random.nextBytes(bSalt);

    return byteToBase64(bSalt);
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * /*from   w  w w . j ava  2s  . c om*/
 * 
 * @param ctx
 *            
 * @param content
 *            
 * @param key
 *            
 * @return byte[] ?
 */
public static byte[] symmetryEncrypt(SecurityContext ctx, byte[] content, Key key) {
    try {
        byte[] cipherContent = null;
        Cipher cipher = Cipher.getInstance(ctx.getSymmetryAlgorithm(), ctx.getJceProvider());
        SecureRandom secureRandom = SecureRandom.getInstance(ctx.getSecureRandomAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, key, secureRandom);
        cipherContent = cipher.doFinal(content);
        return cipherContent;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}

From source file:com.facebook.LinkBench.LinkBenchDriver.java

/**
 * Create a new random number generated, optionally seeded to a known
 * value from the config file.  If seed value not provided, a seed
 * is chosen.  In either case the seed is logged for later reproducibility.
 * @param props/*from   w  w  w .  ja  v  a  2  s. c om*/
 * @param configKey config key for the seed value
 * @return
 */
private Random createMasterRNG(Properties props, String configKey) {
    long seed;
    if (props.containsKey(configKey)) {
        seed = ConfigUtil.getLong(props, configKey);
        logger.info("Using configured random seed " + configKey + "=" + seed);
    } else {
        seed = System.nanoTime() ^ (long) configKey.hashCode();
        logger.info("Using random seed " + seed + " since " + configKey + " not specified");
    }

    SecureRandom masterRandom;
    try {
        masterRandom = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        logger.warn("SHA1PRNG not available, defaulting to default SecureRandom" + " implementation");
        masterRandom = new SecureRandom();
    }
    masterRandom.setSeed(ByteBuffer.allocate(8).putLong(seed).array());

    // Can be used to check that rng is behaving as expected
    logger.debug("First number generated by master " + configKey + ": " + masterRandom.nextLong());
    return masterRandom;
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

final public static _CRYPTOfactory getInstance(InputStream in) throws ClassNotFoundException,
        NoSuchAlgorithmException, IllegalArgumentException, SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException {
    final DataInputStream d = new DataInputStream(in);
    int start = 0;
    final int type_length = d.readInt();
    start = start + 4;//from  w  w  w. j a  va  2  s.  c  o  m
    final int cipher_length = d.readInt();
    start = start + 4;
    final int salter_length = d.readInt();
    start = start + 4;
    final int key_length = d.readInt();
    start = start + 4;
    final StringBuilder type = new StringBuilder();
    final StringBuilder cipher = new StringBuilder();
    final StringBuilder salter = new StringBuilder();
    final byte[] key = new byte[key_length];
    for (int i = 0; i < type_length; i++)
        type.append((char) d.readByte());
    for (int i = 0; i < cipher_length; i++)
        cipher.append((char) d.readByte());
    for (int i = 0; i < salter_length; i++)
        salter.append((char) d.readByte());
    d.readFully(key);
    return new _CRYPTOfactory(
            (Crypter) Class.forName(_CRYPTOfactory.class.getPackage().getName() + "." + type + "Crypter")
                    .getConstructor(byte[].class, String.class, SecureRandom.class)
                    .newInstance(key, cipher.toString(), SecureRandom.getInstance(salter.toString())));
}

From source file:com.mindprotectionkit.freephone.RedPhoneService.java

private byte[] setZID() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {// www.  jav  a 2  s.c  om
        byte[] zid = new byte[12];
        SecureRandom.getInstance("SHA1PRNG").nextBytes(zid);
        String encodedZid = Base64.encodeBytes(zid);

        preferences.edit().putString("ZID", encodedZid).commit();

        return zid;
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.qut.middleware.esoemanager.manager.logic.impl.ServiceCryptoImpl.java

private String generatePassphrase() {
    SecureRandom random;/*w w  w.j  a  va2 s  . c o  m*/
    String passphrase;
    byte[] buf;

    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException nsae) {
        this.logger.error("NoSuchAlgorithmException when trying to create SecureRandom instance " //$NON-NLS-1$
                + nsae.getLocalizedMessage());
        this.logger.debug(nsae.getLocalizedMessage(), nsae);
        random = new SecureRandom();
    }

    buf = new byte[Constants.PASSPHRASE_LENGTH];
    random.nextBytes(buf);
    passphrase = new String(Hex.encodeHex(buf));

    return passphrase;
}

From source file:wssec.TestWSSecurityNewSCT.java

/**
 * Test signature and verification using a SecurityContextToken directly,
 * rather than using a DerivedKeyToken to point to a SecurityContextToken.
 * See WSS-216 - https://issues.apache.org/jira/browse/WSS-216
 *//*from  w w  w.jav a2 s .c  o  m*/
public void testSCTSign() {
    try {
        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
        Document doc = unsignedEnvelope.getAsDocument();
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);

        WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken();
        sctBuilder.prepare(doc, crypto);

        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] tempSecret = new byte[16];
        random.nextBytes(tempSecret);

        // Store the secret
        this.secrets.put(sctBuilder.getIdentifier(), tempSecret);

        String tokenId = sctBuilder.getSctId();

        WSSecSignature builder = new WSSecSignature();
        builder.setSecretKey(tempSecret);
        builder.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        builder.setCustomTokenValueType(WSConstants.WSC_SCT);
        builder.setCustomTokenId(tokenId);
        builder.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);
        builder.build(doc, crypto, secHeader);

        sctBuilder.prependSCTElementToHeader(doc, secHeader);

        if (LOG.isDebugEnabled()) {
            LOG.debug("SCT sign");
            String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
            LOG.debug(outputString);
        }

        verify(doc);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}