Java Code Examples for java.security.SecureRandom#nextBytes()

The following examples show how to use java.security.SecureRandom#nextBytes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RandomServlet.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
  int randomCount = parseParameter(request.getParameter("randomCount"));
  int byteCount = parseParameter(request.getParameter("byteCount"));
  int seedByteCount = parseParameter(request.getParameter("seedByteCount"));

  for (int i = 0; i < randomCount; i++) {
    SecureRandom random = new SecureRandom();
    if (byteCount > 0) {
      random.nextBytes(new byte[byteCount]);
    }
    if (seedByteCount > 0) {
      random.generateSeed(seedByteCount);
    }
  }
}
 
Example 2
Source File: AbstractSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
public String generateSecureRandomId() {
    final SecureRandom generator = new SecureRandom();
    final char[] charMappings = {
            'a', 'b', 'c', 'd', 'e', 'f', 'g',
            'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p'};

    final int charsLength = 40;
    final int generatorBytesLength = 20;
    final int shiftLength = 4;

    // 160 bits
    final byte[] bytes = new byte[generatorBytesLength];
    generator.nextBytes(bytes);

    final char[] chars = new char[charsLength];
    for (int i = 0; i < bytes.length; i++) {
        final int left = bytes[i] >> shiftLength & HEX_HIGH_BITS_BITWISE_FLAG;
        final int right = bytes[i] & HEX_HIGH_BITS_BITWISE_FLAG;
        chars[i * 2] = charMappings[left];
        chars[i * 2 + 1] = charMappings[right];
    }
    return String.valueOf(chars);
}
 
Example 3
Source File: CredentialEncrypter.java    From emodb with Apache License 2.0 6 votes vote down vote up
private SecretKey createKey(byte[] initializationBytes) {
    try {
        // Create the encryption key from a SecureRandom seeded with the secret SEED value and initialization bytes.
        // This way different initialization values will generate different keys.
        SecureRandom random = SecureRandom.getInstance(SEED_PRNG);
        random.setSeed(BaseEncoding.base64().decode(SEED));
        random.setSeed(initializationBytes);

        byte[] keyBytes = new byte[16];
        random.nextBytes(keyBytes);

        return new SecretKeySpec(keyBytes, ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        // This shouldn't happen since SHA1PRNG is supported by all JVMs.
        throw Throwables.propagate(e);
    }
}
 
Example 4
Source File: BCrypt.java    From BigDataPlatform with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generate a salt for use with the BCrypt.hashpw() method
 *
 * @param log_rounds the log2 of the number of rounds of hashing to apply - the work
 *                   factor therefore increases as 2**log_rounds. Minimum 4, maximum 31.
 * @param random     an instance of SecureRandom to use
 * @return an encoded salt value
 */
public static String gensalt(int log_rounds, SecureRandom random) {
    if (log_rounds < MIN_LOG_ROUNDS || log_rounds > MAX_LOG_ROUNDS) {
        throw new IllegalArgumentException("Bad number of rounds");
    }
    StringBuilder rs = new StringBuilder();
    byte rnd[] = new byte[BCRYPT_SALT_LEN];

    random.nextBytes(rnd);

    rs.append("$2a$");
    if (log_rounds < 10) {
        rs.append("0");
    }
    rs.append(log_rounds);
    rs.append("$");
    encode_base64(rnd, rnd.length, rs);
    return rs.toString();
}
 
Example 5
Source File: MacSameTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void doTest(String algo) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException {
    Mac mac;
    try {
        mac = Mac.getInstance(algo, "SunJCE");
    } catch (NoSuchAlgorithmException nsae) {
        // depending on Solaris configuration,
        // it can support HMAC or not with Mac
        System.out.println("Expected NoSuchAlgorithmException thrown: "
                + nsae);
        return;
    }

    byte[] plain = new byte[MESSAGE_SIZE];
    for (int i = 0; i < MESSAGE_SIZE; i++) {
        plain[i] = (byte) (i % 256);
    }

    byte[] tail = new byte[plain.length - OFFSET];
    System.arraycopy(plain, OFFSET, tail, 0, tail.length);

    SecureRandom srdm = new SecureRandom();
    byte[] keyVal = new byte[KEY_SIZE];
    srdm.nextBytes(keyVal);
    SecretKeySpec keySpec = new SecretKeySpec(keyVal, "HMAC");

    mac.init(keySpec);
    byte[] result1 = mac.doFinal(plain);

    mac.reset();
    mac.update(plain[0]);
    mac.update(plain, 1, OFFSET - 1);
    byte[] result2 = mac.doFinal(tail);

    if (!java.util.Arrays.equals(result1, result2)) {
        throw new RuntimeException("result1 and result2 are not the same");
    }
}
 
Example 6
Source File: JmxSupport.java    From mongodb-async-driver with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new JmxSupport.
 *
 * @param server
 *            The MBeanServer for the platform.
 */
public JmxSupport(final MBeanServer server) {
    myServer = server;

    final SecureRandom random = new SecureRandom();
    final byte[] bytes = new byte[RANDOM_BYTES];
    random.nextBytes(bytes);
    myUniqueId = IOUtils.toBase64(bytes);
}
 
Example 7
Source File: Utils.java    From bitherj with Apache License 2.0 5 votes vote down vote up
public static void wipeBytes(byte[] bytes) {
    if (bytes == null) {
        return;
    }
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = 0;
    }
    SecureRandom r = new SecureRandom();
    r.nextBytes(bytes);
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = 0;
    }
}
 
