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:org.kievguide.controller.UserController.java

@RequestMapping(value = "/settingssave", method = RequestMethod.POST)
public ModelAndView settingsSave(@CookieValue(value = "userstatus", defaultValue = "guest") String useremail,
        @RequestParam("firstname") String firstname, @RequestParam("lastname") String lastname,
        @RequestParam("email") String email, @RequestParam("password") String password,
        @RequestParam("photosrc") MultipartFile file, HttpServletResponse response, HttpServletRequest request)
        throws FileNotFoundException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    SecureRandom random = new SecureRandom();
    String photoname = new BigInteger(130, random).toString(32);
    Place place = new Place();

    User user = userService.searchUser(useremail);
    user.setFirstname(firstname);/*from   w  ww. j  a  va2s . c  o  m*/
    user.setLastname(lastname);
    user.setPassword(password);
    user.setEmail(email);
    if (!file.isEmpty()) {
        String folder = request.getSession().getServletContext().getRealPath("");
        folder = folder.substring(0, 30);
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(folder + "/src/main/webapp/img/" + photoname + ".jpg")));
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
        user.setPhotosrc("img/" + photoname + ".jpg");
    }

    userService.addUser(user);
    Cookie userCookie = new Cookie("userstatus", user.getEmail());
    response.addCookie(userCookie);
    String userStatus = Util.userPanel(user.getEmail());
    modelAndView.addObject("userstatus", userStatus);
    return new ModelAndView("redirect:" + "firstrequest");
}

From source file:com.orange.oidc.secproxy_service.MySecureProxy.java

public String getPrivateKeyJwt(String token_endpoint) {
    String privateKeyJwt = null;/*from  w  ww  .j  ava2s .c  om*/
    try {
        JSONObject jo = new JSONObject();
        jo.put("iss", SECURE_PROXY_client_id);
        jo.put("sub", SECURE_PROXY_client_id);
        jo.put("aud", token_endpoint);
        jo.put("jti", new BigInteger(130, new SecureRandom()).toString(32));
        long now = Calendar.getInstance().getTimeInMillis() / 1000;
        // expires in 3 minutes
        jo.put("exp", "" + (now + 180));

        String dataToSign = null;
        try {
            dataToSign = KryptoUtils.encodeB64(jo.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (dataToSign != null && dataToSign.length() > 0) {
            // sign with proxy private key
            String signH = "{\"alg\":\"" + alg + "\"}";
            privateKeyJwt = KryptoUtils.signJWS(dataToSign, signH, alg, RsaKeyProxy.privRsaKey);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return privateKeyJwt;
}

From source file:com.alibaba.wasp.zookeeper.RecoverableZooKeeper.java

public RecoverableZooKeeper(String quorumServers, int sessionTimeout, Watcher watcher, int maxRetries,
        int retryIntervalMillis) throws IOException {
    this.zk = new ZooKeeper(quorumServers, sessionTimeout, watcher);
    this.retryCounterFactory = new RetryCounterFactory(maxRetries, retryIntervalMillis);

    // the identifier = processID@hostName
    this.identifier = ManagementFactory.getRuntimeMXBean().getName();
    LOG.info("The identifier of this process is " + identifier);
    this.id = Bytes.toBytes(identifier);

    this.watcher = watcher;
    this.sessionTimeout = sessionTimeout;
    this.quorumServers = quorumServers;
    salter = new SecureRandom();
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClientWithProxy(byte[] sslCertificateBytes, String proxyAddress,
        int proxyPort) {
    DefaultHttpClient httpClient;//from  w  w  w .java  2 s. co m
    Certificate[] sslCertificate;
    HttpHost proxy;

    httpClient = new DefaultHttpClient();
    try {
        sslCertificate = convertByteArrayToCertificate(sslCertificateBytes);

        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        proxy = new HttpHost(proxyAddress, proxyPort, "https");
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:com.predic8.membrane.core.interceptor.balancer.ClusterNotificationInterceptorTest.java

private GetMethod getSecurityTestMethod(long time) throws Exception {
    String qParams = "cluster=c3&host=node1.clustera&port=3018&time=" + time + "&nonce="
            + new SecureRandom().nextLong();
    return new GetMethod("http://localhost:3002/clustermanager/up?data="
            + URLEncoder.encode(getEncryptedQueryString(qParams), "UTF-8"));
}

From source file:com.telefonica.iot.cosmos.hive.authprovider.HttpClientFactory.java

/**
 * Gets a SSL SchemeRegistry object accepting all the X509 certificates by default.
 * @return A SSL SchemeRegistry object./*from   w w w . ja  v  a  2s  . c o m*/
 */
private SchemeRegistry getSSLSchemeRegistry() {
    // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0

    SSLContext sslContext;

    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        LOGGER.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")");
        return null;
    } // try catch // try catch

    try {
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            } // getAcceptedIssuers

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            } // getAcceptedIssuers

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            } // checkServerTrusted
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        LOGGER.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")");
        return null;
    } // try catch // try catch

    if (sslContext == null) {
        LOGGER.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)");
        return null;
    } // if

    SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    return schemeRegistry;
}

From source file:de.micromata.genome.gwiki.auth.GWikiAuthorizationBase.java

