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.iso.mpeg.dash.crypto.ContentProtectionMpegDashSea.java

/**
 * This constructor is used to generate a new instance of baseline content protection
 * TODO clean up this function, 'cause, damn
 * //from w w  w .  ja  va 2  s  .c o  m
 * @param contentProtectionNode
 * @throws DashCryptoException
 */
ContentProtectionMpegDashSea(RepresentationType representation, long segmentStartNum)
        throws DashCryptoException {
    super(CONTENT_PROTECTION_SCHEME_ID_URI, segmentStartNum, representation);

    KeySystem baselineKeySys = new KeySystemBaselineHttp(this);
    keySystems.add(baselineKeySys);
    segmentEncryption = new SegmentEncryptionAES128CBC();

    // generate a random key to /tmp/key????????.bin
    SecureRandom secRnd = new SecureRandom();
    String keyPath = "/tmp/key" + Integer.toString(10000000 + secRnd.nextInt(90000000)) + ".bin";
    File keyFile = new File(keyPath);
    if (keyFile.exists())
        throw new DashCryptoException("Error - key file " + keyPath + " already exists");
    byte[] keyBytes = new byte[16];
    secRnd.nextBytes(keyBytes);
    try {
        FileUtils.writeByteArrayToFile(keyFile, keyBytes);
    } catch (IOException e) {
        throw new DashCryptoException(e);
    }

    //      // generate a random IV
    //      byte[] ivBytes = new byte[16];
    //      secRnd.nextBytes(ivBytes);

    // create a single CryptoTimeline, covering all segments, including path to random key and implicit IV      
    int numCryptoPeriods = representation.getSegmentList().getSegmentURLs().size(),
            numSegmentsPerCryptoPeriod = 1;
    if (numCryptoPeriods % 2 == 0) { // if even number of segments, have 2-seg cryptoperiods
        numCryptoPeriods /= 2;
        numSegmentsPerCryptoPeriod *= 2;
    }
    CryptoTimeline cryptoTimeline = new CryptoTimeline(keyPath, this, numCryptoPeriods);
    cryptoTimeline.setNumSegments(numSegmentsPerCryptoPeriod); // one or two segments per cryptoperiod
    //      cryptoTimeline.setIV(ivBytes);
    cryptoPeriods.add(cryptoTimeline);
    preAssignSegmentsToCryptoPeriods();

    // parse internal structure to descriptor (or should we do so lazily?)
    contentProtectionDescriptor = generateContentProtectionDescriptor();
}

From source file:org.jasig.cas.support.saml.util.AbstractSaml20ObjectBuilder.java

@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//from   ww w.  j a v  a2 s .  c o m
    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);
}

From source file:org.jumpmind.security.SecurityService.java

public String nextSecureHexString(int len) {
    if (len <= 0)
        throw new IllegalArgumentException("length must be positive");
    SecureRandom secRan = getSecRan();
    MessageDigest alg = null;//from   ww w.ja va 2 s .  c  o  m
    try {
        alg = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException ex) {
        return null;
    }
    alg.reset();
    int numIter = len / 40 + 1;
    StringBuffer outBuffer = new StringBuffer();
    for (int iter = 1; iter < numIter + 1; iter++) {
        byte randomBytes[] = new byte[40];
        secRan.nextBytes(randomBytes);
        alg.update(randomBytes);
        byte hash[] = alg.digest();
        for (int i = 0; i < hash.length; i++) {
            Integer c = new Integer(hash[i]);
            String hex = Integer.toHexString(c.intValue() + 128);
            if (hex.length() == 1)
                hex = "0" + hex;
            outBuffer.append(hex);
        }

    }

    return outBuffer.toString().substring(0, len);
}

From source file:org.apache.hadoop.hbase.regionserver.TestHMobStore.java