Example 8
Source File: MacSameTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void doTest(String algo) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException {
    Mac mac;
    try {
        mac = Mac.getInstance(algo, "SunJCE");
    } catch (NoSuchAlgorithmException nsae) {
        // depending on Solaris configuration,
        // it can support HMAC or not with Mac
        System.out.println("Expected NoSuchAlgorithmException thrown: "
                + nsae);
        return;
    }

    byte[] plain = new byte[MESSAGE_SIZE];
    for (int i = 0; i < MESSAGE_SIZE; i++) {
        plain[i] = (byte) (i % 256);
    }

    byte[] tail = new byte[plain.length - OFFSET];
    System.arraycopy(plain, OFFSET, tail, 0, tail.length);

    SecureRandom srdm = new SecureRandom();
    byte[] keyVal = new byte[KEY_SIZE];
    srdm.nextBytes(keyVal);
    SecretKeySpec keySpec = new SecretKeySpec(keyVal, "HMAC");

    mac.init(keySpec);
    byte[] result1 = mac.doFinal(plain);

    mac.reset();
    mac.update(plain[0]);
    mac.update(plain, 1, OFFSET - 1);
    byte[] result2 = mac.doFinal(tail);

    if (!java.util.Arrays.equals(result1, result2)) {
        throw new RuntimeException("result1 and result2 are not the same");
    }
}
 
Example 9
Source File: DSA.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
protected BigInteger generateK(BigInteger q) {
    SecureRandom random = getSigningRandom();
    byte[] kValue = new byte[q.bitLength()/8];

    while (true) {
        random.nextBytes(kValue);
        BigInteger k = new BigInteger(1, kValue).mod(q);
        if (k.signum() > 0 && k.compareTo(q) < 0) {
            return k;
        }
    }
}
 
Example 10
Source File: CommonBytesTests.java    From cava with Apache License 2.0 5 votes vote down vote up
@Test
void testEqualsWithBufferWrappingBytes() {
  SecureRandom random = new SecureRandom();
  byte[] key = new byte[32];
  random.nextBytes(key);
  Bytes b = w(key);
  Bytes other = Bytes.wrapBuffer(Buffer.buffer(key));
  assertEquals(b, other);
}
 
Example 11
Source File: ToolPbkdf2.java    From protools with Apache License 2.0 5 votes vote down vote up
public static byte[] generateSalt() throws NoSuchAlgorithmException {
    // VERY important to use SecureRandom instead of just Random
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    // Generate a 8 byte (64 bit) salt as recommended by RSA PKCS5
    byte[] salt = new byte[8];
    random.nextBytes(salt);
    return salt;
}
 
Example 12
Source File: AppLockImpl.java    From LolliPin with MIT License 5 votes vote down vote up
private String generateSalt() {
    byte[] salt = new byte[KEY_LENGTH];
    try {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(System.currentTimeMillis());
        sr.nextBytes(salt);
        return Arrays.toString(salt);
    } catch (Exception e) {
        salt = DEFAULT_PASSWORD_SALT.getBytes();
    }
    return Base64.encodeToString(salt, Base64.DEFAULT);
}
 
Example 13
Source File: DSSSecureRandomProviderTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@ParameterizedTest(name = "DigestAlgorithm {index} : {0} - {1}")
@MethodSource("data")
public void signatureParametersTest(DigestAlgorithm digestAlgorithm, int byteArrayLength) throws IOException {
	Date date = new Date();
	
	PAdESSignatureParameters signatureParameters = new PAdESSignatureParameters();
	signatureParameters.bLevel().setSigningDate(date);

	SecureRandomProvider secureRandomProvider = getFixedSecureRandomProvider(signatureParameters, digestAlgorithm, byteArrayLength);
	SecureRandom secureRandom = secureRandomProvider.getSecureRandom();
	
	byte[] byteArray = getEmptyBytes();
	secureRandom.nextBytes(byteArray);

	PAdESSignatureParameters otherSignatureParameters = new PAdESSignatureParameters();
	otherSignatureParameters.bLevel().setSigningDate(date);

	secureRandomProvider = getFixedSecureRandomProvider(otherSignatureParameters, digestAlgorithm, byteArrayLength);
	secureRandom = secureRandomProvider.getSecureRandom();
	
	byte[] sameByteArray = getEmptyBytes();
	secureRandom.nextBytes(sameByteArray);
	assertArrayEquals(byteArray, sameByteArray);
	
	otherSignatureParameters.setFilter("PDFFilter");

	secureRandomProvider = getFixedSecureRandomProvider(otherSignatureParameters, digestAlgorithm, byteArrayLength);
	secureRandom = secureRandomProvider.getSecureRandom();
	
	byte[] secondByteArray = getEmptyBytes();
	secureRandom.nextBytes(secondByteArray);
	
	assertFalse(Arrays.equals(byteArray, secondByteArray));
}
 
