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:ECToken3.java

public static final String encryptv3(String key, String input) throws java.io.UnsupportedEncodingException,
        java.security.NoSuchAlgorithmException, javax.crypto.NoSuchPaddingException,
        java.security.InvalidKeyException, javax.crypto.IllegalBlockSizeException,
        javax.crypto.BadPaddingException, java.security.InvalidAlgorithmParameterException {

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| Encrypt\n");
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| key:                   %s\n", key);
    //System.out.format("| token:                 %s\n", input);

    //----------------------------------------------------
    // Get SHA-256 of key
    //----------------------------------------------------
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(key.getBytes("ASCII"));
    byte[] keyDigest = md.digest();

    //----------------------------------------------------
    // Get Random IV
    //----------------------------------------------------
    SecureRandom random = new SecureRandom();
    byte[] ivBytes = new byte[12];
    random.nextBytes(ivBytes);//from   ww w.ja  v a 2s  . c o  m

    //----------------------------------------------------
    // Encrypt
    //----------------------------------------------------
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(true, new AEADParameters(new KeyParameter(keyDigest), MAC_SIZE_BITS, ivBytes));
    byte[] inputBytes = input.getBytes("ASCII");

    byte[] enc = new byte[cipher.getOutputSize(inputBytes.length)];

    try {
        int res = cipher.processBytes(inputBytes, 0, inputBytes.length, enc, 0);
        cipher.doFinal(enc, res);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    byte[] ivPlusCipherText = new byte[ivBytes.length + enc.length];
    System.arraycopy(ivBytes, 0, ivPlusCipherText, 0, ivBytes.length);
    System.arraycopy(enc, 0, ivPlusCipherText, ivBytes.length, enc.length);

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| iv:                    %s\n", bytesToHex(ivBytes));
    //System.out.format("| ciphertext:            %s\n", bytesToHex(Arrays.copyOfRange(enc, 0, enc.length - 16)));
    //System.out.format("| tag:                   %s\n", bytesToHex(Arrays.copyOfRange(enc, enc.length - 16, enc.length)));
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| token:                 %s\n", bytesToHex(ivPlusCipherText));
    //System.out.format("+-------------------------------------------------------------\n");

    String result = null;
    byte[] temp = null;
    Base64 encoder = new Base64(0, temp, true);
    byte[] encodedBytes = encoder.encode(ivPlusCipherText);
    String encodedStr = new String(encodedBytes, "ASCII").trim();
    String encodedStrTrim = encodedStr.trim();
    return encodedStr.trim();
}

From source file:fr.mycellar.configuration.SpringSecurityConfiguration.java

@Bean
public KeyBasedPersistenceTokenService keyBasedPersistenceTokenService() {
    KeyBasedPersistenceTokenService keyBasedPersistenceTokenService = new KeyBasedPersistenceTokenService();
    keyBasedPersistenceTokenService.setSecureRandom(new SecureRandom());
    keyBasedPersistenceTokenService.setServerInteger(1);
    keyBasedPersistenceTokenService.setServerSecret("_s_e_c_r_e_t_");
    return keyBasedPersistenceTokenService;
}

From source file:com.liusoft.dlog4j.upgrade.StringUtils.java

/**
 * //from  ww w  .  j a  v a  2  s  .com
 * @param src   ??
 * @param key   8?
 * @return      ??
 * @throws Exception
 */
public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
    //      DES????
    SecureRandom sr = new SecureRandom();
    // ?DESKeySpec
    DESKeySpec dks = new DESKeySpec(key);
    // ?DESKeySpec??
    // SecretKey
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    // Cipher??
    Cipher cipher = Cipher.getInstance(DES);
    // ?Cipher
    cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
    // ??
    // ??
    return cipher.doFinal(src);
}

From source file:cz.alej.michalik.totp.server.Users.java

/**
 * Vygenerovat kl? pro generovn TOTP hesla
 * //w w  w  .j  av  a  2 s. co m
 * @return base32 etzec
 */
public static String generateSecret() {
    // Chci kl? o velikosti 20 byt
    int maxBits = 20 * 8 - 1;
    SecureRandom rand = new SecureRandom();
    byte[] val = new BigInteger(maxBits, rand).toByteArray();
    return new Base32().encodeToString(val);
}

