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:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipClientHandler.java

public void issueAppRequest(String body)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException {
    final String S_ProcName = "issueAppRequest";

    if (responseHandler == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Response handler must be set first by setResponseHandler()");
    }//from   www  .  j  a  v  a 2s. com

    if (serverInfo == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Server info must be queried first by requestServerInfo()");
    }

    if (sessionKey == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Session key must be set first by logging in");
    }

    if ((body == null) || (body.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1, "body");
    }

    SecureRandom random = new SecureRandom();
    byte iv[] = new byte[16];
    random.nextBytes(iv);
    byte[] base64IV = Base64.encodeBase64(iv);
    String stringIV = new String(base64IV);
    IvParameterSpec ivspec = new IvParameterSpec(iv);

    byte bodyBytes[] = body.getBytes();
    byte serverEncrypted[] = encryptWithSessionKey(ivspec, bodyBytes);
    byte base64Encrypted[] = Base64.encodeBase64(serverEncrypted);
    String encoded = new String(base64Encrypted);

    final String msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<CFTIPEnvelope\n"
            + "\t\txmlns=\"uri://net.sourceforge.msscodefactory/cftipenvelope\"\n"
            + "\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n"
            + "\t\txsi:schemaLocation=\"uri://net.sourceforge.msscodefactory/cftipenvelope file://xsd/cftip-envelope.xsd\" >\n"
            + "\t<AppRequest MessageIV=\"" + stringIV + "\" Payload=\"" + encoded + "\" />\n"
            + "</CFTIPEnvelope>\n";
    String response = sendReceive(msg);
    if ((response == null) || (response.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "response");
    }
    byte responseBytes[] = Base64.decodeBase64(response);
    byte decrypted[] = decryptWithSessionKey(ivspec, responseBytes);
    String decryptedResponse = new String(decrypted);
    responseHandler.parseStringContents(decryptedResponse);
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public String generatePassphrase() {
    SecureRandom random;
    String passphrase;//from  w ww  .j ava  2s .co  m
    byte[] buf;

    try {
        /* Attempt to get the specified RNG instance */
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException nsae) {
        random = new SecureRandom();
    }

    buf = new byte[10];
    random.nextBytes(buf);
    passphrase = new String(Hex.encodeHex(buf));

    return passphrase;
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

private byte[] generateKeyData() {
    try {/*  w  w  w . j a v  a2 s .  c  o  m*/
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
        byte bytes[] = new byte[DESedeKeySpec.DES_EDE_KEY_LEN];
        random.nextBytes(bytes);
        return bytes;
    } catch (Exception e) {
        throw new RuntimeException("Unable to generate secret key", e);
    }
}

From source file:de.burlov.amazon.s3.dirsync.DirSync.java

/**
 * /*w w w  .  j a  v  a  2s .c  o m*/
 * @param autocreate
 *        'true' wenn fehlende Index/bucket automatisch erstellt werden sollen
 * @throws DirSyncException
 */
private void connect(boolean autocreate) throws DirSyncException {
    if (mainIndex != null) {
        return;
    }
    boolean bucketExists = false;
    try {
        bucketExists = s3Service.isBucketAccessible(bucket);
    } catch (S3ServiceException e1) {
        throw new DirSyncException("Internal error: " + e1.getMessage());
    }
    if (!bucketExists) {
        if (autocreate) {
            /*
             * In 'up' Modus benoetigte Bucket erstellen falls er noch nicht vorhanden ist
             */
            try {
                s3Service.createBucket(bucket, location);
            } catch (S3ServiceException e2) {
                throw new DirSyncException(
                        "Creating bucket '" + bucket + "' failed: " + e2.getLocalizedMessage());
            }
        } else {
            throw new DirSyncException("Bucket not found: " + bucket);
        }
    }
    try {
        mainIndex = (MainIndex) downloadObject(getMainIndexKey(), pbeKey);
    } catch (IOException e) {
        /*
         * Lesen des Indexes fehlgeschlagen, falsches Passwort?
         */
        throw new DirSyncException("Reading main index failed. Are password and S3 login data valid?", e);
    }
    if (mainIndex == null) {
        if (autocreate) {
            /*
             * Noch keine Daten auf dem Server
             */
            mainIndex = new MainIndex();
            /*
             * Schluessel fuer Datenverschluesselung generieren
             */
            SecureRandom srnd = new SecureRandom();
            srnd.setSeed(pbeKey);
            byte[] dataKey = new byte[32];
            srnd.nextBytes(dataKey);
            mainIndex.setEncryptionKey(dataKey);
        } else {
            /*
             * Kein Index gefunden, also keine Daten zum Runterladen
             */
            throw new DirSyncException("No data found");
        }
    }
}

From source file:com.basho.riak.pbc.RiakClient.java

/**
 * helper method to use a reasonable default client id
 * beware, it caches the client id. If you call it multiple times on the same client
 * you get the *same* id (not good for reusing a client with different ids)
 * // ww w  .  j a  v  a 2s .co  m
 * @throws IOException
 */
public void prepareClientID() throws IOException {
    Preferences prefs = Preferences.userNodeForPackage(RiakClient.class);

    String clid = prefs.get("client_id", null);
    if (clid == null) {
        SecureRandom sr;
        try {
            sr = SecureRandom.getInstance("SHA1PRNG");
            // Not totally secure, but doesn't need to be
            // and 100% less prone to 30 second hangs on linux jdk5
            sr.setSeed(UUID.randomUUID().getLeastSignificantBits() + new Date().getTime());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] data = new byte[6];
        sr.nextBytes(data);
        clid = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1);
        prefs.put("client_id", clid);
        try {
            prefs.flush();
        } catch (BackingStoreException e) {
            throw new IOException(e.toString());
        }
    }

    setClientID(clid);
}

From source file:org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.java

private void prepareEncryptionDictRev6(String ownerPassword, String userPassword,
        PDEncryption encryptionDictionary, int permissionInt) throws IOException {
    try {/*ww w.j  a va2 s .com*/
        SecureRandom rnd = new SecureRandom();
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

        // make a random 256-bit file encryption key
        encryptionKey = new byte[32];
        rnd.nextBytes(encryptionKey);

        // Algorithm 8a: Compute U
        byte[] userPasswordBytes = truncate127(userPassword.getBytes(Charsets.UTF_8));
        byte[] userValidationSalt = new byte[8];
        byte[] userKeySalt = new byte[8];
        rnd.nextBytes(userValidationSalt);
        rnd.nextBytes(userKeySalt);
        byte[] hashU = computeHash2B(concat(userPasswordBytes, userValidationSalt), userPasswordBytes, null);
        byte[] u = concat(hashU, userValidationSalt, userKeySalt);

        // Algorithm 8b: Compute UE
        byte[] hashUE = computeHash2B(concat(userPasswordBytes, userKeySalt), userPasswordBytes, null);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashUE, "AES"), new IvParameterSpec(new byte[16]));
        byte[] ue = cipher.doFinal(encryptionKey);

        // Algorithm 9a: Compute O
        byte[] ownerPasswordBytes = truncate127(ownerPassword.getBytes(Charsets.UTF_8));
        byte[] ownerValidationSalt = new byte[8];
        byte[] ownerKeySalt = new byte[8];
        rnd.nextBytes(ownerValidationSalt);
        rnd.nextBytes(ownerKeySalt);
        byte[] hashO = computeHash2B(concat(ownerPasswordBytes, ownerValidationSalt, u), ownerPasswordBytes, u);
        byte[] o = concat(hashO, ownerValidationSalt, ownerKeySalt);

        // Algorithm 9b: Compute OE
        byte[] hashOE = computeHash2B(concat(ownerPasswordBytes, ownerKeySalt, u), ownerPasswordBytes, u);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashOE, "AES"), new IvParameterSpec(new byte[16]));
        byte[] oe = cipher.doFinal(encryptionKey);

        // Set keys and other required constants in encryption dictionary
        encryptionDictionary.setUserKey(u);
        encryptionDictionary.setUserEncryptionKey(ue);
        encryptionDictionary.setOwnerKey(o);
        encryptionDictionary.setOwnerEncryptionKey(oe);

        PDCryptFilterDictionary cryptFilterDictionary = new PDCryptFilterDictionary();
        cryptFilterDictionary.setCryptFilterMethod(COSName.AESV3);
        cryptFilterDictionary.setLength(keyLength);
        encryptionDictionary.setStdCryptFilterDictionary(cryptFilterDictionary);
        encryptionDictionary.setStreamFilterName(COSName.STD_CF);
        encryptionDictionary.setStringFilterName(COSName.STD_CF);
        setAES(true);

        // Algorithm 10: compute "Perms" value
        byte[] perms = new byte[16];
        perms[0] = (byte) permissionInt;
        perms[1] = (byte) (permissionInt >>> 8);
        perms[2] = (byte) (permissionInt >>> 16);
        perms[3] = (byte) (permissionInt >>> 24);
        perms[4] = (byte) 0xFF;
        perms[5] = (byte) 0xFF;
        perms[6] = (byte) 0xFF;
        perms[7] = (byte) 0xFF;
        perms[8] = 'T'; // we always encrypt Metadata
        perms[9] = 'a';
        perms[10] = 'd';
        perms[11] = 'b';
        for (int i = 12; i <= 15; i++) {
            perms[i] = (byte) rnd.nextInt();
        }

        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"),
                new IvParameterSpec(new byte[16]));

        byte[] permsEnc = cipher.doFinal(perms);

        encryptionDictionary.setPerms(permsEnc);
    } catch (GeneralSecurityException e) {
        logIfStrongEncryptionMissing();
        throw new IOException(e);
    }
}

