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.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Given a certificate signing request, produce a signed certificate.
 *
 * @param caKey//  w ww  .  j a v  a 2  s .com
 * @param caCert
 * @param r
 * @param makeAuthority
 * @return
 */
public static X509Certificate fulfillCertRequest(PrivateKey caKey, X509Certificate caCert,
        PKCS10CertificationRequest r, boolean makeAuthority) {
    X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), // the order of O,OU,CN returned is very important
            BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)),
            Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), r.getSubject(),
            getPublicKeyFromInfo(r.getSubjectPublicKeyInfo()));

    try {
        b.addExtension(Extension.basicConstraints, true, new BasicConstraints(makeAuthority));
    } catch (CertIOException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(caKey);
        X509CertificateHolder build = b.build(signer);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(build);
    } catch (OperatorCreationException | CertificateException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:org.apache.camel.component.linkedin.api.LinkedInOAuthRequestFilter.java

@SuppressWarnings("deprecation")
private String getRefreshToken() {
    // authorize application on user's behalf
    webClient.getOptions().setRedirectEnabled(true);

    try {/*w ww.  ja  v  a2  s .  c o m*/
        final String csrfId = String.valueOf(new SecureRandom().nextLong());

        final String encodedRedirectUri = URLEncoder.encode(oAuthParams.getRedirectUri(), "UTF-8");
        final OAuthScope[] scopes = oAuthParams.getScopes();

        final String url;
        if (scopes == null || scopes.length == 0) {
            url = String.format(AUTHORIZATION_URL, oAuthParams.getClientId(), csrfId, encodedRedirectUri);
        } else {
            final int nScopes = scopes.length;
            final StringBuilder builder = new StringBuilder();
            int i = 0;
            for (OAuthScope scope : scopes) {
                builder.append(scope.getValue());
                if (++i < nScopes) {
                    builder.append("%20");
                }
            }
            url = String.format(AUTHORIZATION_URL_WITH_SCOPE, oAuthParams.getClientId(), csrfId,
                    builder.toString(), encodedRedirectUri);
        }
        final HtmlPage authPage = webClient.getPage(url);

        // submit login credentials
        final HtmlForm loginForm = authPage.getFormByName("oauth2SAuthorizeForm");
        final HtmlTextInput login = loginForm.getInputByName("session_key");
        login.setText(oAuthParams.getUserName());
        final HtmlPasswordInput password = loginForm.getInputByName("session_password");
        password.setText(oAuthParams.getUserPassword());
        final HtmlSubmitInput submitInput = loginForm.getInputByName("authorize");

        // disable redirect to avoid loading redirect URL
        webClient.getOptions().setRedirectEnabled(false);

        // validate CSRF and get authorization code
        String redirectQuery;
        try {
            final Page redirectPage = submitInput.click();
            redirectQuery = redirectPage.getUrl().getQuery();
        } catch (FailingHttpStatusCodeException e) {
            // escalate non redirect errors
            if (e.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
                throw e;
            }
            final String location = e.getResponse().getResponseHeaderValue("Location");
            redirectQuery = location.substring(location.indexOf('?') + 1);
        }
        final Map<String, String> params = new HashMap<String, String>();
        final Matcher matcher = QUERY_PARAM_PATTERN.matcher(redirectQuery);
        while (matcher.find()) {
            params.put(matcher.group(1), matcher.group(2));
        }
        final String state = params.get("state");
        if (!csrfId.equals(state)) {
            throw new SecurityException("Invalid CSRF code!");
        } else {
            // return authorization code
            // TODO check results??
            return params.get("code");
        }

    } catch (IOException e) {
        throw new IllegalArgumentException("Error authorizing application: " + e.getMessage(), e);
    }
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static X509Certificate generateCertificate(String domain, int days, KeyPair keyPair)
        throws GeneralSecurityException, IOException {
    X509CertInfo info = new X509CertInfo();
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000l);
    CertificateValidity interval = new CertificateValidity(from, to);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X500Name owner = new X500Name("DC=" + domain);

    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
    info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    info.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));

    AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));

    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(keyPair.getPrivate(), "MD5WithRSA");

    return cert;//from   ww w.j a v  a2 s . c o  m
}

From source file:org.sonar.runner.Main.java

