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:com.intel.chimera.StreamCipherTest.java

private void cryptoCipherTestForReadableByteChannel(int count, String encCipherClass, String decCipherClass,
        byte[] iv) throws IOException {
    Cipher encCipher = null;/*from w  ww. j a  v a  2  s .  c  o  m*/
    try {
        encCipher = (Cipher) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(encCipherClass), props,
                transformation);
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Illegal crypto cipher!");
    }
    LOG.info("Created a cipher object of type: " + encCipherClass);

    // Generate data
    SecureRandom random = new SecureRandom();
    byte[] originalData = new byte[count];
    byte[] decryptedData = new byte[count];
    random.nextBytes(originalData);
    LOG.info("Generated " + count + " records");

    // Encrypt data
    ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
    CTRCryptoOutputStream out = new CTRCryptoOutputStream(Channels.newChannel(encryptedData), encCipher,
            bufferSize, key, iv);
    out.write(originalData, 0, originalData.length);
    out.flush();
    out.close();
    LOG.info("Finished encrypting data");

    Cipher decCipher = null;
    try {
        decCipher = (Cipher) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(decCipherClass), props,
                transformation);
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Illegal crypto cipher!");
    }
    LOG.info("Created a cipher object of type: " + decCipherClass);

    // Decrypt data
    CTRCryptoInputStream in = new CTRCryptoInputStream(
            Channels.newChannel(new ByteArrayInputStream(encryptedData.toByteArray())), decCipher, bufferSize,
            key, iv);

    // Check
    int remainingToRead = count;
    int offset = 0;
    while (remainingToRead > 0) {
        int n = in.read(decryptedData, offset, decryptedData.length - offset);
        if (n >= 0) {
            remainingToRead -= n;
            offset += n;
        }
    }

    Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData);

    // Decrypt data byte-at-a-time
    in = new CTRCryptoInputStream(Channels.newChannel(new ByteArrayInputStream(encryptedData.toByteArray())),
            decCipher, bufferSize, key, iv);

    // Check
    DataInputStream originalIn = new DataInputStream(
            new BufferedInputStream(new ByteArrayInputStream(originalData)));
    int expected;
    do {
        expected = originalIn.read();
        Assert.assertEquals("Decrypted stream read by byte does not match", expected, in.read());
    } while (expected != -1);

    LOG.info("SUCCESS! Completed checking " + count + " records");
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testNullSession() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey);

    try {/*w  ww  . j av a  2 s.  co  m*/
        SignResponseVerifier.checkSignResponse(signResponse, null);
        fail();
    } catch (IllegalArgumentException e) {
        // expected
    }
}

From source file:com.snaplogic.snaps.uniteller.CustomUFSSecurityMgr.java

@Override
public String generatePassword() throws UFSSecurityMgrException {
    String id = null;/*ww  w  .  j av  a  2s  .c o m*/
    try {
        byte[] byteArr = new byte[256];
        SecureRandom secureRnd = SecureRandom.getInstance(ENC_ALG);
        secureRnd.setSeed(new Long(System.currentTimeMillis()).toString().getBytes());
        MessageDigest md = MessageDigest.getInstance(DS_ALG);
        secureRnd.nextBytes(byteArr);
        md.update(byteArr);
        md.update(new Long(System.currentTimeMillis()).toString().getBytes());
        byteArr = md.digest();
        id = Base64.encode(byteArr, 0, 12);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new UFSSecurityMgrException(e.getMessage());
    }
    return id;
}

From source file:com.github.achatain.nopasswordauthentication.utils.TokenService.java

public String generate() {
    SecureRandom sr;

    try {/* ww w  . java2  s .c  o m*/
        sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        LOG.log(Level.SEVERE, "Failed to initiate a secure random", e);
        throw new RuntimeException("Unable to generate an API token", e);
    }

    byte bytes[] = new byte[16];
    sr.nextBytes(bytes);

    return RandomStringUtils.random(64, 0, 0, true, true, null, sr);
}

From source file:Networking.Server.java

