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:net.sourceforge.fenixedu.domain.phd.PhdParticipant.java

public void ensureExternalAccess() {
    if (StringUtils.isEmpty(getAccessHashCode())) {
        super.setAccessHashCode(UUID.randomUUID().toString());
        super.setPassword(RandomStringUtils.random(15, 0, 0, true, true, null, new SecureRandom()));
    }//w w  w. j  a v  a2  s  . c  o  m
}

From source file:org.apache.juneau.rest.test.TestMicroservice.java

static SSLConnectionSocketFactory getSSLSocketFactory() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    TrustManager tm = new SimpleX509TrustManager(true);
    sslContext.init(null, new TrustManager[] { tm }, new SecureRandom());
    return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}

From source file:com.ubipass.middleware.web.action.LicenceMgtAction.java

private String getDate(String userName, String licenceKey) throws Exception {

    // DES????//from   ww  w  .  ja va2  s  .co m
    SecureRandom sr = new SecureRandom();

    byte rawKeyData[] = (userName + "midware").getBytes();

    // ?DESKeySpec
    DESKeySpec dks = new DESKeySpec(rawKeyData);

    // ?DESKeySpec??
    // SecretKey
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey key = keyFactory.generateSecret(dks);

    // Cipher??
    Cipher cipher = Cipher.getInstance("DES");

    // ?Cipher
    cipher.init(Cipher.DECRYPT_MODE, key, sr);

    // ??
    licenceKey = new String(cipher.doFinal(Base64.decodeBase64(licenceKey.getBytes())));

    String[] tmpStr = licenceKey.split("-");

    if (tmpStr.length == 2)
        return tmpStr[1];

    throw new InvalidLicenseException();

}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClient(Certificate[] sslCertificate) {
    DefaultHttpClient httpClient;/*from  w  w w .j  a v  a2s. com*/

    httpClient = new DefaultHttpClient();
    try {
        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:oracle.custom.ui.utils.ServerUtils.java

public static SSLContext getContext() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager tms[] = new TrustManager[] { new X509TrustManager() {
        @Override/*  www  . j a  v  a2s  . c o m*/
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tms, new SecureRandom());
    return context;
}

From source file:io.personium.test.jersey.HttpClientFactory.java

/**
 * SSLSocket?./*from  w w w  . java 2  s .c om*/
 * @return ???SSLSocket
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    // CHECKSTYLE:OFF
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }

    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers =============");
                X509Certificate[] ret = new X509Certificate[0];
                return ret;
            }

            public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e1) {
        throw new RuntimeException(e1);
    }
    // CHECKSTYLE:ON

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier)
    // hostnameVerifier);

    return socketFactory;
}

From source file:net.bluemix.newsaggregator.api.AuthenticationServlet.java

static public void configureSSL() {
    // note that it's not adviced to use this in a production application
    // you should overwrite the X509TrustManager to use a cacerts file (list of trusted signers) 
    try {// w  ww.  j a  va  2  s  . com
        SSLContext sslContext = SSLContext.getInstance("SSL_TLSv2");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } }, new SecureRandom());

        Executor.unregisterScheme("https");
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Executor.registerScheme(new Scheme("https", 443, sslSocketFactory));

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

From source file:jp.pigumer.mqtt.Client.java

void createMqttConnectOptions() {
    Optional<SSLContext> context = initTrustManagers().map(trustManagers -> {
        try {//from  www .j av  a  2  s .  c o  m
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, trustManagers, new SecureRandom());
            return sslContext;
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "failed load", e);
            return null;
        }
    });

    options = new MqttConnectOptions();
    options.setUserName(userName);
    options.setPassword(password);
    context.ifPresent(sslContext -> options.setSocketFactory(sslContext.getSocketFactory()));
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Creates a new self-signed X509 certificate
 *
 * @param pair the public/private keypair- the pubkey will be added to the cert and the private
 * key will be used to sign the certificate
 * @param subject the distinguished name of the subject
 * @param isAuthority true to make the cert a CA cert, false otherwise
 * @return//from w ww .j  av  a  2 s  .co  m
 */
public static X509Certificate newSelfSignedCertificate(KeyPair pair, X500Name subject, boolean isAuthority) {
    X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(subject,
            BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)),
            Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), subject, pair.getPublic());
    try {
        b.addExtension(Extension.basicConstraints, true, new BasicConstraints(isAuthority));
    } catch (CertIOException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        X509CertificateHolder bcCert = b.build(
                new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(pair.getPrivate()));
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(bcCert);
    } catch (CertificateException | OperatorCreationException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:net.link.util.test.pkix.PkiTestUtils.java

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        PrivateKey issuerPrivateKey, @Nullable X509Certificate issuerCert, DateTime notBefore,
        DateTime notAfter, @Nullable String signatureAlgorithm, boolean includeAuthorityKeyIdentifier,
        boolean caCert, boolean timeStampingPurpose, @Nullable URI ocspUri)
        throws IOException, CertificateException, OperatorCreationException {

    String finalSignatureAlgorithm = signatureAlgorithm;
    if (null == signatureAlgorithm)
        finalSignatureAlgorithm = "SHA512WithRSAEncryption";

    X509Principal issuerDN;//from   w  ww.  ja  v  a  2  s  .c o m
    if (null != issuerCert)
        issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().toString());
    else
        issuerDN = new X509Principal(subjectDn);

    // new bc 2.0 API
    X509Principal subject = new X509Principal(subjectDn);
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    BigInteger serialNumber = new BigInteger(SERIALNUMBER_NUM_BITS, new SecureRandom());

    X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
            X500Name.getInstance(issuerDN.toASN1Primitive()), serialNumber, notBefore.toDate(),
            notAfter.toDate(), X500Name.getInstance(subject.toASN1Primitive()), publicKeyInfo);

    // prepare signer
    ContentSigner signer = new JcaContentSignerBuilder(finalSignatureAlgorithm).build(issuerPrivateKey);

    // add extensions
    certificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));
    PublicKey issuerPublicKey;
    if (null != issuerCert)
        issuerPublicKey = issuerCert.getPublicKey();
    else
        issuerPublicKey = subjectPublicKey;
    if (includeAuthorityKeyIdentifier)
        certificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                createAuthorityKeyId(issuerPublicKey));

    certificateBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(caCert));

    if (timeStampingPurpose)
        certificateBuilder.addExtension(X509Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier,
                new DERIA5String(ocspUri.toString()));
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateBuilder.addExtension(X509Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    // build
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateBuilder.build(signer));
}