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.chililog.server.common.CryptoUtils.java

/**
 * <p>//from ww w.java  2 s .  co m
 * From a password, a number of iterations and a salt, returns the corresponding hash. For convenience, the salt is
 * stored within the hash.
 * </p>
 * 
 * <p>
 * This convention is used: <code>base64(hash(plainTextValue + salt)+salt)</code>
 * </p>
 * 
 * @param plainTextValue
 *            String The password to encrypt
 * @param salt
 *            byte[] The salt. If null, one will be created on your behalf.
 * @return String The hash password
 * @throws ChiliLogException
 *             if SHA-512 is not supported or UTF-8 is not a supported encoding algorithm
 */
public static String createSHA512Hash(String plainTextValue, byte[] salt) throws ChiliLogException {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        // Salt generation 64 bits long
        salt = new byte[8];
        random.nextBytes(salt);

        return createSHA512Hash(plainTextValue, salt, true);
    } catch (Exception ex) {
        throw new ChiliLogException(ex, "Error attempting to hash passwords. " + ex.getMessage());
    }
}

From source file:org.projectforge.framework.utils.NumberHelper.java

/**
 * Generates secure random bytes of the given length and return base 64 encoded bytes as url safe String. This is not the length of the
 * resulting string!//from   www .ja va 2  s  . c o  m
 * @param numberOfBytes
 * @return
 */
public static String getSecureRandomBase64String(final int numberOfBytes) {
    final SecureRandom random = new SecureRandom();
    final byte[] bytes = new byte[numberOfBytes];
    random.nextBytes(bytes);
    return org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.encodeBase64(bytes, false));
}

From source file:com.zimbra.cs.account.DataSource.java

private static byte[] randomSalt() {
    SecureRandom random = new SecureRandom();
    byte[] pad = new byte[SALT_SIZE_BYTES];
    random.nextBytes(pad);
    return pad;//from ww w .  j a v a2  s .co m
}

From source file:com.titilink.camel.rest.util.PasswordUtils.java

/**
 * SecureRandom?????//from  ww  w  .  java2  s. co  m
 *
 * @return ?
 */
public synchronized static byte[] generateSecRamdom() {
    try {
        SecureRandom sr = SecureRandom.getInstance(ALGORITHM_SHA1PRNG);
        byte[] bytes = new byte[DECIMAL_16];
        sr.nextBytes(bytes);
        return bytes;
    } catch (NoSuchAlgorithmException e) {
        LOGGER.error("generateSecRamdom error, no such algorithm exception");
    }
    return null;
}

From source file:com.aegiswallet.utils.WalletUtils.java

public static String generateSalt() {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[keySize / 8];
    random.nextBytes(bytes);
    String s = new String(bytes);
    return s;/*ww  w .j a v  a2 s.c o  m*/
}

From source file:org.sufficientlysecure.keychain.util.FileHelper.java

/**
 * Deletes data at a URI securely by overwriting it with random data
 * before deleting it. This method is fail-fast - if we can't securely
 * delete the file, we don't delete it at all.
 *//*from   ww w  .j a v a  2 s .c o m*/
public static int deleteFileSecurely(Context context, Uri uri) throws IOException {

    ContentResolver resolver = context.getContentResolver();
    long lengthLeft = FileHelper.getFileSize(context, uri);

    if (lengthLeft == -1) {
        throw new IOException("Error opening file!");
    }

    SecureRandom random = new SecureRandom();
    byte[] randomData = new byte[1024];

    OutputStream out = resolver.openOutputStream(uri, "w");
    if (out == null) {
        throw new IOException("Error opening file!");
    }
    out = new BufferedOutputStream(out);
    while (lengthLeft > 0) {
        random.nextBytes(randomData);
        out.write(randomData, 0, lengthLeft > randomData.length ? randomData.length : (int) lengthLeft);
        lengthLeft -= randomData.length;
    }
    out.close();

    if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
        return new File(uri.getPath()).delete() ? 1 : 0;
    } else {
        return resolver.delete(uri, null, null);
    }

}

From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Generates a nonce value for the SOAP secure header.
 *
 * @return the nonce value//from   w w  w  .j a v a2 s  .  com
 * @throws Exception
 *             if any error occurs while generating the nonce
 */
private static final String getNonce() throws Exception {
    final SecureRandom random; // Random value generator
    final byte[] nonceBytes; // Bytes to generate the nonce

    random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(System.currentTimeMillis());
    nonceBytes = new byte[16];
    random.nextBytes(nonceBytes);

    return new String(Base64.encodeBase64(nonceBytes), "UTF-8");
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

public static byte[] randomBytes(int size) {
    SecureRandom random = new SecureRandom();
    final byte[] iv = new byte[size];
    random.nextBytes(iv);

    return iv;//from  w w w  .j ava  2s  .  com
}

From source file:piuk.MyWallet.java

public static String encrypt(String text, String password, final int PBKDF2Iterations) throws Exception {

    if (password == null)
        throw new Exception("You must provide an ecryption password");

    // Use secure random to generate a 16 byte iv
    SecureRandom random = new SecureRandom();
    byte iv[] = new byte[AESBlockSize * 4];
    random.nextBytes(iv);

    byte[] textbytes = text.getBytes("UTF-8");

    PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password.toCharArray()), iv,
            PBKDF2Iterations);/* w w w .j  a v a2 s.  c om*/
    KeyParameter keyParam = (KeyParameter) generator.generateDerivedParameters(256);

    CipherParameters params = new ParametersWithIV(keyParam, iv);

    // setup AES cipher in CBC mode with PKCS7 padding
    BlockCipherPadding padding = new ISO10126d2Padding();
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(true, params);

    byte[] outBuf = cipherData(cipher, textbytes);

    // Append to IV to the output
    byte[] ivAppended = ArrayUtils.addAll(iv, outBuf);

    return new String(Base64.encode(ivAppended), "UTF-8");
}

From source file:org.wso2.appserver.webapp.security.utils.SSOUtils.java

/**
 * Generates a unique id.//  w ww  .j  a  va 2  s.  c  om
 *
 * @return a unique id
 */
public static String createID() {
    SecureRandom random = new SecureRandom();
    byte[] bytes = new byte[20]; // 160 bit
    random.nextBytes(bytes);
    char[] characterMapping = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p' };

    char[] characters = new char[40];
    IntStream.range(0, bytes.length).forEach(index -> {
        int left = (bytes[index] >> 4) & 0x0f;
        int right = bytes[index] & 0x0f;
        characters[index * 2] = characterMapping[left];
        characters[index * 2 + 1] = characterMapping[right];
    });

    return String.valueOf(characters);
}