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:io.stallion.utils.GeneralUtils.java

/**
 * Generates a random string using the SecureRandom module, of the given length,
 * using URL safe base64 characters/*from  www.jav a  2 s  .c o  m*/
 *
 * @param length
 * @return
 */
public static String secureRandomToken(int length) {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[length * 4];
    random.nextBytes(bytes);
    String s = Base64.encodeBase64URLSafeString(bytes).substring(0, length);
    return s;
}

From source file:org.linagora.linshare.core.utils.HashUtils.java

/**
 * generate salt (32 bits/4 octets)//ww  w .j  av  a 2 s  .c om
 * @return
 */
public static byte[] getSalt() {
    // Get 32 random bits
    byte[] mybytes;
    try {
        // Create a secure random number generator
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

        // Create secure number generator with seed
        int seedByteCount = 10;
        byte[] seed = sr.generateSeed(seedByteCount);

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

        mybytes = new byte[32 / 8];
        sr.nextBytes(mybytes);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return mybytes;
}

From source file:utils.Hash.java

/**
 * Creates a psedorandom string/*from   www  .  j a v  a  2 s.c  om*/
 * @return Random String
 */
public static String randomString() {
    String result = new String();
    try {
        byte byteArray[] = new byte[16];
        SecureRandom psn1 = SecureRandom.getInstance("SHA1PRNG");
        psn1.setSeed(psn1.nextLong());
        psn1.nextBytes(byteArray);
        BigInteger bigInt = new BigInteger(byteArray);
        result = bigInt.toString();
        log.debug("Generated String = " + result);

    } catch (Exception e) {
        log.error("Random Number Error : " + e.toString());
    }
    return result;
}

From source file:utils.Hash.java

/**
 * Generates a small psedorandom string//from   w  ww  .jav  a 2 s . co m
 * @return Random String
 */
public static String smallRandomString() {
    String result = new String();
    try {
        byte byteArray[] = new byte[4];
        SecureRandom psn1 = SecureRandom.getInstance("SHA1PRNG");
        psn1.setSeed(psn1.nextLong());
        psn1.nextBytes(byteArray);
        BigInteger bigInt = new BigInteger(byteArray);
        result = bigInt.toString();
        log.debug("Generated String = " + result);

    } catch (Exception e) {
        log.error("Random Number Error : " + e.toString());
    }
    return result;
}

From source file:org.jasig.cas.extension.clearpass.EncryptedMapDecorator.java

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

    secureRandom.nextBytes(bytes);

    return getFormattedText(bytes);
}

From source file:ch.threema.apitool.CryptTool.java

/**
 * Encrypt file data using NaCl symmetric encryption with a random key.
 *
 * @param data the file contents to be encrypted
 * @return the encryption result including the random key
 *//* ww w  .jav a  2s .c o  m*/
public static EncryptResult encryptFileData(byte[] data) {
    //create random key
    SecureRandom rnd = new SecureRandom();
    byte[] encryptionKey = new byte[NaCl.SYMMKEYBYTES];
    rnd.nextBytes(encryptionKey);

    //encrypt file data in-place
    NaCl.symmetricEncryptDataInplace(data, encryptionKey, FILE_NONCE);

    return new EncryptResult(data, encryptionKey, FILE_NONCE);
}

From source file:com.ntsync.android.sync.client.ClientKeyHelper.java

private static byte[] createPwdCheck(SecretKey skey) throws InvalidKeyException, UnsupportedEncodingException {
    byte[] iv = new byte[IV_LENGTH];
    SecureRandom random = new SecureRandom();
    random.nextBytes(iv);
    AEADBlockCipher ecipher = CryptoHelper.getCipher();
    byte[] checkData;
    try {/*from  w  w w.jav  a 2  s.  c o m*/
        ecipher.init(true, new AEADParameters(new KeyParameter(skey.getEncoded()), CryptoHelper.MAC_SIZE, iv));

        // create random integer with checksum (UPC-Format : 12 digits)
        String testValue = String.format("%011d", random.nextInt(Integer.MAX_VALUE)) + "0";
        int res1 = calcUpcChecksum(testValue);

        testValue = testValue.substring(0, UPC_NR_LEN) + res1;

        byte[] pwdCheck = CryptoHelper.cipherData(ecipher,
                testValue.getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));

        checkData = new byte[iv.length + pwdCheck.length];
        System.arraycopy(iv, 0, checkData, 0, iv.length);
        System.arraycopy(pwdCheck, 0, checkData, iv.length, pwdCheck.length);
    } catch (DataLengthException e) {
        throw new InvalidKeyException(e.getMessage(), e);
    } catch (IllegalStateException e) {
        throw new InvalidKeyException(e.getMessage(), e);
    } catch (InvalidCipherTextException e) {
        throw new InvalidKeyException(e.getMessage(), e);
    }

    return checkData;
}

From source file:de.eod.jliki.users.utils.PasswordHashUtility.java

/**
 * Generates a salt for password hashing.<br/>
 * @return the salt//from  www  .ja  v a  2s .c  o  m
 */
public static byte[] generateSalt() {
    SecureRandom random;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (final NoSuchAlgorithmException e) {
        LOGGER.fatal("Number generation algorithm not found: " + RNGALGORITHM, e);
        return new byte[SALT_SIZE];
    }
    final byte[] salt = new byte[SALT_SIZE];
    random.nextBytes(salt);
    return salt;
}

From source file:org.apache.ofbiz.base.crypto.HashCrypt.java

private static String getSalt() {
    try {/*from  w w  w  .j a  v  a 2s . c  om*/
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[16];
        sr.nextBytes(salt);
        return salt.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new GeneralRuntimeException("Error while creating salt", e);
    }
}

From source file:org.wso2.carbon.appmgt.gateway.handlers.security.saml2.SAMLUtils.java

/**
 * Builds and returns a SAML authentication request to the IDP.
 *
 * @param messageContext/*w w w . j  ava2  s . c o  m*/
 * @param webApp
 * @return
 */
public static AuthnRequest buildAuthenticationRequest(MessageContext messageContext, WebApp webApp) {

    /* Building Issuer object */
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuerOb = issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp");
    issuerOb.setValue(webApp.getSaml2SsoIssuer());

    /* NameIDPolicy */
    NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
    NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
    nameIdPolicy.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
    nameIdPolicy.setSPNameQualifier("Issuer");
    nameIdPolicy.setAllowCreate(true);

    /* AuthnContextClass */
    AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
    AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder
            .buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "AuthnContextClassRef", "saml");
    authnContextClassRef
            .setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

    /* AuthnContex */
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
    RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

    DateTime issueInstant = new DateTime();
    SecureRandom secRandom = new SecureRandom();
    byte[] result = new byte[32];
    secRandom.nextBytes(result);
    String authReqRandomId = String.valueOf(Hex.encodeHex(result));

    /* Creation of AuthRequestObject */
    AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
    AuthnRequest authRequest = authRequestBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:protocol",
            "AuthnRequest", "samlp");
    authRequest.setForceAuthn(false);
    authRequest.setIsPassive(false);
    authRequest.setIssueInstant(issueInstant);
    authRequest.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    authRequest.setAssertionConsumerServiceURL(getAssertionConsumerUrl(messageContext));
    authRequest.setIssuer(issuerOb);
    authRequest.setNameIDPolicy(nameIdPolicy);
    authRequest.setRequestedAuthnContext(requestedAuthnContext);
    authRequest.setID(authReqRandomId);
    authRequest.setDestination(GatewayUtils.getIDPUrl());
    authRequest.setVersion(SAMLVersion.VERSION_20);

    return authRequest;
}