Example usage for java.security SecureRandom getInstance

List of usage examples for java.security SecureRandom getInstance

Introduction

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

Prototype

public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SecureRandom object that implements the specified Random Number Generator (RNG) algorithm.

Usage

From source file:fr.amapj.service.engine.sudo.SudoManager.java

private String generateSudo() {
    try {// www . j  a v a 2  s  .  com
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

        byte[] salt = new byte[16];
        random.nextBytes(salt);

        Base64 coder = new Base64(true);
        String str = coder.encodeAsString(salt);
        str = str.replace('\r', '0');
        str = str.replace('\n', '0');
        return str;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Erreur inattendue", e);
    }
}

From source file:org.talend.utils.security.AES.java

public AES() {
    try {/*from ww w  .  j a va2s  .  c om*/
        // TDI-28380: Database password in tac db configuration page becomes empty once restart tomcat on Solaris.
        // TDI-30348: Whole tac configuration lost for the passwords.

        Provider p = Security.getProvider("BC");
        KeyGenerator keyGen = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM, p);

        SecureRandom random = SecureRandom.getInstance(RANDOM_SHA1PRNG);
        random.setSeed(KeyValues);
        keyGen.init(128, random);

        Key key = keyGen.generateKey();

        ecipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, p);
        dcipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, p);

        ecipher.init(Cipher.ENCRYPT_MODE, key);
        dcipher.init(Cipher.DECRYPT_MODE, key);
    } catch (Exception e) {
        // log the error to avoid that break GWT service
        log.error(e.getMessage(), e);
    }
}

From source file:com.cloud.consoleproxy.ConsoleProxy.java

private static String genDefaultEncryptorPassword() {
    try {/*from  ww w. j  a v  a2  s  .c om*/
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

        byte[] randomBytes = new byte[16];
        random.nextBytes(randomBytes);
        return Base64.encodeBase64String(randomBytes);
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("Unexpected exception ", e);
        assert (false);
    }

    return "Dummy";
}

From source file:org.computerist.ssltools.zap.ZapSslCertificateUtils.java

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return// w w  w  .  j a  va 2s  .c  om
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));
        certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(X509Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        Vector<DERObject> eku = new Vector<>(3, 1);
        eku.add(KeyPurposeId.id_kp_serverAuth);
        eku.add(KeyPurposeId.id_kp_clientAuth);
        eku.add(KeyPurposeId.anyExtendedKeyUsage);
        certGen.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(FixedSslCertificateService.ZAPROXY_JKS_ALIAS, privKey,
                FixedSslCertificateService.PASSPHRASE, new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

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

/**
 * Generates a salt for password hashing.<br/>
 * @return the salt//from  w w w. ja v a2 s .c  om
 */
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.glite.slcs.session.impl.MemorySessions.java

/**
 * Constructor accessed only by factory//from ww  w.ja  va 2 s  .  c o  m
 */
public MemorySessions() {
    super();
    sessions_ = new Hashtable();
    try {
        random_ = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
    }
}

From source file:com.cisco.oss.foundation.directory.utils.ObfuscatUtil.java

/**
 * Generate a random salt./*from  w ww. j a v  a2  s  .  c  o  m*/
 *
 * @return
 *         the random salt.
 * @throws NoSuchAlgorithmException
 *         the NoSuchAlgorithmException.
 */
public static byte[] generateSalt() throws NoSuchAlgorithmException {
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    byte[] salt = new byte[8];
    random.nextBytes(salt);
    return salt;
}

From source file:jp.primecloud.auto.common.component.PasswordEncryptor.java

/**
 *
 * ?/*from  w  ww  . j  a  v a 2s  . c  o  m*/
 *
 */
private void initialize() {
    ivParameterSpec = new IvParameterSpec(IV);

    try {
        secureRandom = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    // ?
    secureRandom.setSeed(System.currentTimeMillis());
    // ??
    characterSet = createCharacterSet();

    try {
        chipher = Cipher.getInstance(CIPHER_PARAM);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.qut.middleware.saml2.identifier.impl.IdentifierGeneratorImpl.java

public IdentifierGeneratorImpl(IdentifierCache cache) {
    if (cache == null) {
        throw new IllegalArgumentException("identifier cache cannot be null."); //$NON-NLS-1$
    }/*from www .j av a 2  s.  c  om*/
    this.cache = cache;
    this.lock = new ReentrantLock();

    try {
        /* Attempt to get the specified RNG instance */
        this.random = SecureRandom.getInstance(this.RNG);
    } catch (NoSuchAlgorithmException nsae) {
        this.logger.error(Messages.getString("IdentifierGeneratorImpl.13")); //$NON-NLS-1$
        this.logger.debug(nsae.getLocalizedMessage(), nsae);
        this.random = new SecureRandom();
    }

    this.random.setSeed(System.currentTimeMillis());
}

From source file:org.wso2.carbon.identity.provider.openid.OpenIDServerAssociationStore.java

/**
 * Here we instantiate a DAO to access the identity database.
 *
 * @param dbConnection/*from   w w w  .  ja v a 2  s . c  o m*/
 * @param privateAssociations if this association store stores private associations
 */
public OpenIDServerAssociationStore(String associationsType) {
    try {
        SecureRandom secureRandom = SecureRandom.getInstance(SHA_1_PRNG);
        storeId = secureRandom.nextInt(9999);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("SHA1PRNG algorithm could not be found.");
    }
    timestamp = Long.toString(new Date().getTime());
    counter = 0;
    cache = OpenIDAssociationCache.getCacheInstance();
    // get singleton dao
    dao = OpenIDAssociationDAO.getInstance(associationsType);
}