@Test
public void testMOBStoreEncryption() throws Exception {
    final Configuration conf = TEST_UTIL.getConfiguration();

    conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
    conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase");
    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);

    HColumnDescriptor hcd = new HColumnDescriptor(family);
    hcd.setMobEnabled(true);//from   w w w  . ja va2s .  co  m
    hcd.setMobThreshold(100);
    hcd.setMaxVersions(4);
    hcd.setEncryptionType(algorithm);
    hcd.setEncryptionKey(EncryptionUtil.wrapKey(conf,
            conf.get(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, User.getCurrent().getShortName()), cfKey));

    init(name.getMethodName(), conf, hcd, false);

    this.store.add(new KeyValue(row, family, qf1, 1, value));
    this.store.add(new KeyValue(row, family, qf2, 1, value));
    this.store.add(new KeyValue(row, family, qf3, 1, value));
    flush(1);

    this.store.add(new KeyValue(row, family, qf4, 1, value));
    this.store.add(new KeyValue(row, family, qf5, 1, value));
    this.store.add(new KeyValue(row, family, qf6, 1, value));
    flush(2);

    Collection<StoreFile> storefiles = this.store.getStorefiles();
    checkMobHFileEncrytption(storefiles);

    // Scan the values
    Scan scan = new Scan(get);
    InternalScanner scanner = (InternalScanner) store.getScanner(scan,
            scan.getFamilyMap().get(store.getFamily().getName()), 0);

    List<Cell> results = new ArrayList<Cell>();
    scanner.next(results);
    Collections.sort(results, KeyValue.COMPARATOR);
    scanner.close();
    Assert.assertEquals(expected.size(), results.size());
    for (int i = 0; i < results.size(); i++) {
        Assert.assertEquals(expected.get(i), results.get(i));
    }

    // Trigger major compaction
    this.store.triggerMajorCompaction();
    CompactionContext requestCompaction = this.store.requestCompaction(1, null);
    this.store.compact(requestCompaction, NoLimitCompactionThroughputController.INSTANCE);
    Assert.assertEquals(1, this.store.getStorefiles().size());

    //Check encryption after compaction
    checkMobHFileEncrytption(this.store.getStorefiles());
}

From source file:com.cloud.vm.VMInstanceVO.java

public VMInstanceVO(long id, long serviceOfferingId, String name, String instanceName, Type type,
        Long vmTemplateId, HypervisorType hypervisorType, long guestOSId, long domainId, long accountId,
        long userId, boolean haEnabled) {
    this.id = id;
    hostName = name != null ? name : uuid;
    if (vmTemplateId != null) {
        templateId = vmTemplateId;// ww w  . j a  va  2 s .co  m
    }
    this.instanceName = instanceName;
    this.type = type;
    this.guestOSId = guestOSId;
    this.haEnabled = haEnabled;
    state = State.Stopped;
    this.accountId = accountId;
    this.domainId = domainId;
    this.serviceOfferingId = serviceOfferingId;
    this.hypervisorType = hypervisorType;
    this.userId = userId;
    limitCpuUse = false;
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] randomBytes = new byte[16];
        random.nextBytes(randomBytes);
        vncPassword = Base64.encodeBase64URLSafeString(randomBytes);
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("Unexpected exception in SecureRandom Algorithm selection ", e);
    }
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

@Test
public void testRSTS_JAXWS_Client() throws Exception {
    ServletTester servletTester = new ServletTester();
    servletTester.addServlet(MyTestServlet.class, "/");

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter);
    File tmpP12File = File.createTempFile("ssl-", ".p12");
    LOG.debug("p12 file: " + tmpP12File.getAbsolutePath());
    persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray());

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststoreType("pkcs12");
    sslSocketConnector.setKeystoreType("pkcs12");
    sslSocketConnector.setPassword("secret");
    sslSocketConnector.setKeyPassword("secret");
    sslSocketConnector.setTrustPassword("secret");
    sslSocketConnector.setMaxIdleTime(30000);
    int sslPort = getFreePort();
    sslSocketConnector.setPort(sslPort);

    servletTester.getContext().getServer().addConnector(sslSocketConnector);
    String sslLocation = "https://localhost:" + sslPort + "/";

    servletTester.start();/*from  w  w  w.j  av a 2s  .c o m*/
    String location = servletTester.createSocketConnector(true);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager trustManager = new TestTrustManager(certificate);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    SSLContext.setDefault(sslContext);

    try {
        LOG.debug("running R-STS test...");
        RSTSClient client = new RSTSClient(sslLocation);
        SecurityToken inputSecurityToken = new SecurityToken();
        byte[] key = new byte[256 / 8];
        SecureRandom random = new SecureRandom();
        random.nextBytes(key);
        inputSecurityToken.setKey(key);
        inputSecurityToken.setAttachedReference("_" + UUID.randomUUID().toString());
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element tokenElement = document.createElement("Token");
        tokenElement.setTextContent("hello world");
        inputSecurityToken.setToken(tokenElement);

        client.getSecurityToken(inputSecurityToken, "https://auth.beta.agiv.be/ClaimsAwareService/Service.svc");
    } finally {
        servletTester.stop();
    }
}

