Example usage for java.security SecureRandom SecureRandom

List of usage examples for java.security SecureRandom SecureRandom

Introduction

In this page you can find the example usage for java.security SecureRandom SecureRandom.

Prototype

public SecureRandom() 

Source Link

Document

Constructs a secure random number generator (RNG) implementing the default random number algorithm.

Usage

From source file:net.solarnetwork.node.setup.test.DefaultKeystoreServiceTest.java

@BeforeClass
public static void setupClass() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    CA_KEY_PAIR = keyGen.generateKeyPair();
    CA_CERT = PKITestUtils.generateNewCACert(CA_KEY_PAIR.getPublic(), TEST_CA_DN, null,
            CA_KEY_PAIR.getPrivate(), TEST_CA_DN);

    CA_SUB_KEY_PAIR = keyGen.generateKeyPair();
    CA_SUB_CERT = PKITestUtils.generateNewCACert(CA_SUB_KEY_PAIR.getPublic(), TEST_CA_SUB_DN, CA_CERT,
            CA_KEY_PAIR.getPrivate(), TEST_CA_DN);
}

From source file:net.vexelon.myglob.utils.TrustAllSocketFactory.java

public TrustAllSocketFactory() throws InvalidAlgorithmParameterException {
    super();/*from  www.  ja  va2s  .  c  om*/

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }
    } };

    SecureRandom secureRND = new SecureRandom();

    try {
        sslContext = SSLContext.getInstance(org.apache.http.conn.ssl.SSLSocketFactory.TLS);
        sslContext.init(null, trustAllCerts, secureRND);
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidAlgorithmParameterException("Failed to initlize TLS context!", e);
    } catch (KeyManagementException e) {
        throw new InvalidAlgorithmParameterException("Failed to init SSL context!", e);
    }

    socketFactory = sslContext.getSocketFactory();
}

From source file:org.apache.reef.runtime.hdinsight.client.sslhacks.UnsafeClientConstructor.java

private SSLContext getSSLContext() throws KeyManagementException, NoSuchAlgorithmException {
    final SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(new KeyManager[0], new TrustManager[] { new UnsafeTrustManager() }, new SecureRandom());
    return sc;/*from   ww w  .  j a  v  a2 s. c om*/
}

From source file:com.gfw.press.encrypt.Encrypt.java

public Encrypt() {
    super();/*from w  w w.  jav a 2  s. c om*/
    secureRandom = new SecureRandom();
    try {
        cipher = Cipher.getInstance("AES/CFB/NoPadding");
        keyGenerator = KeyGenerator.getInstance("AES");
    } catch (NoSuchAlgorithmException | NoSuchPaddingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:TSAClient.java

/**
 *
 * @param messageImprint imprint of message contents
 * @return the encoded time stamp token//www. j  a va 2s.c o m
 * @throws IOException if there was an error with the connection or data from the TSA server,
 *                     or if the time stamp response could not be validated
 */
public byte[] getTimeStampToken(byte[] messageImprint) throws IOException {
    digest.reset();
    byte[] hash = digest.digest(messageImprint);

    // 32-bit cryptographic nonce
    SecureRandom random = new SecureRandom();
    int nonce = random.nextInt();

    // generate TSA request
    TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
    tsaGenerator.setCertReq(true);
    ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm());
    TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));

    // get TSA response
    byte[] tsaResponse = getTSAResponse(request.getEncoded());

    TimeStampResponse response;
    try {
        response = new TimeStampResponse(tsaResponse);
        response.validate(request);
    } catch (TSPException e) {
        throw new IOException(e);
    }

    TimeStampToken token = response.getTimeStampToken();
    if (token == null) {
        throw new IOException("Response does not have a time stamp token");
    }

    return token.getEncoded();
}

From source file:jenkins.security.RSAConfidentialKey.java

/**
 * Obtains the private key (lazily.)/*from   w  w w. j  a va 2 s. c  o  m*/
 * <p>
 * This method is not publicly exposed as per the design principle of {@link ConfidentialKey}.
 * Instead of exposing private key, define methods that use them in specific way, such as
 * {@link RSADigitalSignatureConfidentialKey}.
 *
 * @throws Error
 *      If key cannot be loaded for some reasons, we fail.
 */