Example 14
Source File: DSA.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected BigInteger generateK(BigInteger q) {
    // Implementation defined in FIPS 186-4 AppendixB.2.1.
    SecureRandom random = getSigningRandom();
    byte[] kValue = new byte[(q.bitLength() + 7)/8 + 8];

    random.nextBytes(kValue);
    return new BigInteger(1, kValue).mod(
            q.subtract(BigInteger.ONE)).add(BigInteger.ONE);
}
 
Example 15
Source File: PasswordHash.java    From Aooms with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a salted PBKDF2 hash of the password.
 *
 * @param password the password to hash
 * @return a salted PBKDF2 hash of the password
 */
public static String createHash(char[] password)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Generate a random salt
    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[SALT_BYTE_SIZE];
    random.nextBytes(salt);
    // Hash the password
    byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
    // format iterations:salt:hash
    return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);
}
 
Example 16
Source File: PBKDF2.java    From JavaSecurity with Apache License 2.0 5 votes vote down vote up
private static byte[] generateSalt() {
    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[SALT_SIZE];
    random.nextBytes(salt);

    return salt;
}
 
Example 17
Source File: CryptoAlgos.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
/**
 * Indicates the computation of an n-byte cryptographic-strength random
 * number.
 *
 * Note The NTLM Authentication Protocol does not define the statistical
 * properties of the random number generator. It is left to the discretion of
 * the implementation to define the strength requirements of the NONCE(n)
 * operation.
 */
public static byte[] NONCE(int n) {
    // Generate random nonce for LMv2 and NTv2 responses
    byte[] nonce = new byte[n];
    SecureRandom random = new SecureRandom();
    random.nextBytes(nonce);

    // Fixed nonce for debugging purposes
    //* DEBUG */for (int i = 0; i < N; i++) nonce[i] = (byte) (i + 1);

    return nonce;
}
 
Example 18
Source File: BaseWrapCipher.java    From ripple-lib-java with ISC License 4 votes vote down vote up
protected void engineInit(
    int                     opmode,
    Key                     key,
    AlgorithmParameterSpec  params,
    SecureRandom            random)
throws InvalidKeyException, InvalidAlgorithmParameterException
{
    CipherParameters        param;

    if (key instanceof BCPBEKey)
    {
        BCPBEKey k = (BCPBEKey)key;

        if (params instanceof PBEParameterSpec)
        {
            param = PBE.Util.makePBEParameters(k, params, wrapEngine.getAlgorithmName());
        }
        else if (k.getParam() != null)
        {
            param = k.getParam();
        }
        else
        {
            throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
        }
    }
    else
    {
        param = new KeyParameter(key.getEncoded());
    }

    if (params instanceof IvParameterSpec)
    {
        IvParameterSpec iv = (IvParameterSpec) params;
        param = new ParametersWithIV(param, iv.getIV());
    }

    if (param instanceof KeyParameter && ivSize != 0)
    {
        iv = new byte[ivSize];
        random.nextBytes(iv);
        param = new ParametersWithIV(param, iv);
    }

    if (random != null)
    {
        param = new ParametersWithRandom(param, random);
    }

    switch (opmode)
    {
    case Cipher.WRAP_MODE:
        wrapEngine.init(true, param);
        break;
    case Cipher.UNWRAP_MODE:
        wrapEngine.init(false, param);
        break;
    case Cipher.ENCRYPT_MODE:
    case Cipher.DECRYPT_MODE:
        throw new IllegalArgumentException("engine only valid for wrapping");
    default:
        System.out.println("eeek!");
    }
}
 
Example 19
Source File: CipherUtils.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] getRandomKey() {
    byte[] keybytes = new byte[16];
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(keybytes);
    return keybytes;
}
 
Example 20
Source File: Priority_Inversion.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public synchronized void run() {
    System.out.println("Start priority " + getPriority());
    // The following should take over a second
    SecureRandom rand = new SecureRandom();
    rand.nextBytes(new byte[5]);
}