From source file:org.xdi.oxauth.client.model.authorize.JwtAuthorizationRequest.java

public String getEncodedJwt() {
    String encodedJwt = null;//from  ww w  . ja  va  2 s.c om

    try {
        if (signatureAlgorithm == SignatureAlgorithm.NONE) {
            encodedJwt = JwtUtil.encodeJwt(headerToJSONObject(), payloadToJSONObject(), signatureAlgorithm);
        } else if (signatureAlgorithm == SignatureAlgorithm.HS256
                || signatureAlgorithm == SignatureAlgorithm.HS384
                || signatureAlgorithm == SignatureAlgorithm.HS512) {
            encodedJwt = JwtUtil.encodeJwt(headerToJSONObject(), payloadToJSONObject(), signatureAlgorithm,
                    sharedKey);
        } else if (signatureAlgorithm == SignatureAlgorithm.RS256
                || signatureAlgorithm == SignatureAlgorithm.RS384
                || signatureAlgorithm == SignatureAlgorithm.RS512) {
            encodedJwt = JwtUtil.encodeJwt(headerToJSONObject(), payloadToJSONObject(), signatureAlgorithm,
                    rsaPrivateKey);
        } else if (signatureAlgorithm == SignatureAlgorithm.ES256
                || signatureAlgorithm == SignatureAlgorithm.ES384
                || signatureAlgorithm == SignatureAlgorithm.ES512) {
            encodedJwt = JwtUtil.encodeJwt(headerToJSONObject(), payloadToJSONObject(), signatureAlgorithm,
                    ecPrivateKey);
        } else if (keyEncryptionAlgorithm != null && blockEncryptionAlgorithm != null) {
            JweEncrypterImpl jweEncrypter = null;
            if (rsaPublicKey != null) {
                jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm,
                        rsaPublicKey);
            } else {
                jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm,
                        sharedSymmetricKey);
            }

            String header = headerToJSONObject().toString();
            String encodedHeader = JwtUtil.base64urlencode(header.getBytes(Util.UTF8_STRING_ENCODING));

            String claims = payloadToJSONObject().toString();
            String encodedClaims = JwtUtil.base64urlencode(claims.getBytes(Util.UTF8_STRING_ENCODING));

            byte[] contentMasterKey = new byte[blockEncryptionAlgorithm.getCmkLength() / 8];
            SecureRandom random = new SecureRandom();
            random.nextBytes(contentMasterKey);
            String encodedEncryptedKey = jweEncrypter.generateEncryptedKey(contentMasterKey);

            byte[] initializationVector = new byte[blockEncryptionAlgorithm.getInitVectorLength() / 8];
            random.nextBytes(initializationVector);
            String encodedInitializationVector = JwtUtil.base64urlencode(initializationVector);

            String additionalAuthenticatedData = encodedHeader + "." + encodedEncryptedKey + "."
                    + encodedInitializationVector;

            Pair<String, String> result = jweEncrypter.generateCipherTextAndIntegrityValue(contentMasterKey,
                    initializationVector, additionalAuthenticatedData.getBytes(Util.UTF8_STRING_ENCODING),
                    encodedClaims.getBytes(Util.UTF8_STRING_ENCODING));
            String encodedCipherText = result.getFirst();
            String encodedIntegrityValue = result.getSecond();

            encodedJwt = encodedHeader + "." + encodedEncryptedKey + "." + encodedInitializationVector + "."
                    + encodedCipherText + "." + encodedIntegrityValue;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (InvalidJwtException e) {
        e.printStackTrace();
    } catch (InvalidJweException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return encodedJwt;
}

From source file:org.xdi.oxauth.client.model.authorize.JwtAuthorizationRequest.java

public String getEncodedJwt(String payload) {
    String encodedJwt = null;/*  w w w  . j av a 2 s  .  c o  m*/

    try {
        JSONObject payloadJsonObject = new JSONObject(payload);
        if (signatureAlgorithm == SignatureAlgorithm.NONE) {
            encodedJwt = JwtUtil.encodeJwt(headerToJSONObject(), payloadJsonObject, signatureAlgorithm);
        } else if (signatureAlgorithm == SignatureAlgorithm.HS256
                || signatureAlgorithm == SignatureAlgorithm.HS384
                || signatureAlgorithm == SignatureAlgorithm.HS512) {
            encodedJwt = JwtUtil.encodeJwt(headerToJSONObject(), payloadJsonObject, signatureAlgorithm,
                    sharedKey);
        } else if (signatureAlgorithm == SignatureAlgorithm.RS256
                || signatureAlgorithm == SignatureAlgorithm.RS384
                || signatureAlgorithm == SignatureAlgorithm.RS512) {
            encodedJwt = JwtUtil.encodeJwt(headerToJSONObject(), payloadJsonObject, signatureAlgorithm,
                    rsaPrivateKey);
        } else if (signatureAlgorithm == SignatureAlgorithm.ES256
                || signatureAlgorithm == SignatureAlgorithm.ES384
                || signatureAlgorithm == SignatureAlgorithm.ES512) {
            encodedJwt = JwtUtil.encodeJwt(headerToJSONObject(), payloadJsonObject, signatureAlgorithm,
                    ecPrivateKey);
        } else if (keyEncryptionAlgorithm != null && blockEncryptionAlgorithm != null) {
            JweEncrypterImpl jweEncrypter = null;
            if (rsaPublicKey != null) {
                jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm,
                        rsaPublicKey);
            } else {
                jweEncrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm,
                        sharedSymmetricKey);
            }

            String header = headerToJSONObject().toString();
            String encodedHeader = JwtUtil.base64urlencode(header.getBytes(Util.UTF8_STRING_ENCODING));

            String claims = payloadJsonObject.toString();
            String encodedClaims = JwtUtil.base64urlencode(claims.getBytes(Util.UTF8_STRING_ENCODING));

            byte[] contentMasterKey = new byte[blockEncryptionAlgorithm.getCmkLength() / 8];
            SecureRandom random = new SecureRandom();
            random.nextBytes(contentMasterKey);
            String encodedEncryptedKey = jweEncrypter.generateEncryptedKey(contentMasterKey);

            byte[] initializationVector = new byte[blockEncryptionAlgorithm.getInitVectorLength() / 8];
            random.nextBytes(initializationVector);
            String encodedInitializationVector = JwtUtil.base64urlencode(initializationVector);

            String additionalAuthenticatedData = encodedHeader + "." + encodedEncryptedKey + "."
                    + encodedInitializationVector;

            Pair<String, String> result = jweEncrypter.generateCipherTextAndIntegrityValue(contentMasterKey,
                    initializationVector, additionalAuthenticatedData.getBytes(Util.UTF8_STRING_ENCODING),
                    encodedClaims.getBytes(Util.UTF8_STRING_ENCODING));
            String encodedCipherText = result.getFirst();
            String encodedIntegrityValue = result.getSecond();

            encodedJwt = encodedHeader + "." + encodedEncryptedKey + "." + encodedInitializationVector + "."
                    + encodedCipherText + "." + encodedIntegrityValue;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (InvalidJwtException e) {
        e.printStackTrace();
    } catch (InvalidJweException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return encodedJwt;
}

From source file:org.apache.ws.security.message.WSSecEncryptedKey.java

/**
 * Create an ephemeral key//from w w w .j a va  2 s. c o m
 * 
 * @return an ephemeral key
 * @throws WSSecurityException
 */
protected byte[] generateEphemeralKey() throws WSSecurityException {
    try {
        final SecureRandom r = WSSecurityUtil.resolveSecureRandom();
        if (r == null) {
            throw new WSSecurityException("Random generator is not initialzed.");
        }
        byte[] temp = new byte[this.keySize / 8];
        r.nextBytes(temp);
        return temp;
    } catch (Exception e) {
        throw new WSSecurityException("Error in creating the ephemeral key", e);
    }
}

From source file:com.trifork.riak.RiakClient.java

/**
 * helper method to use a reasonable default client id
 * /*from   ww w .  j av  a2  s.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");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] data = new byte[6];
        sr.nextBytes(data);
        clid = Base64Coder.encodeLines(data);
        prefs.put("client_id", clid);
        try {
            prefs.flush();
        } catch (BackingStoreException e) {
            throw new IOException(e);
        }
    }

    setClientID(clid);
}