protected synchronized RSAPrivateKey getPrivateKey() {
    try {
        if (priv == null) {
            byte[] payload = load();
            if (payload == null) {
                KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
                gen.initialize(2048, new SecureRandom()); // going beyond 2048 requires crypto extension
                KeyPair keys = gen.generateKeyPair();
                priv = (RSAPrivateKey) keys.getPrivate();
                pub = (RSAPublicKey) keys.getPublic();
                store(priv.getEncoded());
            } else {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                priv = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(payload));

                RSAPrivateCrtKey pks = (RSAPrivateCrtKey) priv;
                pub = (RSAPublicKey) keyFactory
                        .generatePublic(new RSAPublicKeySpec(pks.getModulus(), pks.getPublicExponent()));
            }
        }
        return priv;
    } catch (IOException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    } catch (GeneralSecurityException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    }
}

From source file:com.jiubang.core.util.HttpUtils.java

/**
 * Open an URL connection. If HTTPS, accepts any certificate even if not
 * valid, and connects to any host name.
 * /*from  w  w w  .  j a v a 2  s  .com*/
 * @param url
 *            The destination URL, HTTP or HTTPS.
 * @return The URLConnection.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private static URLConnection getConnection(URL url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException {
    URLConnection conn = url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        // Trust all certificates
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom());
        SSLSocketFactory socketFactory = context.getSocketFactory();
        ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);

        // Allow all hostnames
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);

    }
    conn.setConnectTimeout(SOCKET_TIMEOUT);
    conn.setReadTimeout(SOCKET_TIMEOUT);
    return conn;
}

From source file:adminpassword.AESDemo.java

public String generateSalt() {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[20];
    random.nextBytes(bytes);//from www . j a v a  2 s.com
    String s = new String(bytes);
    return s;
}

From source file:demo.oauth.server.controllers.ApplicationController.java

@RequestMapping("/registerClient")
public ModelAndView registerApp(@ModelAttribute("client") ClientApp clientApp) throws Exception {

    if (StringUtils.isEmpty(clientApp.getClientName())) {
        clientApp.setError("Client name field is required!");

        return handleInternalRedirect(clientApp);
    }/* ww  w.  jav  a 2s.c  o  m*/

    MD5SequenceGenerator tokenGen = new MD5SequenceGenerator();
    Principal principal = SecurityContextHolder.getContext().getAuthentication();
    String consumerKey = clientApp.getConsumerKey();
    if (StringUtils.isEmpty(consumerKey)) {
        consumerKey = tokenGen
                .generate((principal.getName() + clientApp.getClientName()).getBytes(StandardCharsets.UTF_8));
    }

    String secretKey = tokenGen.generate(new SecureRandom().generateSeed(20));

    Client clientInfo = new Client(consumerKey, secretKey, clientApp.getClientName(), null);
    clientInfo.setCallbackURI(clientApp.getCallbackURL());
    clientInfo.setLoginName(principal.getName());

    Client authNInfo = clientManager.registerNewClient(consumerKey, clientInfo);
    if (authNInfo != null) {
        clientApp.setError("Client already exists!");

        return handleInternalRedirect(clientApp);
    }

    ModelAndView modelAndView = new ModelAndView("clientDetails");
    modelAndView.getModel().put("clientInfo", clientInfo);

    return modelAndView;
}

From source file:com.fegor.alfresco.security.crypto.Crypto.java

/**
 * Encryption configuration//www .j ava  2  s  .c o m
 * 
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void configEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    salt_pos = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(salt_pos);

    if (logger.isDebugEnabled())
        logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]");

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /*
     * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files
     * .shtml
     */
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    eCipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = eCipher.getParameters();

    vector_init = params.getParameterSpec(IvParameterSpec.class).getIV();

    if (logger.isDebugEnabled())
        logger.debug(
                this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]");
}