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.apache.rahas.TrustUtil.java

/**
 * Create an ephemeral key/*from  w w  w  .  j a  v  a  2  s.c om*/
 *
 * @return The generated ephemeral key
 * @throws TrustException
 */
protected byte[] generateEphemeralKey(byte[] reqEnt, byte[] respEnt, String algo, int keySize)
        throws TrustException {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] temp = new byte[keySize / 8];
        random.nextBytes(temp);
        return temp;
    } catch (Exception e) {
        throw new TrustException("Error in creating the ephemeral key", e);
    }
}

From source file:rapture.kernel.AdminApiImpl.java

private String generateSecureToken() {
    try {//w ww .j  a va 2s . com
        // get secure random
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte bytes[] = new byte[128];
        random.nextBytes(bytes);
        // get its digest
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] result = sha.digest(bytes);
        // encode to hex
        return (new Hex()).encodeHexString(result);
    } catch (NoSuchAlgorithmException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, e.getMessage());
    }
}

From source file:de.fhg.fokus.hss.server.zh.HSSzhOperationsImpl.java

/**
 * This method generates the authentication vectors sized by given paramter.
 * @return a list of Authentication vectors
 *//*from  w  w w  .ja  va 2s.  c  o  m*/
public ArrayList generateAuthenticationVectors() {
    LOGGER.debug("entering");

    ArrayList vectorList = null;
    try {

        vectorList = new ArrayList(numberAuthItems.intValue());

        HexCoDec codec;
        codec = new HexCoDec();
        byte[] secretKey = codec.decode(impi.getSkey());
        byte[] amf = codec.decode(impi.getAmf());

        // op and generate opC   
        byte[] op = codec.decode(impi.getOperatorId());
        byte[] opC = Milenage.generateOpC(secretKey, op);

        String authScheme = impi.getAuthScheme();
        Inet4Address ip = impi.getIP();
        byte[] sqn = codec.decode(impi.getSqn());

        if (authScheme.equalsIgnoreCase("Digest-MD5")) {
            // Authentication Scheme is Digest-MD5
            LOGGER.debug("Auth-Scheme is Digest-MD5");
            SecureRandom randomAccess = SecureRandom.getInstance("SHA1PRNG");

            for (long ix = 0; ix < numberAuthItems; ix++) {
                byte[] randBytes = new byte[16];
                randomAccess.setSeed(System.currentTimeMillis());
                randomAccess.nextBytes(randBytes);

                secretKey = codec.decodePassword(impi.getSkey()).getBytes();

                AuthenticationVector aVector = new AuthenticationVector(authScheme, randBytes, secretKey);
                vectorList.add(aVector);
            }
            impi.setSqn(codec.encode(sqn));
            HibernateUtil.getCurrentSession().update(impi);
        } else if (authScheme.equalsIgnoreCase("Digest-AKAv1-MD5")
                || authScheme.equalsIgnoreCase("Digest-AKAv2-MD5")) {
            // We have AKAv1 or AKAv2
            LOGGER.debug("Auth-Scheme is Digest-AKA");

            for (long ix = 0; ix < numberAuthItems; ix++) {
                sqn = DigestAKA.getNextSQN(sqn, HSSProperties.IND_LEN);
                byte[] copySqnHe = new byte[6];
                int k = 0;
                for (int i = 0; i < 6; i++, k++) {
                    copySqnHe[k] = sqn[i];
                }

                vectorList.add(DigestAKA.getAuthenticationVector(authScheme, secretKey, opC, amf, copySqnHe));
            }
            impi.setSqn(codec.encode(sqn));
            HibernateUtil.getCurrentSession().update(impi);
        }

    } catch (NoSuchAlgorithmException e) {
        LOGGER.error(this, e);
    } catch (InvalidKeyException e) {
        LOGGER.error(this, e);
    } catch (Exception e) {
        // Check impi
        if (impi.getAmf() == null) {
            throw new NullPointerException("Missing AMF value.");
        }

        if (impi.getSkey() == null) {
            throw new NullPointerException("Missing Secret Key value.");
        }

        if (impi.getAuthScheme() == null) {
            throw new NullPointerException("Missing Authentication Scheme.");
        }

        if (impi.getOperatorId() == null) {
            throw new NullPointerException("Missing Operator ID.");
        }
    }

    LOGGER.debug("exiting");
    return vectorList;
}