private int executeTask() {
    Stats stats = new Stats().start();
    try {/*ww w .ja v  a  2  s .c om*/
        if (cli.isDisplayStackTrace()) {
            Logs.info("Error stacktraces are turned on.");
        }
        runnerFactory.create(conf.properties()).execute();

    } catch (Exception e) {
        displayExecutionResult(stats, "FAILURE");
        showError("Error during Sonar runner execution", e, cli.isDisplayStackTrace());
        return Exit.ERROR;
    }

    // add permission to buildUserId
    try {
        String buildUserId = System.getProperty("build.user.id");
        Properties props = conf.properties();
        String login = props.getProperty("sonar.login");

        String hostUrl = (String) props.get("sonar.host.url");
        Map<String, String> env = System.getenv();

        String password = SonarContext.getInstance(props).getSonarPassword();
        String project_key = props.getProperty("sonar.projectKey");
        String command;
        Process proc;
        BufferedReader reader;
        String line = "";
        //String tid = (new Long(Thread.currentThread())).toString();
        String tid = String.valueOf(Thread.currentThread().getId());
        String cookie = "cookie-" + Long.toString(new SecureRandom().nextLong());

        // login
        HttpPost httpRequest;
        ArrayList<BasicNameValuePair> postParameters = new ArrayList<BasicNameValuePair>();

        String reqUrl = URIUtils.extractHost(new URI(hostUrl)).toString() + "/dologin";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("username", login));
        postParameters.add(new BasicNameValuePair("password", password));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Login succeed");

        //user permission remove anyone
        reqUrl = hostUrl + "/api/permissions/remove"; //permission=user&group=anyone&component=" + project_key ;
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "user"));
        postParameters.add(new BasicNameValuePair("group", "anyone"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Removed permission 'user' from group anyone");

        //user permission to sonar-users
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=user&group=sonar-users&component=" + project_key;
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "user"));
        postParameters.add(new BasicNameValuePair("group", "sonar-users"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'user' to group sonar-users");

        //admin permission to sonar-administrators
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=admin&group=sonar-administrators&component=" + project_key + "'";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "admin"));
        postParameters.add(new BasicNameValuePair("group", "sonar-administrators"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'admin' to group sonar-administrators");

        //admin permission to self
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=admin&user=" + buildUserId + "&component=" + project_key + "'";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "admin"));
        postParameters.add(new BasicNameValuePair("user", buildUserId));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'admin' to user " + buildUserId);

        //codeviewer permission to self, maybe unnecessary
        reqUrl = hostUrl + "/api/permissions/add"; //?permission=codeviewer&user=" + buildUserId + "&component=" + project_key;
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "codeviewer"));
        postParameters.add(new BasicNameValuePair("user", buildUserId));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Added permission 'codeviewer' to user " + buildUserId);

        //remove codeviewer permission from anyone
        reqUrl = hostUrl + "/api/permissions/remove"; //?permission=codeviewer&group=anyone&component=" + project_key + "'";
        httpRequest = new HttpPost(reqUrl);
        postParameters.clear();
        postParameters.add(new BasicNameValuePair("permission", "codeviewer"));
        postParameters.add(new BasicNameValuePair("group", "anyone"));
        postParameters.add(new BasicNameValuePair("component", project_key));
        httpRequest.setEntity(new UrlEncodedFormEntity(postParameters));
        doRequest(httpRequest);
        Logs.info("Removed permission 'codeviewer' from group anyone");

    } catch (Exception e) {
        showError("Error during Sonar runner execution", e, cli.isDisplayStackTrace());
        return Exit.ERROR;
    }

    displayExecutionResult(stats, "SUCCESS");
    return Exit.SUCCESS;
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

void install(String[] redirectEndpointUrls, String[] postLogoutRedirectUrls, String logoutUrl)
        throws Exception {
    String domainControllerFQDN = this.relyingPartyConfig.getOpFQDN();
    int domainControllerPort = Integer.parseInt(this.relyingPartyConfig.getOpListeningPort());
    String tenant = this.relyingPartyConfig.getTenant();

    // retrieve OIDC meta data
    MetadataHelper metadataHelper = new MetadataHelper.Builder(domainControllerFQDN)
            .domainControllerPort(domainControllerPort).tenant(tenant).keyStore(this.keyStore).build();

    ProviderMetadata providerMetadata = metadataHelper.getProviderMetadata();
    RSAPublicKey providerPublicKey = metadataHelper.getProviderRSAPublicKey(providerMetadata);

    // create a non-registered OIDC client and get bearer tokens by admin user name/password
    ConnectionConfig connectionConfig = new ConnectionConfig(providerMetadata, providerPublicKey,
            this.keyStore);
    ClientConfig clientConfig = new ClientConfig(connectionConfig, null, null);
    OIDCClient nonRegisteredClient = new OIDCClient(clientConfig);
    TokenSpec tokenSpec = new TokenSpec.Builder(TokenType.BEARER)
            .resourceServers(Arrays.asList("rs_admin_server")).build();
    OIDCTokens oidcTokens = nonRegisteredClient.acquireTokensByPassword(
            this.relyingPartyConfig.getAdminUsername(), this.relyingPartyConfig.getAdminPassword(), tokenSpec);

    // create a private/public key pair, generate a certificate and assign it to a solution user name.
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair keypair = keyGen.generateKeyPair();
    String solutionUserName = this.relyingPartyConfig.getClientPrefix() + UUID.randomUUID().toString();
    X509Certificate clientCertificate = generateCertificate(keypair, solutionUserName);

    // create REST idm client
    IdmClient idmClient = createIdmClient(oidcTokens.getAccessToken(), domainControllerFQDN,
            domainControllerPort);//from w  w w  . j av a 2 s. co  m

    VmdirClient vmdirClient = createVMdirClient(oidcTokens.getAccessToken(), domainControllerFQDN,
            domainControllerPort);

    // create a solution user
    CertificateDTO certificateDTO = new CertificateDTO.Builder()
            .withEncoded(convertToBase64PEMString(clientCertificate)).build();
    SolutionUserDTO solutionUserDTO = new SolutionUserDTO.Builder().withName(solutionUserName)
            .withDomain(tenant).withCertificate(certificateDTO).build();
    vmdirClient.solutionUser().create(tenant, solutionUserDTO);

    // add the solution user to ActAs group
    List<String> members = Arrays.asList(solutionUserName + "@" + tenant);
    vmdirClient.group().addMembers(tenant, "ActAsUsers", tenant, members,
            com.vmware.directory.rest.common.data.MemberType.USER);

    // register a OIDC client
    OIDCClientMetadataDTO oidcClientMetadataDTO = new OIDCClientMetadataDTO.Builder()
            .withRedirectUris(Arrays.asList(redirectEndpointUrls))
            .withPostLogoutRedirectUris(Arrays.asList(postLogoutRedirectUrls)).withLogoutUri(logoutUrl)
            .withTokenEndpointAuthMethod("private_key_jwt")
            .withCertSubjectDN(clientCertificate.getSubjectDN().getName())
            .withAuthnRequestClientAssertionLifetimeMS(2 * 60 * 1000L).build();
    OIDCClientDTO oidcClientDTO = idmClient.oidcClient().register(tenant, oidcClientMetadataDTO);

    // persist data involved installation in files so they can be picked up in case server reboots
    savePublicKey(this.relyingPartyConfig.getOpPublickeyFile(), providerPublicKey);
    savePrivateKey(this.relyingPartyConfig.getRpPrivatekeyFile(), keypair.getPrivate());
    writeObject(this.relyingPartyConfig.getRpCertificateFile(), clientCertificate);
    writeObject(this.relyingPartyConfig.getRpInfoFile(), oidcClientDTO.getClientId());
    writeObject(this.relyingPartyConfig.getRpListeningPortFile(), this.relyingPartyConfig.getRpListeningPort());
}

From source file:edu.tamu.tcat.crypto.spongycastle.SecureTokenImpl.java

private byte[] createIV() {
    SecureRandom random = new SecureRandom();
    byte[] iv = new byte[ivSize / 8];
    random.nextBytes(iv);/*from  w  w  w.  j a v a  2  s. co m*/
    return iv;
}

From source file:com.trustly.api.SignedAPI.java

/**
 * Generates a random messageID. Good for testing.
 * @return return a random generated messageid.
 *///ww w.j  a va2  s . c o  m
public String newMessageID() {
    SecureRandom random = new SecureRandom();

    return new BigInteger(130, random).toString(32);
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

public static KeyPair generateKeyPair(int bits) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(bits, new SecureRandom());
    return keyGen.generateKeyPair();
}

From source file:com.openvcx.webcall.ConferenceCreateServlet.java

/**
 * <i>javax.Servlet</i> overridden initializer method
 *///from  w w w .j  ava2s.c om
@Override
public void init(ServletConfig c) throws ServletException {
    logger.debug("init start");
    super.init(c);

    try {

        //
        // Load the config file defined in web.xml 'sip-ngconference.conf'
        //
        String configFilePath = getServletContext().getInitParameter("config");
        m_config = new Configuration(configFilePath);

        m_confDefDir = m_config.getString(CONFIG_CONFERENCE_DEF, CONFERNCE_CONFIG_DIR);
        if (m_confDefDir.charAt(m_confDefDir.length() - 1) != File.separatorChar) {
            m_confDefDir += File.separatorChar;
        }
        m_confDefDirAuto = m_confDefDir + "auto/";

        m_tempDir = m_config.getString(CONFIG_CONFERENCE_TEMP_DIR, CONFERENCE_TEMP_DIR);
        if (m_tempDir.charAt(m_tempDir.length() - 1) != File.separatorChar) {
            m_tempDir += File.separatorChar;
        }

        if (null == (m_mediaPortalAddress = m_config.getString(CONFIG_MEDIAPORTAL_LISTENER_ADDRESS, null))) {
            // Try to lookup the legacy naming convention if the user has somehow retained
            // an old sip-ngconference.conf
            m_mediaPortalAddress = m_config.getString(CONFIG_MEDIAPORTAL_LISTENER_ADDRESS_LEGACY, null);
        }
        m_bAutoProvision = m_config.getBoolean(CONFIG_CONFERENCE_PROVISION_AUTO, m_bAutoProvision);

        logger.info("confDefDirAuto: '" + m_confDefDirAuto + "', tempDir: '" + m_tempDir + "', mediaPortal: '"
                + m_mediaPortalAddress + ", provision.auto: " + m_bAutoProvision);

        m_rand = new SecureRandom();

    } catch (Exception e) {
        LogUtil.printError(logger, "init: ", e);
        throw new ServletException(e);
    }

    logger.debug("init done");

}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private void addSslConnection(URLConnection connection) {
    if (connection instanceof HttpsURLConnection) {
        try {//from   w w  w. ja v  a  2s .  co  m
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { new AcceptAllTrustManager() }, new SecureRandom());
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new AcceptAllHostnameVerifier());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}