Example usage for java.security SecureRandom nextBytes

List of usage examples for java.security SecureRandom nextBytes

Introduction

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

Prototype

@Override
public void nextBytes(byte[] bytes) 

Source Link

Document

Generates a user-specified number of random bytes.

Usage

From source file:org.owasp.benchmark.testcode.BenchmarkTest00193.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = request.getHeader("vector");
    if (param == null)
        param = "";

    String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param);

    try {/*from   w w  w.  j ava2s. c o m*/
        java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");

        // Get 40 random bytes
        byte[] randomBytes = new byte[40];
        secureRandomGenerator.nextBytes(randomBytes);

        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);

        String user = "SafeByron";
        String fullClassName = this.getClass().getName();
        String testCaseNumber = fullClassName
                .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
        user += testCaseNumber;

        String cookieName = "rememberMe" + testCaseNumber;

        boolean foundUser = false;
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
            javax.servlet.http.Cookie cookie = cookies[i];
            if (cookieName.equals(cookie.getName())) {
                if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                    foundUser = true;
                }
            }
        }

        if (foundUser) {
            response.getWriter().println("Welcome back: " + user + "<br/>");
        } else {
            javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
            rememberMe.setSecure(true);
            request.getSession().setAttribute(cookieName, rememberMeKey);
            response.addCookie(rememberMe);
            response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                    + " whose value is: " + rememberMe.getValue() + "<br/>");
        }

    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
        throw new ServletException(e);
    } finally {
        response.getWriter().println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
}

From source file:org.eclipse.jgit.lfs.server.fs.LfsServerTest.java

/**
 * Creates a file with random content, repeatedly writing a random string of
 * 4k length to the file until the file has at least the specified length.
 *
 * @param f//from w  w  w. ja va 2s .c  o  m
 *            file to fill
 * @param size
 *            size of the file to generate
 * @return length of the generated file in bytes
 * @throws IOException
 */
protected long createPseudoRandomContentFile(Path f, long size) throws IOException {
    SecureRandom rnd = new SecureRandom();
    byte[] buf = new byte[4096];
    rnd.nextBytes(buf);
    ByteBuffer bytebuf = ByteBuffer.wrap(buf);
    try (FileChannel outChannel = FileChannel.open(f, StandardOpenOption.CREATE_NEW,
            StandardOpenOption.WRITE)) {
        long len = 0;
        do {
            len += outChannel.write(bytebuf);
            if (bytebuf.position() == 4096) {
                bytebuf.rewind();
            }
        } while (len < size);
    }
    return Files.size(f);
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest00745.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String[] values = request.getParameterValues("BenchmarkTest00745");
    String param;/*from  ww w.  jav a 2 s  .c  om*/
    if (values != null && values.length > 0)
        param = values[0];
    else
        param = "";

    String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param);

    try {
        java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");

        // Get 40 random bytes
        byte[] randomBytes = new byte[40];
        secureRandomGenerator.nextBytes(randomBytes);

        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);

        String user = "SafeByron";
        String fullClassName = this.getClass().getName();
        String testCaseNumber = fullClassName
                .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
        user += testCaseNumber;

        String cookieName = "rememberMe" + testCaseNumber;

        boolean foundUser = false;
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; !foundUser && i < cookies.length; i++) {
                javax.servlet.http.Cookie cookie = cookies[i];
                if (cookieName.equals(cookie.getName())) {
                    if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                        foundUser = true;
                    }
                }
            }
        }

        if (foundUser) {
            response.getWriter().println("Welcome back: " + user + "<br/>");

        } else {
            javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
            rememberMe.setSecure(true);
            //         rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
            rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet 
            // e.g., /benchmark/sql-01/BenchmarkTest01001
            request.getSession().setAttribute(cookieName, rememberMeKey);
            response.addCookie(rememberMe);
            response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                    + " whose value is: " + rememberMe.getValue() + "<br/>");
        }
    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
        throw new ServletException(e);
    } finally {
        response.getWriter().println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
}

From source file:test.integ.be.fedict.commons.eid.client.BeIDCardTest.java