From source file:dk.netarkivet.harvester.harvesting.metadata.MetadataFileWriterTester.java

@Test
public void testMetadataFileWriterArc() throws IOException {
    File metafile = getOutputArcFile("metadata.arc");
    MetadataFileWriter mdfw = MetadataFileWriterArc.createWriter(metafile);

    String uri = "http://www.netarkivet.dk/";
    long ctm = System.currentTimeMillis();

    SecureRandom random = new SecureRandom();
    byte[] payload = new byte[8192];
    random.nextBytes(payload);/*from  ww  w.j  a v a  2  s. c  om*/

    mdfw.write(uri, "application/binary", "127.0.0.1", ctm, payload);
    mdfw.close();
    metafile.deleteOnExit();

    File metadataArcFile = getOutputArcFile("42-metadata-1.arc");
    MetadataFileWriter mfwa = MetadataFileWriterArc.createWriter(metadataArcFile);
    for (File f : logsDir.listFiles()) {
        mfwa.writeFileTo(f, "metadata://netarkivet.dk/crawl/logs/" + f.getName(), "text/plain");
    }
}

From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java

/**
 * ??/*from  w  ww. java  2  s  .  c o m*/
 * 
 * @param pubFile public file
 * @param priFile private file
 * @throws IOException IOException
 */
@SuppressWarnings("PMD.PrematureDeclaration")
protected void generater(File pubFile, File priFile) throws IOException {
    try {
        KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM);
        SecureRandom secrand = new SecureRandom();
        keygen.initialize(KEY_SIZE, secrand);
        KeyPair keys = keygen.genKeyPair();
        PublicKey pubkey = keys.getPublic();
        PrivateKey prikey = keys.getPrivate();
        byte[] priKey = Base64.encodeBase64(prikey.getEncoded());
        byte[] pubKey = Base64.encodeBase64(pubkey.getEncoded());
        if (pubFile.exists()) {
            throw new IOException(pubFile.getPath() + " is exist!");
        }
        if (priFile.exists()) {
            throw new IOException(priFile.getPath() + " is exist!");
        }
        OutputStream pubOutput = new FileOutputStream(pubFile);
        try {
            IOUtils.write(pubKey, pubOutput);
        } finally {
            IOUtils.closeQuietly(pubOutput);
        }
        OutputStream priOutput = new FileOutputStream(priFile);
        try {
            IOUtils.write(priKey, priOutput);
        } finally {
            IOUtils.closeQuietly(priOutput);
        }
    } catch (NoSuchAlgorithmException e) {
        log.error("?", e);
    }
}

From source file:it.infn.mw.iam.config.X509TrustConfig.java

@Bean
public SSLContext sslContext() {

    try {/*  ww w  . j  a  v  a  2 s .c om*/
        SSLContext context = SSLContext.getInstance("TLSv1");

        X509TrustManager tm = SocketFactoryCreator.getSSLTrustManager(certificateValidator());
        SecureRandom r = new SecureRandom();
        context.init(null, new TrustManager[] { tm }, r);

        return context;

    } catch (NoSuchAlgorithmException | KeyManagementException 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  w ww .  j av a 2s  .c o m
    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:com.cfs.util.AESCriptografia.java

public String gerarSalt() {
    /* Tamanho do buffer do Salt */
    final int SALT_LENGTH = 16;
    /* Criao do buffer do Salt */
    byte[] salt = new byte[SALT_LENGTH];
    /* Criao do gerador de Salt */
    SecureRandom aleatorio = new SecureRandom();
    /* Gerao de um Salt aleatrio */
    aleatorio.nextBytes(salt);/*w  w  w .  j a  v  a2s  .c om*/
    /* Encoda o salt gerado */
    String retorno = Base64.encodeBase64String(salt);
    /* Retorna o salt gerado */
    return retorno;
}

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

public static HttpClient getHttpsClient(byte[] sslCertificateBytes) {
    DefaultHttpClient httpClient;/*from   ww  w.j  a  va2 s  .  c o m*/
    Certificate[] sslCertificate;

    httpClient = new DefaultHttpClient();
    try {
        sslCertificate = convertByteArrayToCertificate(sslCertificateBytes);

        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;
}