Example usage for java.security SecureRandom SecureRandom

List of usage examples for java.security SecureRandom SecureRandom

Introduction

In this page you can find the example usage for java.security SecureRandom SecureRandom.

Prototype

public SecureRandom() 

Source Link

Document

Constructs a secure random number generator (RNG) implementing the default random number algorithm.

Usage

From source file:com.jsonstore.util.JSONStoreUtil.java

public static byte[] generateLocalKey(int numBytes) {
    byte[] randBytes = new byte[numBytes];
    (new SecureRandom()).nextBytes(randBytes);
    return randBytes;
}

From source file:com.vmware.admiral.auth.lightwave.pc.X509CertificateHelper.java

public X509Certificate generateX509Certificate(String keyPairAlg, String sigAlg)
        throws NoSuchAlgorithmException, CertificateException, OperatorCreationException {

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyPairAlg);
    keyGen.initialize(1024, new SecureRandom());

    KeyPair clientKeyPair = keyGen.generateKeyPair();

    String solutionUser = "oidc.client" + UUID.randomUUID().toString();

    return generateCertificate(clientKeyPair, solutionUser, sigAlg);
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static KeyPair generate(File keystore) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }/*w  w  w . j  a va 2s. c  o  m*/

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (ks.containsAlias(ALIAS)) {
            PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
            PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
            return new KeyPair(publicKey, privateKey);
        } else {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(KEYSIZE, new SecureRandom());
            return generator.generateKeyPair();
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

From source file:com.blackcrowsys.sinscrypto.AesKeyGenerator.java

@Override
public String generateIV() {
    SecureRandom random = new SecureRandom();
    byte[] bytes = new byte[IVSIZE];
    random.nextBytes(bytes);/*from w  w w.  j  a va 2  s.c  o  m*/
    return Hex.encodeHexString(bytes);
}

From source file:io.kodokojo.service.redis.AbstractRedisStore.java

public AbstractRedisStore(Key key, String host, int port) {
    if (key == null) {
        throw new IllegalArgumentException("key must be defined.");
    }/*from   w ww . j  av a2s  .  co m*/
    if (isBlank(host)) {
        throw new IllegalArgumentException("host must be defined.");
    }
    this.key = key;
    pool = createJedisPool(host, port);
    try {
        messageDigest = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to get instance of SHA-1 digest");
    }

    SecureRandom secureRandom = new SecureRandom();
    saltKey = new BigInteger(128, secureRandom).toString(10);
}

From source file:club.jmint.crossing.specs.Security.java

public static String desEncrypt(String data, String key) throws CrossException {
    String ret = null;/*w w  w .  j a  v a  2s  . co m*/
    try {
        DESKeySpec desKey = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);

        Cipher cipher = Cipher.getInstance(CIPHER_DES_ALGORITHM);
        SecureRandom random = new SecureRandom();
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        byte[] results = cipher.doFinal(data.getBytes("UTF-8"));
        ret = Base64.encodeBase64String(results);
    } catch (Exception e) {
        CrossLog.printStackTrace(e);
        throw new CrossException(ErrorCode.COMMON_ERR_ENCRYPTION.getCode(),
                ErrorCode.COMMON_ERR_ENCRYPTION.getInfo());
    }
    return ret;
}

From source file:com.mastfrog.scamper.ProtocolModule.java

public ProtocolModule(int bossThreads, int workerThreads, DataEncoding useBson) {
    this.bossThreads = bossThreads;
    this.workerThreads = workerThreads;
    this.encoding = useBson;
    secureRandom = new SecureRandom();
    rand = new Random(secureRandom.nextLong());
}

From source file:com.cyberninjas.xerobillableexpenses.util.Settings.java

public Settings() {
    try {/*from  w  w w  .  j a v a  2 s.co  m*/
        String parentClass = new Exception().getStackTrace()[1].getClassName();
        this.prefs = Preferences.userNodeForPackage(Class.forName(parentClass));
        Random r = new SecureRandom();

        //Set IV
        this.iv = prefs.getByteArray("DRUGS", null);

        //Pick Random PWD
        byte[] b = new byte[128];
        r.nextBytes(b);
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        sha.update(b);
        String sHash = new String(Base64.encodeBase64(sha.digest()));

        String password = prefs.get("LAYOUT", sHash);
        if (password.equals(sHash))
            prefs.put("LAYOUT", sHash);

        //Keep 'em Guessing
        r.nextBytes(b);
        sha.update(b);
        prefs.put("PASSWORD", new String(Base64.encodeBase64(sha.digest())));

        //Set Random Salt
        byte[] tSalt = new byte[8];
        r.nextBytes(tSalt);
        byte[] salt = prefs.getByteArray("HIMALAYAN", tSalt);
        if (Arrays.equals(salt, tSalt))
            prefs.putByteArray("HIMALAYAN", salt);

        /* Derive the key, given password and salt. */
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
        SecretKey tmp = factory.generateSecret(spec);
        this.secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(RSAx509CertGen.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(RSAx509CertGen.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(RSAx509CertGen.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.znsx.util.licence.LicenceUtil.java

/**
 * ?DSA??p,q,g,j,x,y/*ww w  .j av a2 s.  com*/
 * 
 * @param seed
 *            ??
 * @throws Exception
 * @author huangbuji
 *         <p />
 *         Create at 2014-2-8 ?4:45:26
 */
@SuppressWarnings("restriction")
public static void genKey(String seed) throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = new SecureRandom();
    random.setSeed(seed.getBytes("utf8"));
    keygen.initialize(1024, random);

    KeyPair keyPair = keygen.generateKeyPair();
    DSAPublicKeyImpl publicKey = (DSAPublicKeyImpl) keyPair.getPublic();
    DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate();
    DSAParams dsaParams = privateKey.getParams();
    Base64 base64 = new Base64();
    String p = new String(base64.encode(dsaParams.getP().toByteArray()), "utf8");
    String q = new String(base64.encode(dsaParams.getQ().toByteArray()), "utf8");
    String g = new String(base64.encode(dsaParams.getG().toByteArray()), "utf8");
    String x = new String(base64.encode(privateKey.getX().toByteArray()), "utf8");
    String y = new String(base64.encode(publicKey.getY().toByteArray()), "utf8");
    System.out.println("P: " + p);
    System.out.println("Q: " + q);
    System.out.println("G: " + g);
    System.out.println("X: " + x);
    System.out.println("Y: " + y);

    String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8");
    String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8");
    System.err.println("public: " + publicKeyString);
    System.err.println("private: " + privateKeyString);

    File publicFile = new File("D:/binPublic.ky");
    File privateFile = new File("D:/binPrivate.ky");
    FileOutputStream out = new FileOutputStream(publicFile);
    out.write(publicKey.getEncoded());
    out.flush();
    out.close();
    out = new FileOutputStream(privateFile);
    out.write(privateKey.getEncoded());
    out.flush();
    out.close();
}

From source file:org.cloudfoundry.identity.uaa.login.feature.ChangePasswordIT.java

@Before
public void setUp() throws Exception {
    int randomInt = new SecureRandom().nextInt();

    String adminAccessToken = testClient.getOAuthAccessToken("admin", "adminsecret", "client_credentials",
            "clients.read clients.write clients.secret");

    String scimClientId = "scim" + randomInt;
    testClient.createScimClient(adminAccessToken, scimClientId);

    String scimAccessToken = testClient.getOAuthAccessToken(scimClientId, "scimsecret", "client_credentials",
            "scim.read scim.write password.write");

    userEmail = "user" + randomInt + "@example.com";
    testClient.createUser(scimAccessToken, userEmail, userEmail, "secret", true);
}