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.jmangos.realm.network.packet.auth.client.CMD_AUTH_LOGON_CHALLENGE.java

@Override
protected void readImpl() throws BufferUnderflowException, RuntimeException {

    readC();//from  w  w  w  .  j a v  a 2 s  .  c  o m
    if (readC() == WoWAuthResponse.WOW_SUCCESS.getMessageId()) {
        final SecureRandom random = new SecureRandom();
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
            return;
        }
        final BigInteger k = new BigInteger("3");
        final byte[] Bb = readB(32);
        final BigInteger g = new BigInteger(readB(readC()));
        final byte[] Nb = readB(readC());
        final byte[] saltb = readB(32);
        /* byte[] unk3 = */readB(16);
        readC();
        ArrayUtils.reverse(Bb);
        final BigInteger B = new BigInteger(1, Bb);
        ArrayUtils.reverse(Bb);
        ArrayUtils.reverse(Nb);
        final BigInteger N = new BigInteger(1, Nb);
        ArrayUtils.reverse(Nb);
        final BigInteger a = new BigInteger(1, random.generateSeed(19));

        final byte[] passhash = sha.digest(this.config.AUTH_LOGIN.toUpperCase().concat(":")
                .concat(this.config.AUTH_PASSWORD.toUpperCase()).getBytes(Charset.forName("UTF-8")));
        sha.update(saltb);
        sha.update(passhash);

        final byte[] xhash = sha.digest();
        ArrayUtils.reverse(xhash);
        final BigInteger x = new BigInteger(1, xhash);
        logger.debug("x:" + x.toString(16).toUpperCase());
        final BigInteger v = g.modPow(x, N);
        logger.debug("v:" + v.toString(16).toUpperCase());
        final BigInteger A = g.modPow(a, N);
        logger.debug("A:" + A.toString(16).toUpperCase());
        logger.debug("B:" + B.toString(16).toUpperCase());
        this.ahash = A.toByteArray();
        ArrayUtils.reverse(this.ahash);
        sha.update(this.ahash);
        sha.update(Bb);
        final byte[] hashu = sha.digest();
        ArrayUtils.reverse(hashu);
        final BigInteger u = new BigInteger(1, hashu);
        logger.debug("u:" + u.toString(16).toUpperCase());
        final BigInteger S = (B.subtract(k.multiply(g.modPow(x, N)))).modPow(a.add(u.multiply(x)), N);

        final byte[] full_S = S.toByteArray();
        ArrayUtils.reverse(full_S);
        logger.debug("t:" + StringUtils.toHexString(full_S));
        final byte[] s1_hash = new byte[16];
        final byte[] s2_hash = new byte[16];
        for (int i = 0; i < 16; i++) {
            s1_hash[i] = full_S[i * 2];
            s2_hash[i] = full_S[(i * 2) + 1];
        }
        final byte[] t1 = sha.digest(s1_hash);
        final byte[] t2 = sha.digest(s2_hash);
        final byte[] vK = new byte[40];
        for (int i = 0; i < 20; i++) {
            vK[i * 2] = t1[i];
            vK[(i * 2) + 1] = t2[i];
        }

        byte[] hash = new byte[20];
        logger.debug("N:" + N.toString(16).toUpperCase());
        hash = sha.digest(Nb);

        logger.debug("hash:" + new BigInteger(1, hash).toString(16).toUpperCase());

        byte[] gH = new byte[20];
        sha.update(g.toByteArray());
        gH = sha.digest();
        for (int i = 0; i < 20; ++i) {
            hash[i] ^= gH[i];
        }

        byte[] t4 = new byte[20];
        t4 = sha.digest(this.config.AUTH_LOGIN.toUpperCase().getBytes(Charset.forName("UTF-8")));

        sha.update(hash);
        logger.debug("hash:" + StringUtils.toHexString(hash));
        sha.update(t4);
        logger.debug("t4:" + StringUtils.toHexString(t4));
        sha.update(saltb);
        logger.debug("saltb:" + StringUtils.toHexString(saltb));
        sha.update(this.ahash);
        logger.debug("ahash:" + StringUtils.toHexString(this.ahash));
        sha.update(Bb);
        logger.debug("Bb:" + StringUtils.toHexString(Bb));
        sha.update(vK);
        logger.debug("vK:" + StringUtils.toHexString(vK));
        this.m1 = sha.digest();

        sha.update(this.ahash);
        sha.update(this.m1);
        sha.update(vK);
        logger.debug("m1 value" + StringUtils.toHexString(this.m1));
        @SuppressWarnings("unused")
        final byte[] m2 = sha.digest();

        final ChannelPipeline pipeline = getClient().getChannel().getPipeline();
        ((RealmToAuthChannelHandler) pipeline.getLast()).setSeed(vK);

    } else {
        getChannel().getPipeline().remove("handler");
        getChannel().getPipeline().remove("eventlog");
        getChannel().getPipeline().remove("executor");
        getChannel().close();
        getChannel().getFactory().releaseExternalResources();
    }
}

