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.haulmont.cuba.core.sys.PasswordEncryptionImpl.java

@Override
public String generateRandomPassword() {
    SecureRandom random;/*from   w w w.  j  a  v a 2 s .c o  m*/
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to load SHA1PRNG", e);
    }
    byte[] passwordBytes = new byte[6];
    random.nextBytes(passwordBytes);
    return new String(Base64.encodeBase64(passwordBytes), StandardCharsets.UTF_8).replace("=", "");
}

From source file:nz.net.orcon.kanban.automation.actions.BulletinSmsEndpoint.java

public String sendMessage(String destination, String message) throws Exception {

    String messageId = RandomStringUtils.random(10, 0, 0, true, true, null,
            SecureRandom.getInstance("SHA1PRNG"));

    URL url = new URL(urlName);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    try {/*  w  w w.ja  v  a  2s. c o  m*/
        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", encodeBasicAuth(this.user, this.password));
        con.setDoOutput(true);

        StringBuffer form = new StringBuffer();
        form.append("to=").append(destination);

        conditionalAppend(form, "messageId", messageId);
        conditionalAppend(form, "body", URLEncoder.encode(message, "UTF-8"));

        OutputStream out = con.getOutputStream();
        try {
            out.write(form.toString().getBytes("US-ASCII"));
        } finally {
            out.close();
        }

        if (!(con.getResponseCode() == 200)) {
            throw new IOException("Return resultcode not success: " + con.getResponseCode());
        }

        return messageId;

    } finally {
        con.disconnect();
    }

}

From source file:com.vimukti.accounter.developer.api.PublicKeyGenerator.java

private static void generate() throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeySpecException, KeyStoreException, CertificateException, IOException, URISyntaxException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed("VimTech".getBytes("UTF-8"));
    keyGen.initialize(1024, random);/*from   ww w. j av a  2 s  .co  m*/

    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey priv = pair.getPrivate();
    PublicKey pub = pair.getPublic();
    System.out.println(priv);
    System.out.println(pub);

    byte[] encoded = pub.getEncoded();
    byte[] encodeBase64 = Base64.encodeBase64(encoded);
    System.out.println("Public Key:" + new String(encodeBase64));

    byte[] encodedPrv = priv.getEncoded();
    byte[] encodeBase64Prv = Base64.encodeBase64(encodedPrv);
    System.out.println("Private Key:" + new String(encodeBase64Prv));

    byte[] decodeBase64 = Base64.decodeBase64(encodeBase64);
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(decodeBase64);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");

    System.out.println(keyFactory.generatePublic(pubKeySpec).equals(pub));
}

From source file:org.soulwing.credo.service.crypto.ConcretePasswordGenerator.java

/**
 * Initializes the receiver.//from w ww .jav  a2  s  .com
 */
@PostConstruct
public void init() {
    try {
        secureRandom = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:io.hops.hopsworks.common.dao.user.security.ua.SecurityUtils.java

/**
 * Generate the secrete key for mobile devices.
 *
 * @return/*  w w w. j av  a 2 s. c  om*/
 */
public static String calculateSecretKey() throws NoSuchAlgorithmException {
    byte[] secretKey = new byte[10];
    SecureRandom sha1Prng = SecureRandom.getInstance("SHA1PRNG");
    sha1Prng.nextBytes(secretKey);
    Base32 codec = new Base32();
    byte[] encodedKey = codec.encode(secretKey);
    return new String(encodedKey);
}

From source file:Uuid32Generator.java

public String generate() {
    StringBuilder strRetVal = new StringBuilder();
    String strTemp;/*from   w  ww  .java  2s. c o m*/
    try {
        // IPAddress segment
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipaddr = addr.getAddress();
        for (byte anIpaddr : ipaddr) {
            Byte b = new Byte(anIpaddr);
            strTemp = Integer.toHexString(b.intValue() & 0x000000ff);
            strRetVal.append(ZEROS.substring(0, 2 - strTemp.length()));
            strRetVal.append(strTemp);
        }
        strRetVal.append(':');

        // CurrentTimeMillis() segment
        strTemp = Long.toHexString(System.currentTimeMillis());
        strRetVal.append(ZEROS.substring(0, 12 - strTemp.length()));
        strRetVal.append(strTemp).append(':');

        // random segment
        SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
        strTemp = Integer.toHexString(prng.nextInt());
        while (strTemp.length() < 8) {
            strTemp = '0' + strTemp;
        }
        strRetVal.append(strTemp.substring(4)).append(':');

        // IdentityHash() segment
        strTemp = Long.toHexString(System.identityHashCode(this));
        strRetVal.append(ZEROS.substring(0, 8 - strTemp.length()));
        strRetVal.append(strTemp);
    } catch (UnknownHostException uhex) {
        throw new RuntimeException("Unknown host.", uhex);
    } catch (NoSuchAlgorithmException nsaex) {
        throw new RuntimeException("Algorithm 'SHA1PRNG' is unavailiable.", nsaex);
    }
    return strRetVal.toString().toUpperCase();
}

From source file:org.starnub.utilities.crypto.PasswordHash.java

/**
 * Computes a salted PBKDF2 hash of given plaintext password
 * suitable for storing in a database.//from  w ww. ja  v  a  2s  .  c om
 * Empty passwords are not supported.
 * @param password String password to be hashed
 * @return String of salted password
 * @throws Exception
 */
public String getSaltedHash(String password) throws Exception {
    byte[] salt = SecureRandom.getInstance("SHA1PRNG").generateSeed(saltLen);
    // store the salt with the password
    return Base64.encodeBase64String(salt) + "$" + hash(password, salt);
}

From source file:edu.internet2.middleware.openid.common.impl.SecureRandomIdentifierGenerator.java

/**
 * Constructor./*from  www.j a  v a  2 s  .  c o  m*/
 * 
 * @param algorithm the random number generation algorithm to use
 * 
 * @throws NoSuchAlgorithmException thrown if the algorithm is not supported by the JVM
 */
public SecureRandomIdentifierGenerator(String algorithm) throws NoSuchAlgorithmException {
    random = SecureRandom.getInstance(algorithm);
}

From source file:com.muk.ext.security.impl.DefaultNonceService.java

@Override
public byte[] generatePsudoRandomNonce() throws NoSuchAlgorithmException {
    byte[] nonce = new byte[16];
    Random rand;/* w  ww.  j  a  va2  s. c  om*/
    rand = SecureRandom.getInstance("SHA1PRNG");
    rand.nextBytes(nonce);

    return nonce;
}

From source file:com.github.aynu.mosir.core.standard.util.SecurityHelper.java

/**
 * ???//www  .  j  av a2s.  c om
 * <dl>
 * <dt>?
 * <dd>??????????
 * </dl>
 * @return ??
 * @throws NoSuchAlgorithmException ??
 */
public static SecureRandom getSecureRandom() throws NoSuchAlgorithmException {
    return SecureRandom.getInstance("SHA1PRNG");
    // return SecureRandom.getInstanceStrong();
}