@Test
public void testAuthnSignature() throws Exception {
    final BeIDCard beIDCard = getBeIDCard();

    final byte[] toBeSigned = new byte[10];
    final SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(toBeSigned);

    final X509Certificate authnCertificate = beIDCard.getAuthenticationCertificate();

    byte[] signatureValue;
    try {/*from  www  .  j a  v  a2  s. c o m*/
        signatureValue = beIDCard.signAuthn(toBeSigned, false);
    } finally {
        beIDCard.close();
    }

    final BeIDIntegrity beIDIntegrity = new BeIDIntegrity();
    final boolean result = beIDIntegrity.verifyAuthnSignature(toBeSigned, signatureValue, authnCertificate);

    assertTrue(result);
}

From source file:test.integ.be.fedict.commons.eid.client.BeIDCardTest.java

@Test
public void testNonRepSignature() throws Exception {
    final byte[] toBeSigned = new byte[10];
    final SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(toBeSigned);
    final MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    final byte[] digestValue = messageDigest.digest(toBeSigned);

    final BeIDCard beIDCard = getBeIDCard();

    X509Certificate signingCertificate;
    byte[] signatureValue;
    try {/*from   w  w  w. ja  va2s  .c om*/
        signatureValue = beIDCard.sign(digestValue, BeIDDigest.SHA_1, FileType.NonRepudiationCertificate,
                false);
        assertNotNull(signatureValue);
        signingCertificate = beIDCard.getSigningCertificate();
    } finally {
        beIDCard.close();
    }

    final BeIDIntegrity beIDIntegrity = new BeIDIntegrity();
    final boolean result = beIDIntegrity.verifyNonRepSignature(digestValue, signatureValue, signingCertificate);
    assertTrue(result);
}

From source file:test.integ.be.fedict.commons.eid.client.BeIDCardTest.java

@Test
public void testPSSSignature() throws Exception {
    final BeIDCard beIDCard = getBeIDCard();

    final byte[] toBeSigned = new byte[10];
    final SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(toBeSigned);

    final X509Certificate authnCertificate = beIDCard.getAuthenticationCertificate();

    final MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
    final byte[] digestValue = messageDigest.digest(toBeSigned);

    byte[] signatureValue;
    try {/*from  w w  w  .  j  a  va2s.c o  m*/
        signatureValue = beIDCard.sign(digestValue, BeIDDigest.SHA_1_PSS, FileType.AuthentificationCertificate,
                false);
    } finally {
        beIDCard.close();
    }

    Security.addProvider(new BouncyCastleProvider());

    final BeIDIntegrity beIDIntegrity = new BeIDIntegrity();
    final boolean result = beIDIntegrity.verifySignature("SHA1withRSAandMGF1", signatureValue,
            authnCertificate.getPublicKey(), toBeSigned);

    assertTrue(result);
}

From source file:test.integ.be.fedict.commons.eid.client.BeIDCardTest.java