From source file:com.cloudbees.tftwoway.Client.java

private static SSLContext createSSLContext() throws Exception {
    KeyManager[] serverKeyManagers = getKeyManager();
    TrustManager[] serverTrustManagers = getTrustManager();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(serverKeyManagers, serverTrustManagers, new SecureRandom());

    return sslContext;
}

From source file:com.intel.chimera.stream.AbstractCryptoStreamTest.java

@Before
public void before() throws IOException {
    Random random = new SecureRandom();
    random.nextBytes(data);/* www.  j  a v a 2s  . c  om*/
    random.nextBytes(key);
    random.nextBytes(iv);
    setUp();
    prepareData();
}

From source file:com.orange.cloud.servicebroker.filter.core.config.OkHttpClientConfig.java

@Bean
public OkHttpClient squareHttpClient() {
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override/*from   w w w  . ja v a2  s. c om*/
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCerts() };

    SSLSocketFactory sslSocketFactory = null;
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        sslSocketFactory = (SSLSocketFactory) sc.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        new IllegalArgumentException(e);
    }

    log.info("===> configuring OkHttp");
    OkHttpClient.Builder ohc = new OkHttpClient.Builder().protocols(Arrays.asList(Protocol.HTTP_1_1))
            .followRedirects(true).followSslRedirects(true).hostnameVerifier(hostnameVerifier)
            .sslSocketFactory(sslSocketFactory).addInterceptor(LOGGING_INTERCEPTOR);

    if ((this.proxyHost != null) && (this.proxyHost.length() > 0)) {
        log.info("Activating proxy on host {} port {}", this.proxyHost, this.proxyPort);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxyHost, this.proxyPort));
        ohc.proxy(proxy);
        ohc.proxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Arrays.asList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress socket, IOException e) {
                throw new IllegalArgumentException("connection to proxy failed", e);
            }
        });
    }

    return ohc.build();
}

From source file:io.kodokojo.service.redis.AbstractRedisStore.java

protected String generateId() {
    try (Jedis jedis = pool.getResource()) {

        SecureRandom secureRandom = new SecureRandom();
        String rand = new BigInteger(128, secureRandom).toString(10);
        String id = saltKey + rand + jedis.incr(getGenerateIdKey()).toString();
        String newId = RedisUtils.hexEncode(messageDigest.digest(id.getBytes()));
        return newId;
    }/*from   ww  w . j a  v  a 2s.  c  o  m*/
}

From source file:com.bitsofproof.supernode.api.BIP39Test.java

@Test
public void bip39EncodeDecodeTest() throws IOException, JSONException, ValidationException {
    JSONObject testData = readObject(TESTS);
    JSONArray english = testData.getJSONArray("english");
    for (int i = 0; i < testData.length(); ++i) {
        JSONArray test = english.getJSONArray(i);
        byte[] m = BIP39.decode(test.getString(1), "BOP");
        assertTrue(test.getString(1).equals(BIP39.encode(m, "BOP")));
    }/*from   ww  w.  java  2  s  .  co m*/
    SecureRandom random = new SecureRandom();
    for (int i = 0; i < 1000; ++i) {
        byte[] secret = new byte[32];
        random.nextBytes(secret);
        String e = BIP39.encode(secret, "BOP");
        assertTrue(Arrays.equals(BIP39.decode(e, "BOP"), secret));
    }
}

From source file:com.amazonaws.cognito.devauthsample.AESEncryption.java

