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:adminpassword.Encryption.java

public String encrypt(String word, String idKey) throws Exception {

    byte[] ivBytes;
    String password = idKey; //you can give whatever you want. This is for testing purpose
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[20];
    random.nextBytes(bytes);/*from  ww  w  . j a v a 2s . co m*/

    byte[] saltBytes = bytes;

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65556, 256);
    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    //encrypting the word
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(word.getBytes("UTF-8"));

    //prepend salt and vi
    byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
    System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
    System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
    System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length,
            encryptedTextBytes.length);
    return new Base64().encodeToString(buffer);
}

From source file:com.ec2box.manage.util.OTPUtil.java

/**
 * generates OPT secret//  ww w. j  a  v  a2 s.c om
 *
 * @return String shared secret
 */
public static String generateSecret() {
    byte[] buffer = new byte[(NUM_SCRATCH_CODES * SCRATCH_CODE_SIZE) + SECRET_SIZE];
    new SecureRandom().nextBytes(buffer);

    byte[] secret = Arrays.copyOf(buffer, SECRET_SIZE);

    return new String(new Base32().encode(secret));

}

From source file:com.bytecode.util.Crypto.java

private static byte[] encrypt(String keystring, String message, int bits) throws Exception {
    byte[] encValue = null;
    SecureRandom random = new SecureRandom();
    byte[] nonceBytes = new byte[8];
    random.nextBytes(nonceBytes);//from  w w  w .  j av a  2  s.c  o m
    IvParameterSpec nonce = new IvParameterSpec(Arrays.copyOf(nonceBytes, 16));

    Key key = generateKey(keystring, bits);
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.ENCRYPT_MODE, key, nonce);
    byte[] ciphertextWithoutNonce = c.doFinal(message.getBytes("UTF-8"));
    encValue = Arrays.copyOf(nonceBytes, nonceBytes.length + ciphertextWithoutNonce.length);
    for (int i = 0; i < ciphertextWithoutNonce.length; i++) {
        encValue[i + 8] = ciphertextWithoutNonce[i];
    }

    return encValue;
}

From source file:Main.java

private static SSLContext sslContextForTrustedCertificates(InputStream in) {
    try {//from   ww w  . ja v a 2 s . c om
        CertificateFactory e = CertificateFactory.getInstance("X.509");
        Collection certificates = e.generateCertificates(in);
        if (certificates.isEmpty()) {
            throw new IllegalArgumentException("expected non-empty set of trusted certificates");
        } else {
            char[] password = "password".toCharArray();
            KeyStore keyStore = newEmptyKeyStore(password);
            int index = 0;
            Iterator keyManagerFactory = certificates.iterator();
            while (keyManagerFactory.hasNext()) {
                Certificate trustManagerFactory = (Certificate) keyManagerFactory.next();
                String sslContext = Integer.toString(index++);
                keyStore.setCertificateEntry(sslContext, trustManagerFactory);
            }

            KeyManagerFactory var10 = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            var10.init(keyStore, password);
            TrustManagerFactory var11 = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            var11.init(keyStore);
            SSLContext var12 = SSLContext.getInstance("TLS");
            var12.init(var10.getKeyManagers(), var11.getTrustManagers(), new SecureRandom());
            return var12;
        }
    } catch (Exception var9) {
        var9.printStackTrace();
    }
    return null;
}

From source file:com.collaide.fileuploader.helper.TestHelper.java

protected static String getRandomString() {
    return new BigInteger(130, new SecureRandom()).toString(32);
}

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

/**
 * ??//from   ww  w . j  a  v  a2 s .  co  m
 * 
 * @param seed
 *            ??
 * @return
 * @throws Exception
 */
public static Map<String, String> generateKey(String seed) throws Exception {
    Map<String, String> map = new HashMap<String, String>(2);
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = new SecureRandom();
    random.setSeed(seed.getBytes("utf8"));
    keygen.initialize(1024, random);

    KeyPair keyPair = keygen.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    Base64 base64 = new Base64();
    String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8");
    String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8");
    // BASE64Encoder encoder = new BASE64Encoder();
    // map.put("public", encoder.encode(publicKey.getEncoded()));
    // map.put("private", encoder.encode(privateKey.getEncoded()));
    map.put("public", publicKeyString);
    map.put("private", privateKeyString);

    System.out.println("publicKey: " + map.get("public"));
    System.out.println("privateKey: " + map.get("private"));
    return map;
}

From source file:com.cprassoc.solr.auth.security.Sha256AuthenticationProvider.java

static void putUser(String user, String pwd, Map credentials) {
    if (user == null || pwd == null)
        return;/*  w ww .  ja va  2 s .  c om*/

    final Random r = new SecureRandom();
    byte[] salt = new byte[32];
    r.nextBytes(salt);
    String saltBase64 = Base64.encodeBase64String(salt);
    String val = sha256(pwd, saltBase64) + " " + saltBase64;
    credentials.put(user, val);
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java

protected static SSLContext getAnonymousSSLContext() throws GeneralSecurityException {
    SSLContext sslContext = getSSLContext();
    sslContext.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom());
    return sslContext;
}

From source file:com.drisoftie.cwdroid.util.CredentialUtils.java

private static SecretKey generateKey() throws NoSuchAlgorithmException {
    // Generate a 256-bit key
    final int outputKeyLength = 256;

    SecureRandom secureRandom = new SecureRandom();
    // Do *not* seed secureRandom! Automatically seeded from system entropy.
    KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
    keyGenerator.init(outputKeyLength, secureRandom);
    return keyGenerator.generateKey();
}

From source file:com.shenit.commons.codec.CodecUtils.java

/**
 * ??//  w  w  w. j ava2 s  . c o m
 * 
 * @return
 */
public static byte[] generateRandomKey(String codec) {
    SecureRandom sr = new SecureRandom();
    // DES?KeyGenerator
    KeyGenerator kg;
    try {
        kg = KeyGenerator.getInstance(codec);
        kg.init(sr);
        // ?
        Key secret = kg.generateKey();
        // ??
        return secret.getEncoded();
    } catch (NoSuchAlgorithmException e) {
        LOG.warn("[generateKey] not supported algorithm -> " + codec);
    }
    return null;
}