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.sonatype.nexus.test.utils.FileTestingUtils.java

public static File populate(File file, int sizeInMB) throws IOException {
    file.getParentFile().mkdirs();//from w w w . j a v  a 2 s .c om

    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(file));
    zip.putNextEntry(new ZipEntry("content.random"));
    for (int i = 0; i < sizeInMB * 1024; i++) {
        byte[] b = new byte[1024];
        SecureRandom r = new SecureRandom();
        r.nextBytes(b);

        zip.write(b);
    }
    zip.closeEntry();
    zip.close();

    return file;
}

From source file:net.seleucus.wsp.crypto.FwknopSymmetricCrypto.java

public static String encrypt(byte[] key, String message)
        throws NoSuchAlgorithmException, IOException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    SecureRandom sr = new SecureRandom();
    byte[] salt = new byte[8];
    sr.nextBytes(salt);

    byte[][] key_and_iv = deriveKeyAndIV(salt, key);

    SecretKeySpec enc_key;/*from  w ww . j  a v  a2  s .c o m*/
    enc_key = new SecretKeySpec(key_and_iv[0], "AES");
    Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec iv = new IvParameterSpec(key_and_iv[1]);
    aes.init(Cipher.ENCRYPT_MODE, enc_key, iv);

    byte[] salted = "Salted__".getBytes("UTF-8");
    byte[] cipher = aes.doFinal(message.getBytes("UTF-8"));

    byte[] result = new byte[salted.length + salt.length + cipher.length];

    // now we need to glue: "Salted__" + salt + cipher
    System.arraycopy(salted, 0, result, 0, salted.length);
    System.arraycopy(salt, 0, result, salted.length, salt.length);
    System.arraycopy(cipher, 0, result, salted.length + salt.length, cipher.length);

    // remove = and FWKNOP_ENCRYPTION_HEADER
    return Base64.encodeBase64String(result).replace("=", "").replace(FWKNOP_ENCRYPTION_HEADER, "");
}

From source file:Logi.GSeries.Libraries.Encryption.java

public static String encrypt(String decryptedString, String password) {
    try {/*from w  w w  . j a  v a 2  s  .  co  m*/
        // build the initialization vector (randomly).
        SecureRandom random = new SecureRandom();
        byte initialVector[] = new byte[16];
        //generate random 16 byte IV AES is always 16bytes
        random.nextBytes(initialVector);
        IvParameterSpec ivspec = new IvParameterSpec(initialVector);
        SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
        byte[] encrypted = cipher.doFinal(decryptedString.getBytes());
        byte[] encryptedWithIV = new byte[encrypted.length + initialVector.length];
        System.arraycopy(encrypted, 0, encryptedWithIV, 0, encrypted.length);
        System.arraycopy(initialVector, 0, encryptedWithIV, encrypted.length, initialVector.length);
        return Base64.encodeBase64String(encryptedWithIV);
    } catch (Exception ex) {
        Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex);
        return "Error";
    }
}

From source file:org.apache.cloudstack.framework.security.keys.KeysManagerImpl.java

private static String getBase64EncodedRandomKey(int nBits) {
    SecureRandom random;
    try {//from w ww.j  a  v  a  2s.  c om
        random = SecureRandom.getInstance("SHA1PRNG");
        byte[] keyBytes = new byte[nBits / 8];
        random.nextBytes(keyBytes);
        return Base64.encodeBase64URLSafeString(keyBytes);
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("Unhandled exception: ", e);
    }
    return null;
}

From source file:org.gss_project.gss.server.domain.Nonce.java

/**
 * Creates a new nonce and resets its expiry date.
 *
 * @param userId the ID of the associated user
 * @return a new nonce/*from w  w w .  j  a v a 2  s .  co  m*/
 */
public static Nonce createNonce(Long userId) {
    Nonce n = new Nonce();
    n.userId = userId;
    SecureRandom random = new SecureRandom();
    n.nonce = new byte[NONCE_SIZE];
    random.nextBytes(n.nonce);
    Calendar cal = Calendar.getInstance();
    // Set nonce time-to-live to 5 minutes.
    cal.add(Calendar.MINUTE, 5);
    n.nonceExpiryDate = cal.getTime();
    try {
        n.encodedNonce = URLEncoder.encode(new String(Base64.encodeBase64(n.nonce), "US-ASCII"), "US-ASCII");
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
    }
    return n;
}

From source file:aaf.vhr.crypto.GoogleAuthenticator.java