From source file:org.wso2.carbon.user.core.system.SystemUserRoleManager.java

public void addSystemUser(String userName, Object credential, String[] roleList) throws UserStoreException {

    Connection dbConnection = null;
    String password = (String) credential;
    try {/*  w w w.j a  v  a2  s  .co  m*/
        dbConnection = DatabaseUtil.getDBConnection(dataSource);
        String sqlStmt1 = SystemJDBCConstants.ADD_USER_SQL;

        String saltValue = null;
        try {
            SecureRandom secureRandom = SecureRandom.getInstance(UserCoreConstants.SHA_1_PRNG);
            byte[] bytes = new byte[16];
            //secureRandom is automatically seeded by calling nextBytes
            secureRandom.nextBytes(bytes);
            saltValue = Base64.encode(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA1PRNG algorithm could not be found.");
        }

        password = this.preparePassword(password, saltValue);

        this.updateStringValuesToDatabase(dbConnection, sqlStmt1, userName, password, saltValue, false,
                new Date(), tenantId);

        // add user to role.
        updateSystemRoleListOfUser(userName, null, roleList);

        dbConnection.commit();
    } catch (Throwable e) {
        try {
            if (dbConnection != null) {
                dbConnection.rollback();
            }
        } catch (SQLException e1) {
            log.error("Error while rollbacking add system user operation", e1);
        }
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage(), e);
        }
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        DatabaseUtil.closeAllConnections(dbConnection);
    }
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}//from  w ww.j av  a2s. co m
 */
@Override
public final byte[] getRandom(final int size) {
    byte[] randomVector = new byte[size];
    try {
        SecureRandom s = SecureRandom.getInstance("SHA1PRNG");
        s.nextBytes(new byte[1]); // force seed
        s.nextBytes(randomVector);
    } catch (NoSuchAlgorithmException e) {
        new Random().nextBytes(randomVector);
    }
    return randomVector;
}

From source file:org.apache.rahas.impl.SAMLTokenIssuer.java

/**
 * Create an ephemeral key//from   w  w w.j a v a 2s.com
 * 
 * @return The generated key as a byte array
 * @throws TrustException
 */
protected byte[] generateEphemeralKey(int keySize) throws TrustException {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] temp = new byte[keySize / 8];
        random.nextBytes(temp);
        return temp;
    } catch (Exception e) {
        throw new TrustException("Error in creating the ephemeral key", e);
    }
}

From source file:org.apache.hadoop.crypto.TestCryptoCodec.java

/**
 * Regression test for IV calculation, see HADOOP-11343
 *//*from w  w w. j av a2 s. com*/
@Test(timeout = 120000)
public void testCalculateIV() throws Exception {
    JceAesCtrCryptoCodec codec = new JceAesCtrCryptoCodec();
    codec.setConf(conf);

    SecureRandom sr = new SecureRandom();
    byte[] initIV = new byte[16];
    byte[] IV = new byte[16];

    long iterations = 1000;
    long counter = 10000;

    // Overflow test, IV: 00 00 00 00 00 00 00 00 ff ff ff ff ff ff ff ff 
    for (int i = 0; i < 8; i++) {
        initIV[8 + i] = (byte) 0xff;
    }

    for (long j = 0; j < counter; j++) {
        assertIVCalculation(codec, initIV, j, IV);
    }

    // Random IV and counter sequence test
    for (long i = 0; i < iterations; i++) {
        sr.nextBytes(initIV);

        for (long j = 0; j < counter; j++) {
            assertIVCalculation(codec, initIV, j, IV);
        }
    }

    // Random IV and random counter test
    for (long i = 0; i < iterations; i++) {
        sr.nextBytes(initIV);

        for (long j = 0; j < counter; j++) {
            long c = sr.nextLong();
            assertIVCalculation(codec, initIV, c, IV);
        }
    }
}

