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.k42b3.neodym.oauth.Oauth.java

private String getNonce() {
    try {// w  w w .j  a va2 s .c o  m
        byte[] nonce = new byte[32];

        Random rand;

        rand = SecureRandom.getInstance("SHA1PRNG");

        rand.nextBytes(nonce);

        return DigestUtils.md5Hex(rand.toString());
    } catch (Exception e) {
        return DigestUtils.md5Hex("" + System.currentTimeMillis());
    }
}

From source file:com.titilink.camel.rest.util.PasswordUtils.java

/**
 * SecureRandom?????/*from  w w w  . j  ava  2s .co m*/
 *
 * @return ?
 */
public synchronized static byte[] generateSecRamdom() {
    try {
        SecureRandom sr = SecureRandom.getInstance(ALGORITHM_SHA1PRNG);
        byte[] bytes = new byte[DECIMAL_16];
        sr.nextBytes(bytes);
        return bytes;
    } catch (NoSuchAlgorithmException e) {
        LOGGER.error("generateSecRamdom error, no such algorithm exception");
    }
    return null;
}

From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Generates a nonce value for the SOAP secure header.
 *
 * @return the nonce value//from  www .java  2  s  .  c om
 * @throws Exception
 *             if any error occurs while generating the nonce
 */
private static final String getNonce() throws Exception {
    final SecureRandom random; // Random value generator
    final byte[] nonceBytes; // Bytes to generate the nonce

    random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(System.currentTimeMillis());
    nonceBytes = new byte[16];
    random.nextBytes(nonceBytes);

    return new String(Base64.encodeBase64(nonceBytes), "UTF-8");
}

From source file:servlets.module.challenge.BrokenCryptoHomeMade.java

public static String randomKeyLengthString() {
    String result = new String();
    try {/*from ww w .  j  a va2 s .  c  o m*/
        byte byteArray[] = new byte[16];
        SecureRandom psn1 = SecureRandom.getInstance("SHA1PRNG");
        psn1.setSeed(psn1.nextLong());
        psn1.nextBytes(byteArray);
        result = new String(byteArray, Charset.forName("US-ASCII"));
        //log.debug("Generated Key = " + result);
        if (result.length() != 16) {
            log.error("Generated Key is the incorrect Length: Shortening ");
            result = result.substring(0, 15);
            if (result.length() != 16)
                log.fatal("Encryption key length is Still not Right");
        }
    } catch (Exception e) {
        log.error("Random Number Error : " + e.toString());
    }
    return result;
}

From source file:org.wso2.carbon.user.core.system.SystemUserRoleManager.java

public void addSystemUser(String userName, Object credential, String[] roleList) throws UserStoreException {

    Connection dbConnection = null;
    String password = (String) credential;
    try {/*from w  ww  .  ja  va 2s  .  com*/
        dbConnection = DatabaseUtil.getDBConnection(dataSource);
        String sqlStmt1 = SystemJDBCConstants.ADD_USER_SQL;

        String saltValue = null;
        try {
            SecureRandom secureRandom = SecureRandom.getInstance(UserCoreConstants.SHA_1_PRNG);
            byte[] bytes = new byte[16];
            //secureRandom is automatically seeded by calling nextBytes
            secureRandom.nextBytes(bytes);
            saltValue = Base64.encode(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA1PRNG algorithm could not be found.");
        }

        password = this.preparePassword(password, saltValue);

        this.updateStringValuesToDatabase(dbConnection, sqlStmt1, userName, password, saltValue, false,
                new Date(), tenantId);

        // add user to role.
        updateSystemRoleListOfUser(userName, null, roleList);

        dbConnection.commit();
    } catch (Throwable e) {
        try {
            if (dbConnection != null) {
                dbConnection.rollback();
            }
        } catch (SQLException e1) {
            log.error("Error while rollbacking add system user operation", e1);
        }
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage(), e);
        }
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        DatabaseUtil.closeAllConnections(dbConnection);
    }
}

From source file:com.data.pack.Util.java