@Test
public void testPSSSignatureSHA256() throws Exception {
    final BeIDCard beIDCard = getBeIDCard();

    final byte[] toBeSigned = new byte[10];
    final SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(toBeSigned);

    final X509Certificate authnCertificate = beIDCard.getAuthenticationCertificate();

    final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    final byte[] digestValue = messageDigest.digest(toBeSigned);

    byte[] signatureValue;
    try {// w  w  w.j a  v  a2s  .  c  o  m
        signatureValue = beIDCard.sign(digestValue, BeIDDigest.SHA_256_PSS,
                FileType.AuthentificationCertificate, false);
    } finally {
        beIDCard.close();
    }

    Security.addProvider(new BouncyCastleProvider());

    final BeIDIntegrity beIDIntegrity = new BeIDIntegrity();
    final boolean result = beIDIntegrity.verifySignature("SHA256withRSAandMGF1", signatureValue,
            authnCertificate.getPublicKey(), toBeSigned);

    assertTrue(result);
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest00598.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String param = "";
    boolean flag = true;
    java.util.Enumeration<String> names = request.getParameterNames();
    while (names.hasMoreElements() && flag) {
        String name = (String) names.nextElement();
        String[] values = request.getParameterValues(name);
        if (values != null) {
            for (int i = 0; i < values.length && flag; i++) {
                String value = values[i];
                if (value.equals("vector")) {
                    param = name;//w  ww.j a  va  2 s .c o m
                    flag = false;
                }
            }
        }
    }

    String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param);

    try {
        java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");

        // Get 40 random bytes
        byte[] randomBytes = new byte[40];
        secureRandomGenerator.nextBytes(randomBytes);

        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);

        String user = "SafeByron";
        String fullClassName = this.getClass().getName();
        String testCaseNumber = fullClassName
                .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
        user += testCaseNumber;

        String cookieName = "rememberMe" + testCaseNumber;

        boolean foundUser = false;
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
            javax.servlet.http.Cookie cookie = cookies[i];
            if (cookieName.equals(cookie.getName())) {
                if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                    foundUser = true;
                }
            }
        }

        if (foundUser) {
            response.getWriter().println("Welcome back: " + user + "<br/>");
        } else {
            javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
            rememberMe.setSecure(true);
            request.getSession().setAttribute(cookieName, rememberMeKey);
            response.addCookie(rememberMe);
            response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                    + " whose value is: " + rememberMe.getValue() + "<br/>");
        }

    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
        throw new ServletException(e);
    } finally {
        response.getWriter().println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
}

From source file:org.globusonline.nexus.GlobusOnlineRestClient.java

private long generateNonce() {
    SecureRandom sr = null;
    try {//from  ww w. j a  v  a  2s  .co  m
        sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] bytes = new byte[1024 / 8];
        sr.nextBytes(bytes);
        int seedByteCount = 10;
        byte[] seed = sr.generateSeed(seedByteCount);
        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return sr.nextLong();
}

From source file:org.owasp.benchmark.testcode.BenchmarkTest01069.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String param = "";
    if (request.getHeader("BenchmarkTest01069") != null) {
        param = request.getHeader("BenchmarkTest01069");
    }/*from   w ww .j a  va 2 s.  c  om*/

    // URL Decode the header value since req.getHeader() doesn't. Unlike req.getParameter().
    param = java.net.URLDecoder.decode(param, "UTF-8");

    String bar = new Test().doSomething(request, param);

    try {
        java.security.SecureRandom secureRandomGenerator = java.security.SecureRandom.getInstance("SHA1PRNG");

        // Get 40 random bytes
        byte[] randomBytes = new byte[40];
        secureRandomGenerator.nextBytes(randomBytes);

        String rememberMeKey = org.owasp.esapi.ESAPI.encoder().encodeForBase64(randomBytes, true);

        String user = "SafeByron";
        String fullClassName = this.getClass().getName();
        String testCaseNumber = fullClassName
                .substring(fullClassName.lastIndexOf('.') + 1 + "BenchmarkTest".length());
        user += testCaseNumber;

        String cookieName = "rememberMe" + testCaseNumber;

        boolean foundUser = false;
        javax.servlet.http.Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; !foundUser && i < cookies.length; i++) {
                javax.servlet.http.Cookie cookie = cookies[i];
                if (cookieName.equals(cookie.getName())) {
                    if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
                        foundUser = true;
                    }
                }
            }
        }

        if (foundUser) {
            response.getWriter().println("Welcome back: " + user + "<br/>");

        } else {
            javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
            rememberMe.setSecure(true);
            //         rememberMe.setPath("/benchmark/" + this.getClass().getSimpleName());
            rememberMe.setPath(request.getRequestURI()); // i.e., set path to JUST this servlet 
            // e.g., /benchmark/sql-01/BenchmarkTest01001
            request.getSession().setAttribute(cookieName, rememberMeKey);
            response.addCookie(rememberMe);
            response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
                    + " whose value is: " + rememberMe.getValue() + "<br/>");
        }
    } catch (java.security.NoSuchAlgorithmException e) {
        System.out.println("Problem executing SecureRandom.nextBytes() - TestCase");
        throw new ServletException(e);
    } finally {
        response.getWriter().println("Randomness Test java.security.SecureRandom.nextBytes(byte[]) executed");
    }
}