private static byte[] getIv() {
    byte[] iv = new byte[16];
    new SecureRandom().nextBytes(iv);

    return iv;/*from w w w .  j a v  a  2  s  .c  o m*/
}

From source file:org.gege.caldavsyncadapter.caldav.EasySSLSocketFactory.java

private EasySSLSocketFactory() {
    super();//from  w w  w.  j av  a2 s.  co m
    TrustManager[] tm = new TrustManager[] { new X509TrustManager() {

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

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

    } };
    try {
        this.sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
        this.sslcontext.init(null, tm, new SecureRandom());
        this.socketfactory = this.sslcontext.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Faild to instantiate TrustAllSSLSocketFactory!", e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "Failed to instantiate TrustAllSSLSocketFactory!", e);
    }
}

From source file:com.orchestra.portale.externalauth.FbAuthenticationManager.java

public static User fbLoginJs(HttpServletRequest request, HttpServletResponse response,
        UserRepository userRepository) {

    //Get access_token from request
    String access_token = request.getParameter("access_token");
    User user = null;//from  www  . ja v a2s .c  o  m

    if (StringUtils.isNotEmpty(access_token)) {

        try {

            Boolean validity = FacebookUtils.ifTokenValid(access_token);

            //if token is valid, retrieve userid and email from Facebook
            if (validity) {
                Map<String, String> userId_mail = FacebookUtils.getUserIDMail(access_token);
                String id = userId_mail.get("id");
                String email = userId_mail.get("email");

                try {
                    user = fbUserCheck(id, email, userRepository);
                } catch (UserNotFoundException ioex) {
                    /*Retrieve User Data to Registration*/
                    Map<String, String> userData = FacebookUtils.getUserData(access_token);

                    /*Create User*/
                    com.orchestra.portale.persistence.sql.entities.User new_user = new com.orchestra.portale.persistence.sql.entities.User();
                    new_user.setFbEmail(userData.get("email"));
                    new_user.setFbUser(userData.get("id"));
                    new_user.setUsername(userData.get("email"));
                    new_user.setFirstName(userData.get("firstName"));
                    new_user.setLastName(userData.get("lastName"));
                    new_user.setPassword(new BigInteger(130, new SecureRandom()).toString(32));

                    /*Create Role*/
                    com.orchestra.portale.persistence.sql.entities.Role new_user_role = new com.orchestra.portale.persistence.sql.entities.Role();
                    new_user_role.setRole("ROLE_USER");
                    new_user_role.setUser(new_user);
                    ArrayList<com.orchestra.portale.persistence.sql.entities.Role> new_user_roles = new ArrayList<com.orchestra.portale.persistence.sql.entities.Role>();
                    new_user_roles.add(new_user_role);
                    new_user.setRoles(new_user_roles);

                    /*Save User*/
                    userRepository.save(new_user);

                    //Save user image
                    try {
                        String img_url = userData.get("img");
                        String user_id_img = userRepository.findByUsername(new_user.getUsername()).getId()
                                .toString();

                        HttpSession session = request.getSession();
                        ServletContext sc = session.getServletContext();

                        String destination = sc.getRealPath("/") + "dist" + File.separator + "user"
                                + File.separator + "img" + File.separator + user_id_img + File.separator;

                        NetworkUtils.saveImageFromURL(img_url, destination, "avatar.jpg");

                    } catch (MalformedURLException ex) {
                        throw new FacebookException();
                    } catch (IOException ioexc) {
                        ioexc.getMessage();
                    }

                    /*Create Spring User*/
                    boolean enabled = true;
                    boolean accountNonExpired = true;
                    boolean credentialsNonExpired = true;
                    boolean accountNonLocked = true;

                    user = new User(new_user.getUsername(), new_user.getPassword().toLowerCase(), enabled,
                            accountNonExpired, credentialsNonExpired, accountNonLocked,
                            getAuthorities(new_user.getRoles()));

                }

            }

        } catch (FacebookException ioex) {
            ioex.printStackTrace();
        }

    }

    return user;
}

From source file:org.exfio.weave.storage.StorageContext.java

public String generateWeaveID() {
    SecureRandom rnd = new SecureRandom();
    byte[] weaveID = rnd.generateSeed(9);
    return Base64.encodeToString(weaveID, Base64.NO_PADDING | Base64.NO_WRAP | Base64.URL_SAFE);
}