From source file:com.jbrisbin.riak.async.RiakAsyncClient.java

@SuppressWarnings({ "unchecked" })
@Override/* w  w w  .ja v  a 2 s  .c o m*/
public Promise<byte[]> generateAndSetClientId() throws IOException {
    SecureRandom sr;
    try {
        sr = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    byte[] data = new byte[6];
    sr.nextBytes(data);
    String clientId = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1);
    RPB.RpbSetClientIdReq.Builder b = RPB.RpbSetClientIdReq.newBuilder().setClientId(copyFromUtf8(clientId));
    Promise<byte[]> promise = new Promise<byte[]>();
    try {
        getConnection().write(new RpbRequest(new RpbMessage(MSG_SetClientIdReq, b.build()), promise));
    } catch (Exception e) {
        errorHandler.handleError(e);
    }
    return promise;
}

From source file:com.qut.middleware.esoemanager.manager.logic.impl.ServiceCryptoImpl.java

private String generatePassphrase() {
    SecureRandom random;
    String passphrase;/*ww  w . j a v a2  s . c  o m*/
    byte[] buf;

    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException nsae) {
        this.logger.error("NoSuchAlgorithmException when trying to create SecureRandom instance " //$NON-NLS-1$
                + nsae.getLocalizedMessage());
        this.logger.debug(nsae.getLocalizedMessage(), nsae);
        random = new SecureRandom();
    }

    buf = new byte[Constants.PASSPHRASE_LENGTH];
    random.nextBytes(buf);
    passphrase = new String(Hex.encodeHex(buf));

    return passphrase;
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipClientHandler.java

public void issueLoginRequest(String body)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException {
    final String S_ProcName = "issueLoginRequest";

    if (responseHandler == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Response handler must be set first by setResponseHandler()");
    }/*  w ww .  ja va2  s .  co m*/

    if (serverInfo == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Server info must be queried first by requestServerInfo()");
    }

    if ((body == null) || (body.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1, "body");
    }

    SecureRandom random = new SecureRandom();
    byte iv[] = new byte[16];
    random.nextBytes(iv);
    byte[] base64IV = Base64.encodeBase64(iv);
    String stringIV = new String(base64IV);
    IvParameterSpec ivspec = new IvParameterSpec(iv);

    byte[] encodedSessionKey = getEncodedSessionKey();
    byte[] encryptedSessionKey = encryptWithServerPublicKey(encodedSessionKey);
    byte[] base64SessionKey = Base64.encodeBase64(encryptedSessionKey);
    String stringSessionKey = new String(base64SessionKey);

    byte bodyBytes[] = body.getBytes();
    byte serverEncrypted[] = encryptWithSessionKey(ivspec, bodyBytes);
    byte base64Encrypted[] = Base64.encodeBase64(serverEncrypted);
    String encoded = new String(base64Encrypted);

    final String msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<CFTIPEnvelope\n"
            + "\t\txmlns=\"uri://net.sourceforge.msscodefactory/cftipenvelope\"\n"
            + "\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n"
            + "\t\txsi:schemaLocation=\"uri://net.sourceforge.msscodefactory/cftipenvelope file://xsd/cftip-envelope.xsd\" >\n"
            + "\t<LoginRequest MessageIV=\"" + stringIV + "\" AES256Key=\"" + stringSessionKey + "\" Payload=\""
            + encoded + "\" />\n" + "</CFTIPEnvelope>\n";
    String response = sendReceive(msg);
    if ((response == null) || (response.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "response");
    }
    byte responseBytes[] = Base64.decodeBase64(response);
    byte decrypted[] = decryptWithSessionKey(ivspec, responseBytes);
    String decryptedResponse = new String(decrypted);
    responseHandler.parseStringContents(decryptedResponse);
}