/**
 * Generate a random secret key. This must be saved by the server and associated with the
 * users account to verify the code displayed by Google Authenticator.
 * The user must register this secret on their device.
 * @return secret key//from w  ww  .  j a v  a2  s  .c  o m
 */
public static String generateSecretKey() {
    try {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        Base32 codec = new Base32();

        byte[] buffer = new byte[10];
        sr.nextBytes(buffer);
        byte[] bEncodedKey = codec.encode(buffer);
        String encodedKey = new String(bEncodedKey);
        return encodedKey;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
}

From source file:org.underworldlabs.util.DesEncrypter.java

public static String generateKey(int length) {
    try {/*from   w w  w  .jav  a 2s . c  o m*/
        StringBuffer key = new StringBuffer(length);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] intbytes = new byte[4];

        for (int i = 0; i < length; i++) {
            random.nextBytes(intbytes);
            key.append(pwdChars[Math.abs(getIntFromByte(intbytes) % pwdChars.length)]);
        }

        return key.toString();
    } catch (NoSuchAlgorithmException e) {
        return null;
    }
}

From source file:org.apache.accumulo.core.crypto.CryptoUtils.java

private static SecureRandom newSecureRandom(String secureRNG, String secureRNGProvider) {
    SecureRandom secureRandom = null;
    try {/*from  w  w w.j  av  a  2 s .c  o m*/
        secureRandom = SecureRandom.getInstance(secureRNG, secureRNGProvider);

        // Immediately seed the generator
        byte[] throwAway = new byte[16];
        secureRandom.nextBytes(throwAway);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new CryptoException("Unable to generate secure random.", e);
    }
    return secureRandom;
}

From source file:ECToken3.java

public static final String encryptv3(String key, String input) throws java.io.UnsupportedEncodingException,
        java.security.NoSuchAlgorithmException, javax.crypto.NoSuchPaddingException,
        java.security.InvalidKeyException, javax.crypto.IllegalBlockSizeException,
        javax.crypto.BadPaddingException, java.security.InvalidAlgorithmParameterException {

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| Encrypt\n");
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| key:                   %s\n", key);
    //System.out.format("| token:                 %s\n", input);

    //----------------------------------------------------
    // Get SHA-256 of key
    //----------------------------------------------------
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(key.getBytes("ASCII"));
    byte[] keyDigest = md.digest();

    //----------------------------------------------------
    // Get Random IV
    //----------------------------------------------------
    SecureRandom random = new SecureRandom();
    byte[] ivBytes = new byte[12];
    random.nextBytes(ivBytes);

    //----------------------------------------------------
    // Encrypt/*from   w  w  w. ja v  a 2s  .  com*/
    //----------------------------------------------------
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(true, new AEADParameters(new KeyParameter(keyDigest), MAC_SIZE_BITS, ivBytes));
    byte[] inputBytes = input.getBytes("ASCII");

    byte[] enc = new byte[cipher.getOutputSize(inputBytes.length)];

    try {
        int res = cipher.processBytes(inputBytes, 0, inputBytes.length, enc, 0);
        cipher.doFinal(enc, res);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    byte[] ivPlusCipherText = new byte[ivBytes.length + enc.length];
    System.arraycopy(ivBytes, 0, ivPlusCipherText, 0, ivBytes.length);
    System.arraycopy(enc, 0, ivPlusCipherText, ivBytes.length, enc.length);

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| iv:                    %s\n", bytesToHex(ivBytes));
    //System.out.format("| ciphertext:            %s\n", bytesToHex(Arrays.copyOfRange(enc, 0, enc.length - 16)));
    //System.out.format("| tag:                   %s\n", bytesToHex(Arrays.copyOfRange(enc, enc.length - 16, enc.length)));
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| token:                 %s\n", bytesToHex(ivPlusCipherText));
    //System.out.format("+-------------------------------------------------------------\n");

    String result = null;
    byte[] temp = null;
    Base64 encoder = new Base64(0, temp, true);
    byte[] encodedBytes = encoder.encode(ivPlusCipherText);
    String encodedStr = new String(encodedBytes, "ASCII").trim();
    String encodedStrTrim = encodedStr.trim();
    return encodedStr.trim();
}

From source file:org.jasig.cas.web.flow.CasFlowExecutionKeyFactory.java

private static byte[] getRandomSalt(final int size) {
    final SecureRandom secureRandom = new SecureRandom();
    final byte[] bytes = new byte[size];

    secureRandom.nextBytes(bytes);
    return bytes;
}