public static void copyFile(InputStream in, OutputStream out, int flag) throws IOException {
    byte[] buffer = new byte[1024];
    int read;//from  w  w w .  j  a v  a2s.c o m

    try {

        Cipher encipher = null;
        try {
            encipher = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Cipher decipher = null;
        try {
            decipher = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyGenerator kgen = null;
        try {
            kgen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        byte[] keyStart = "fitnesSbridge".getBytes();
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(keyStart);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();

        // byte key[] =
        // {0x00,0x32,0x22,0x11,0x00,0x00,0x00,0x00,0x00,0x23,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
        skey = kgen.generateKey();
        // Lgo
        try {
            encipher.init(Cipher.ENCRYPT_MODE, skey);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CipherInputStream cis = new CipherInputStream(in, encipher);
        try {
            decipher.init(Cipher.DECRYPT_MODE, skey);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CipherOutputStream cos = new CipherOutputStream(out, decipher);

        try {

            if (flag == 2) {
                cos = new CipherOutputStream(out, encipher);
            } else {
                cos = new CipherOutputStream(out, decipher);
            }
            while ((read = in.read()) != -1) {
                cos.write(read);
                cos.flush();
            }

            cos.flush();
            cos.close();
            in.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (Exception e) {
        // TODO: handle exception
    }

    //
    // byte[] keyStart = "this is a key".getBytes();
    // KeyGenerator kgen = KeyGenerator.getInstance("AES");
    // SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    // sr.setSeed(keyStart);
    // kgen.init(128, sr); // 192 and 256 bits may not be available
    // SecretKey skey = kgen.generateKey();
    // byte[] key = skey.getEncoded();
    //
    //
    // byte[] b = baos.toByteArray();
    // while ((read = in.read(buffer)) != -1) {
    //
    // // decrypt
    // byte[] decryptedData = Util.decrypt(key,buffer);
    // out.write(decryptedData, 0, read);
    // }
    // } catch (NoSuchAlgorithmException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // catch (Exception e) {
    // // TODO: handle exception
    // }
    //
}

From source file:com.badlogic.gdx.pay.android.ouya.PurchaseManagerAndroidOUYA.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 ww . ja v  a2 s. com*/
    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, ouyaPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    purchasable = new Purchasable(product.getIdentifier(), Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));

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

From source file:com.jbrisbin.riak.async.RiakAsyncClient.java

@SuppressWarnings({ "unchecked" })
@Override//from  ww w.j av  a 2  s .  c  o m
public Promise<byte[]> generateAndSetClientId() throws IOException {
    SecureRandom sr;
    try {
        sr = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    byte[] data = new byte[6];
    sr.nextBytes(data);
    String clientId = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1);
    RPB.RpbSetClientIdReq.Builder b = RPB.RpbSetClientIdReq.newBuilder().setClientId(copyFromUtf8(clientId));
    Promise<byte[]> promise = new Promise<byte[]>();
    try {
        getConnection().write(new RpbRequest(new RpbMessage(MSG_SetClientIdReq, b.build()), promise));
    } catch (Exception e) {
        errorHandler.handleError(e);
    }
    return promise;
}

From source file:tv.ouya.sdk.TestOuyaFacade.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.j  a 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(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("TestOuyaFacade", "TestOuyaFacade.requestPurchase(" + product.getIdentifier() + ")");
    UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog",
            "TestOuyaFacade.requestPurchase(" + product.getIdentifier() + ")");

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

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.AbstractSessionManager.java

public void start() throws Exception {
    if (_random == null) {
        log.debug("New random session seed");
        try {/*from   w w  w. ja  va2 s.c  o m*/
            _random = SecureRandom.getInstance("SHA1PRNG");
        } catch (NoSuchAlgorithmException e) {
            log.warn("Could not generate SecureRandom for session-id randomness", e);
            _random = new Random();
            _weakRandom = true;
        }
        _random.setSeed(_random.nextLong() ^ System.currentTimeMillis() ^ hashCode()
                ^ Runtime.getRuntime().freeMemory());
    }

    if (_sessions == null)
        _sessions = new HashMap();

    // Start the session scavenger if we haven't already
    if (_scavenger == null) {
        _scavenger = new SessionScavenger();
        _scavenger.start();
    }
}