public byte[] encryptMessage() {
    byte[] cipherText = null;
    byte[] text = null;
    try {/*from  w  w  w.  j  a  va2s.  c  om*/

        byte[] plainText = message.getBytes();

        SecretKeySpec myKey;
        myKey = new SecretKeySpec(this.d.getSessionKey(), "AES");

        SecureRandom random = new SecureRandom();
        byte randombytes[] = new byte[16];
        random.nextBytes(randombytes);
        this.d.setIv(randombytes);

        IvParameterSpec iv = new IvParameterSpec(this.d.getIv());
        Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, myKey, iv);
        cipherText = new byte[c.getOutputSize(plainText.length)];
        c.doFinal(plainText, 0, plainText.length, cipherText);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(iv.getIV());
        outputStream.write((cipherText));
        text = outputStream.toByteArray();

        File ivMsgFile = new File("./write_iv.txt");
        if (ivMsgFile.createNewFile()) {
            System.out.println("File is created!");
        }

        FileOutputStream sigfos = new FileOutputStream(ivMsgFile);
        sigfos.write(text);
        sigfos.flush();
        sigfos.close();

        byte[] sig_bytes = new byte[(int) ivMsgFile.length()];
        BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(ivMsgFile));
        bis1.read(sig_bytes, 0, sig_bytes.length);

        sendMesLen((int) ivMsgFile.length());
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println("sent time: " + timestamp);
        Socket writeSocket = new Socket(Ip, port);
        writeSocket.getOutputStream().write(sig_bytes, 0, sig_bytes.length);
        writeSocket.getOutputStream().flush();
        writeSocket.close();

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException | ShortBufferException | IllegalBlockSizeException
            | BadPaddingException | IOException ex) {
        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
    }
    return Base64.encodeBase64(text);
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testVerifierSignResponse() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey);
    LOG.debug("SignResponse: " + signResponse);

    LOG.debug("decoded sign response: " + new String(Base64.decode(signResponse.getBytes())));

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            tokenKey, null);//www . ja va  2 s . c o  m
    session.setDestination("destination");
    session.setInResponseTo("in-response-to");
    SignResponseVerificationResult result = SignResponseVerifier.checkSignResponse(signResponse, session);

    assertTrue(session.isSignResponseVerified());
    assertNotNull(result);
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testSignerIdentity() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey, DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR, null,
            "signer-identity");
    LOG.debug("SignResponse: " + signResponse);

    LOG.debug("decoded sign response: " + new String(Base64.decode(signResponse.getBytes())));

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            tokenKey, null);/*  ww w  . ja v a  2s .c o m*/
    session.setDestination("destination");
    session.setInResponseTo("in-response-to");
    SignResponseVerificationResult result = SignResponseVerifier.checkSignResponse(signResponse, session);

    assertTrue(session.isSignResponseVerified());
    assertNotNull(result);
    assertEquals("signer-identity", result.getSignerIdentity());
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testMessageIDDoesNotMatch() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey);
    LOG.debug("SignResponse: " + signResponse);

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id-foobar",
            "token-id", tokenKey, null);
    session.setDestination("destination");
    session.setInResponseTo("in-response-to");
    try {/*from w w w . j  a  va  2s.co  m*/
        SignResponseVerifier.checkSignResponse(signResponse, session);
        fail();
    } catch (SecurityException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
        assertFalse(session.isSignResponseVerified());
    }
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testReplyToNotMatch() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey);
    LOG.debug("SignResponse: " + signResponse);

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            tokenKey, null);/*from w ww . j av a2  s  .  c  o m*/
    session.setDestination("destination");
    session.setInResponseTo("in-response-to-foobar");
    try {
        SignResponseVerifier.checkSignResponse(signResponse, session);
        fail();
    } catch (SecurityException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
        assertFalse(session.isSignResponseVerified());
    }
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testDestinationDoesNotMatch() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey);
    LOG.debug("SignResponse: " + signResponse);

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            tokenKey, null);//from ww  w.  j  a v a  2 s  . c o m
    session.setDestination("destination-foobar");
    session.setInResponseTo("in-response-to");
    try {
        SignResponseVerifier.checkSignResponse(signResponse, session);
        fail();
    } catch (SecurityException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
        assertFalse(session.isSignResponseVerified());
    }
}