private Pair<String, String> createAuthToken(GWikiContext ctx, String user, String password) {
    int tklength = 16;
    Random r = new SecureRandom();
    String internalToken = RandomStringUtils.random(tklength, 32, 127, true, true, null, r);
    return Pair.make(user + ":" + internalToken, internalToken);

}

From source file:com.titilink.common.app.EncryptDecryptUtil.java

public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, SignatureException {
    //// w  w  w  . j a va2  s . c  o  m
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    //?
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    //??
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom());
    byte[] cipherData = cipher
            .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8")));

    //
    Cipher cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom());
    byte[] plainData = cipher1.doFinal(cipherData);
    System.out.println(new String(plainData, Charset.forName("UTF-8")));

    //???????
    Signature signature = Signature.getInstance("MD5withRSA");
    signature.initSign(privateKey);
    signature.update(cipherData);
    byte[] signData = signature.sign();

    //?????
    Signature signature1 = Signature.getInstance("MD5withRSA");
    signature1.initVerify(publicKey);
    signature1.update(cipherData);
    System.out.println(signature1.verify(signData));

}

From source file:com.google.cloud.backend.config.BackendConfigManager.java

/**
 * Returns the current configuration of the backend.
 * //from  w  w w  .ja  v  a2  s.c  om
 * @result Entity that represents the current configurations of the backend.
 */
protected Entity getConfiguration() {

    // check memcache
    Key key = getKey();
    Entity config = (Entity) memcache.get(getMemKeyForConfigEntity(key));
    if (config != null) {
        return config;
    }

    // get from datastore
    try {
        config = datastoreService.get(key);
    } catch (EntityNotFoundException e) {
        // Default to the LOCKED authentication mode and disabled push
        // notification
        config = new Entity(key);
        config.setProperty(AUTHENTICATION_MODE, AuthMode.LOCKED.name());
        config.setProperty(PUSH_ENABLED, false);
        config.setProperty(LAST_SUBSCRIPTION_DELETE_TIMESTAMP, null);

        // Generate unique secret for this app to be used for XSRF token
        SecureRandom rnd = new SecureRandom();
        String secret = new BigInteger(256, rnd).toString();
        config.setProperty(PER_APP_SECRET_KEY, secret);

        datastoreService.put(config);
    }

    // put the config entity to memcache and return it
    memcache.put(getMemKeyForConfigEntity(key), config);
    return config;
}

From source file:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java

public DataChannelImpl(PeerConnection parent) throws IOException {
    logger.info("Initializing {}", this.getClass().getName());
    this.dtlsServer = new WebrtcDtlsServer(parent.getKeyStoreInfo());
    this.parent = parent;
    this.channel = new DatagramSocket();
    this.channel.setReceiveBufferSize(16000000);
    this.receiveBufferSize = this.channel.getReceiveBufferSize();
    this.channel.setSendBufferSize(16000000);
    this.sendBufferSize = this.channel.getSendBufferSize();
    //this.channel.setReuseAddress(true);
    this.port = channel.getLocalPort();
    this.serverProtocol = new DTLSServerProtocol(new SecureRandom());
    this.mode = ConnectionMode.BINDING;

    /**//ww w  . j  av a 2s.  c  o  m
     * Print monitoring information
     */
    this.monitor = () -> {
        while (running && channel.isBound()) {
            try {
                Thread.sleep(3000);
                sctpService.runMonitoring();
            } catch (Exception e) {
                logger.error("Logging error", e);
            }
        }
    };

    /**
     * Create heartbeat message
     */
    this.heartBeat = () -> {
        while (running && channel.isBound()) {
            try {
                Thread.sleep(5000);
                byte[] beat = sctpService.createHeartBeat();
                logger.debug("Sending heartbeat: " + Hex.encodeHexString(beat));
                putDataOnWire(beat);
            } catch (Exception e) {
                logger.error("HeartBeat error: ", e);
            }
        }
    };

    /**
     * Acknowledge received data
     */
    this.sackSender = () -> {
        while (running && channel.isBound()) {
            try {
                Thread.sleep(1); //sleep to not go ham on cpu
                logger.trace("Creating sack:");
                byte[] beat = sctpService.createSackMessage();
                if (beat.length > 0) {
                    logger.trace("Sending sack: " + Hex.encodeHexString(beat));
                    putDataOnWire(beat);
                } else {
                    logger.trace("Already on latest sack, no send");
                }

            } catch (Exception e) {
                logger.error("Sack error: ", e);
            }

        }
    };

    /**
     * Resends non acknowledged sent messages
     */
    this.reSender = () -> {
        while (running && channel.isBound() && !channel.isClosed()) {
            try {
                Thread.sleep(250);
                List<byte[]> msgs = sctpService.getMessagesForResend();
                if (!msgs.isEmpty()) {
                    msgs.forEach(i -> {
                        try {
                            Thread.sleep(1); //Sleep to let others work a bit
                            logger.debug("Resending data: " + Hex.encodeHexString(i));
                            putDataOnWire(i);
                        } catch (InterruptedException e) {
                            logger.error("Resend error: ", e);
                        }
                    });
                }
            } catch (Exception e) {
                logger.error("Resend error: ", e);
            }
        }
    };
}