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.zimbra.cs.mailbox.ACL.java

public static String generateAccessKey() {
    SecureRandom random = new SecureRandom();
    byte[] key = new byte[ACCESSKEY_SIZE_BYTES];
    random.nextBytes(key);

    // in the form of e.g. 8d159aed5fb9431d8ac52db5e20baafb
    return new String(Hex.encodeHex(key));
}

From source file:com.zimbra.common.util.RandomPassword.java

public static String generate(int minLength, int maxLength, String alphabet) {
    SecureRandom random = new SecureRandom();

    // Calculate the desired length of the password
    int length;/*ww  w  . j ava 2 s .co m*/
    if (minLength > maxLength) {
        throw new IllegalArgumentException("minLength=" + minLength + " > maxLength=" + maxLength);
    } else if (minLength < maxLength) {
        length = minLength + random.nextInt(1 + maxLength - minLength);
    } else {
        length = maxLength;
    }

    int alphabetLength = alphabet.length();
    int limit = byteLimit(alphabetLength);

    StringBuffer password = new StringBuffer(length);
    byte[] randomByte = new byte[1];

    while (password.length() < length) {
        random.nextBytes(randomByte);
        int i = randomByte[0] + 128;
        if (i < limit) {
            password.append(alphabet.charAt(i % alphabetLength));
        }
    }

    return password.toString();
}

From source file:pt.aptoide.backupapps.data.webservices.ManagerUploads.java

public static String generateBoundary() {
    try {//from   w  w w.  ja v a 2  s .c  o m
        // Create a secure random number generator
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

        // Get 1024 random bits
        byte[] bytes = new byte[1024 / 8];
        sr.nextBytes(bytes);

        int seedByteCount = 10;
        byte[] seed = sr.generateSeed(seedByteCount);

        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);

        return "***" + Long.toString(sr.nextLong()) + "***";

    } catch (NoSuchAlgorithmException e) {
    }
    return "*********";
}

From source file:main.java.vasolsim.common.GenericUtils.java

/**
 * initializes a cipher/*w w  w.ja  v  a 2  s .  c o m*/
 *
 * @param key  the key
 * @param mode the mode (Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE)
 *
 * @return an initialized cipher
 *
 * @throws VaSolSimException for all the usual crypto stuff
 */
public static Cipher initCrypto(byte[] key, int mode) throws VaSolSimException {
    if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE)
        throw new VaSolSimException(ERROR_MESSAGE_BAD_CIPHER_MODE);

    byte[] parametricIV = new byte[16];
    Cipher cipher;
    try {
        //create an IV
        SecureRandom random = new SecureRandom();
        random.nextBytes(parametricIV);

        //initialize the crypto
        cipher = Cipher.getInstance(DEFAULT_SERVICE_PROVIDER_INTERFACE, DEFAULT_SERVICE_PROVIDER);
        cipher.init(mode, new SecretKeySpec(key, DEFAULT_ENCRYPTION_ALGORITHM),
                new IvParameterSpec(parametricIV));
    } catch (NoSuchAlgorithmException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (NoSuchProviderException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD PROVIDER\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (NoSuchPaddingException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nNO SUCH PADDING\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (InvalidKeyException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD KEY\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM PARAMS\n" + e.toString()
                + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    }

    return cipher;
}

From source file:ece356.UserDBAO.java

private static String generateSalt() {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[20];
    random.nextBytes(bytes);
    return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
}

From source file:piuk.blockchain.android.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);//from w  ww .jav  a2  s . co  m
    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, Base64.NO_WRAP), "UTF-8");
}

From source file:com.kactech.otj.Utils.java

public static ByteBuffer seal(String msg, String nymID, PublicKey nymKey) throws InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    SecureRandom random = new SecureRandom();
    byte[] aesKey = new byte[16];
    random.nextBytes(aesKey);
    byte[] vector = new byte[16];
    random.nextBytes(vector);//from ww w  .j a  va2s. co m
    return seal(msg, nymID, nymKey, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(vector));
}

From source file:acp.sdk.SecureUtil.java

/**
 * /*from ww w  .  jav a  2 s  . c  om*/
 * @param aBytesText
 * @param aBlockSize
 * @return
 */
private static byte[] addPKCS1Padding(byte[] aBytesText, int aBlockSize) {
    if (aBytesText.length > (aBlockSize - 3)) {
        return null;
    }
    SecureRandom tRandom = new SecureRandom();
    byte[] tAfterPaddingBytes = new byte[aBlockSize];
    tRandom.nextBytes(tAfterPaddingBytes);
    tAfterPaddingBytes[0] = 0x00;
    tAfterPaddingBytes[1] = 0x02;
    int i = 2;
    for (; i < aBlockSize - 1 - aBytesText.length; i++) {
        if (tAfterPaddingBytes[i] == 0x00) {
            tAfterPaddingBytes[i] = (byte) tRandom.nextInt();
        }
    }
    tAfterPaddingBytes[i] = 0x00;
    System.arraycopy(aBytesText, 0, tAfterPaddingBytes, (i + 1), aBytesText.length);

    return tAfterPaddingBytes;
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * Generate a random salt for use with the cipher.
 *
 * @return String version of the 8 byte salt
 * @author Randy McEoin// w  ww . ja v a  2s.  c om
 */
public static String generateSalt() throws NoSuchAlgorithmException {
    byte[] salt = new byte[8];
    SecureRandom sr;
    try {
        sr = SecureRandom.getInstance("SHA1PRNG");
        sr.nextBytes(salt);
        if (debug) {
            Log.d(TAG, "generateSalt: salt=" + salt.toString());
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw e;
    }
    return toHexString(salt);
}

From source file:net.openid.appauth.AuthorizationRequest.java

private static String generateRandomState() {
    SecureRandom sr = new SecureRandom();
    byte[] random = new byte[STATE_LENGTH];
    sr.nextBytes(random);
    return Base64.encodeToString(random, Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE);
}