From source file:tv.ouya.sample.game.OptionsActivity.java

private void requestPurchase(final Options.Level level)
        throws GeneralSecurityException, JSONException, UnsupportedEncodingException {
    final String productId = getProductIdForLevel(level);

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

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", productId);
    purchaseRequest.put("testing", "true"); // This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);/* w ww  .j av a 2s  .  c  o m*/
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    Purchasable purchasable = new Purchasable(productId, Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, productId);
    }
    mOuyaFacade.requestPurchase(purchasable, new OuyaResponseListener<String>() {
        @Override
        public void onSuccess(String result) {
            String responseProductId;
            try {
                OuyaEncryptionHelper helper = new OuyaEncryptionHelper();

                JSONObject response = new JSONObject(result);
                String responseUUID = helper.decryptPurchaseResponse(response, mPublicKey);
                synchronized (mOutstandingPurchaseRequests) {
                    responseProductId = mOutstandingPurchaseRequests.remove(responseUUID);
                }
                if (responseProductId == null || !responseProductId.equals(productId)) {
                    onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS,
                            "Purchased product is not the same as purchase request product", Bundle.EMPTY);
                    return;
                }
            } catch (JSONException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (ParseException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (IOException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (GeneralSecurityException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            }

            if (responseProductId.equals(getProductIdForLevel(level))) {
                setNeedsPurchaseText(levelToRadioButton.get(level), false);
                Toast.makeText(OptionsActivity.this, "Level purchased!", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(int errorCode, String errorMessage, Bundle optionalData) {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this,
                    "Error making purchase!\n\nError " + errorCode + "\n" + errorMessage + ")",
                    Toast.LENGTH_LONG).show();

        }

        @Override
        public void onCancel() {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this, "You cancelled the purchase!", Toast.LENGTH_LONG).show();
        }
    });
}

From source file:org.apache.hadoop.hbase.mob.compactions.TestMobCompactor.java

@Test(timeout = 300000)
public void testMajorCompactionFromAdmin() throws Exception {
    resetConf();/*from  w ww . ja va  2 s . c om*/
    int mergeSize = 5000;
    // change the mob compaction merge size
    conf.setLong(MobConstants.MOB_COMPACTION_MERGEABLE_THRESHOLD, mergeSize);
    SecureRandom rng = new SecureRandom();
    byte[] keyBytes = new byte[AES.KEY_LENGTH];
    rng.nextBytes(keyBytes);
    String algorithm = conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
    Key cfKey = new SecretKeySpec(keyBytes, algorithm);
    byte[] encryptionKey = EncryptionUtil.wrapKey(conf,
            conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, User.getCurrent().getShortName()), cfKey);
    final TableName tableName = TableName.valueOf(name.getMethodName());
    HTableDescriptor desc = new HTableDescriptor(tableName);
    HColumnDescriptor hcd1 = new HColumnDescriptor(family1);
    hcd1.setMobEnabled(true);
    hcd1.setMobThreshold(0);
    hcd1.setEncryptionType(algorithm);
    hcd1.setEncryptionKey(encryptionKey);
    HColumnDescriptor hcd2 = new HColumnDescriptor(family2);
    hcd2.setMobEnabled(true);
    hcd2.setMobThreshold(0);
    desc.addFamily(hcd1);
    desc.addFamily(hcd2);
    admin.createTable(desc, getSplitKeys());
    Table table = conn.getTable(tableName);
    BufferedMutator bufMut = conn.getBufferedMutator(tableName);
    int count = 4;
    // generate mob files
    loadData(admin, bufMut, tableName, count, rowNumPerFile);
    int rowNumPerRegion = count * rowNumPerFile;

    assertEquals("Before deleting: mob rows count", regionNum * rowNumPerRegion, countMobRows(table));
    assertEquals("Before deleting: mob cells count", regionNum * cellNumPerRow * rowNumPerRegion,
            countMobCells(table));
    assertEquals("Before deleting: mob file count", regionNum * count, countFiles(tableName, true, family1));

    createDelFile(table, tableName, Bytes.toBytes(family1), Bytes.toBytes(qf1));

    assertEquals("Before compaction: mob rows count", regionNum * (rowNumPerRegion - delRowNum),
            countMobRows(table));
    assertEquals("Before compaction: mob cells count",
            regionNum * (cellNumPerRow * rowNumPerRegion - delCellNum), countMobCells(table));
    assertEquals("Before compaction: family1 mob file count", regionNum * count,
            countFiles(tableName, true, family1));
    assertEquals("Before compaction: family2 mob file count", regionNum * count,
            countFiles(tableName, true, family2));
    assertEquals("Before compaction: family1 del file count", regionNum, countFiles(tableName, false, family1));
    assertEquals("Before compaction: family2 del file count", regionNum, countFiles(tableName, false, family2));

    // do the major mob compaction, it will force all files to compaction
    admin.majorCompact(tableName, hcd1.getName(), CompactType.MOB);

    waitUntilMobCompactionFinished(tableName);
    assertEquals("After compaction: mob rows count", regionNum * (rowNumPerRegion - delRowNum),
            countMobRows(table));
    assertEquals("After compaction: mob cells count",
            regionNum * (cellNumPerRow * rowNumPerRegion - delCellNum), countMobCells(table));
    assertEquals("After compaction: family1 mob file count", regionNum, countFiles(tableName, true, family1));
    assertEquals("After compaction: family2 mob file count", regionNum * count,
            countFiles(tableName, true, family2));
    assertEquals("After compaction: family1 del file count", 0, countFiles(tableName, false, family1));
    assertEquals("After compaction: family2 del file count", regionNum, countFiles(tableName, false, family2));
    Assert.assertTrue(verifyEncryption(tableName, family1));
    table.close();
}

From source file:com.intel.diceros.test.securerandom.DRNGTest.java

@Override
public void performTest() throws Exception {
    SecureRandom random = SecureRandom.getInstance("DRNG", "DC");
    random.nextDouble();/* w w  w. j  av a2s  . c o m*/
    byte[] bytes = new byte[65536];
    random.nextBytes(bytes);

    final int[] epsilon = bytes2Ints(bytes);
    testFrequency(epsilon);
    testBlockFrequency(epsilon, 10);
    testRuns(epsilon);
    testLongestRunOfOnes(epsilon);
    testRank(epsilon);
    testDiscreteFourierTransform(epsilon);
    testNonOverlappingTemplateMatching(epsilon, 4);
    testOverlappingTemplateMatchings(epsilon, 9);
    testUniversal(epsilon);
    testLinearComplexity(epsilon, 1000);
    testSerial(epsilon, 2);
    testApproximateEntropy(epsilon, 2);
    testCumulativeSums(epsilon);
    testRandomExcursions(epsilon);
    testRandomExcursionsVariant(epsilon);
}

From source file:com.cloud.api.ApiServer.java

public void loginUser(HttpSession session, String username, String password, Long domainId, String domainPath,
        String loginIpAddress, Map<String, Object[]> requestParameters) throws CloudAuthenticationException {
    // We will always use domainId first. If that does not exist, we will use domain name. If THAT doesn't exist
    // we will default to ROOT
    if (domainId == null) {
        if (domainPath == null || domainPath.trim().length() == 0) {
            domainId = DomainVO.ROOT_DOMAIN;
        } else {/*from   w ww  .  ja v a  2  s .  co m*/
            Domain domainObj = _domainMgr.findDomainByPath(domainPath);
            if (domainObj != null) {
                domainId = domainObj.getId();
            } else { // if an unknown path is passed in, fail the login call
                throw new CloudAuthenticationException("Unable to find the domain from the path " + domainPath);
            }
        }
    }

    UserAccount userAcct = _accountMgr.authenticateUser(username, password, domainId, loginIpAddress,
            requestParameters);
    if (userAcct != null) {
        String timezone = userAcct.getTimezone();
        float offsetInHrs = 0f;
        if (timezone != null) {
            TimeZone t = TimeZone.getTimeZone(timezone);
            s_logger.info("Current user logged in under " + timezone + " timezone");

            java.util.Date date = new java.util.Date();
            long longDate = date.getTime();
            float offsetInMs = (t.getOffset(longDate));
            offsetInHrs = offsetInMs / (1000 * 60 * 60);
            s_logger.info("Timezone offset from UTC is: " + offsetInHrs);
        }

        Account account = _accountMgr.getAccount(userAcct.getAccountId());

        // set the userId and account object for everyone
        session.setAttribute("userid", userAcct.getId());
        UserVO user = (UserVO) _accountMgr.getActiveUser(userAcct.getId());
        if (user.getUuid() != null) {
            session.setAttribute("user_UUID", user.getUuid());
        }

        session.setAttribute("username", userAcct.getUsername());
        session.setAttribute("firstname", userAcct.getFirstname());
        session.setAttribute("lastname", userAcct.getLastname());
        session.setAttribute("accountobj", account);
        session.setAttribute("account", account.getAccountName());

        session.setAttribute("domainid", account.getDomainId());
        DomainVO domain = (DomainVO) _domainMgr.getDomain(account.getDomainId());
        if (domain.getUuid() != null) {
            session.setAttribute("domain_UUID", domain.getUuid());
        }

        session.setAttribute("type", Short.valueOf(account.getType()).toString());
        session.setAttribute("registrationtoken", userAcct.getRegistrationToken());
        session.setAttribute("registered", new Boolean(userAcct.isRegistered()).toString());

        if (timezone != null) {
            session.setAttribute("timezone", timezone);
            session.setAttribute("timezoneoffset", Float.valueOf(offsetInHrs).toString());
        }

        // (bug 5483) generate a session key that the user must submit on every request to prevent CSRF, add that
        // to the login response so that session-based authenticators know to send the key back
        SecureRandom sesssionKeyRandom = new SecureRandom();
        byte sessionKeyBytes[] = new byte[20];
        sesssionKeyRandom.nextBytes(sessionKeyBytes);
        String sessionKey = Base64.encodeBase64String(sessionKeyBytes);
        session.setAttribute("sessionkey", sessionKey);

        return;
    }
    throw new CloudAuthenticationException("Failed to authenticate user " + username + " in domain " + domainId
            + "; please provide valid credentials");
}