List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:Main.java
/** * Generate a random string (used for database encryption) * * @return a random string of 64 characters *//*from w w w . j a v a 2 s .co m*/ public static String generateRandomString() { SecureRandom generator = new SecureRandom(); StringBuilder randomStringBuilder = new StringBuilder(); char tempChar; int numbChar = 0; while (numbChar < SEED_LENGTH) { tempChar = (char) (generator.nextInt(SEED_SPACE) + 32); boolean num = tempChar >= 48 && tempChar < 58;//0-9 boolean cap = tempChar >= 65 && tempChar < 91;//A-Z boolean lower = tempChar >= 65 && tempChar < 91;//a-z if (num || cap || lower) { randomStringBuilder.append(tempChar); numbChar++; } } return randomStringBuilder.toString(); }
From source file:com.example.license.RSAUtil.java
public static KeyPair generatorKeyPair(String seed) throws Exception { KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); SecureRandom random = new SecureRandom(); random.setSeed(seed.getBytes());/*w ww . jav a 2 s.c o m*/ kpGenerator.initialize(2014, random); KeyPair keyPair = kpGenerator.generateKeyPair(); return keyPair; }
From source file:Main.java
/** * Generates a device ID.//from w w w . jav a2 s . c om */ public synchronized static String getDeviceId(Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String deviceId = preferences.getString("device_id", null); if (deviceId == null) { String chars = "123456789ABCDEFGHJKLMNPQRSTUVWXY"; byte[] randomBytes = new byte[12]; new SecureRandom().nextBytes(randomBytes); StringBuilder builder = new StringBuilder(12); for (int i = 0; i < 12; i++) { builder.append(chars.charAt((randomBytes[i] & 0xFF) % chars.length())); } deviceId = builder.toString(); preferences.edit().putString("device_id", deviceId).apply(); } return deviceId; }
From source file:com.shadows.liquiblq.common.utils.HashManager.java
public static String GenerateStringSalt() { SecureRandom RANDOM = new SecureRandom(); byte[] salt = new byte[16]; RANDOM.nextBytes(salt);/*w w w .ja v a2 s .co m*/ return Base64.encodeBase64String(salt); }
From source file:Main.java
public static byte[] getRandomKey() { byte[] keybytes = new byte[16]; SecureRandom sr = new SecureRandom(); sr.nextBytes(keybytes);//from ww w . ja va2 s. c om return keybytes; }
From source file:Main.java
static byte[] generateRandomKey(int bitSize) { if (bitSize == 0 || bitSize % 8 != 0) return null; return new SecureRandom().generateSeed(bitSize / 8); }
From source file:bridgempp.PermissionsManager.java
public static String generateKey(int permissions, boolean useOnce) { SecureRandom random = new SecureRandom(); byte[] byteKey = new byte[32]; random.nextBytes(byteKey);// ww w. j a va 2s . c o m String key = Base64.getEncoder().encodeToString(byteKey); accessKeys.put(key, new AccessKey(key, permissions, useOnce)); return key; }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
public static void main(String[] args) throws Exception { logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName()); Options options = new Options(); options.addOption("unisonXMLFile", true, "The full path to the Unison xml file"); options.addOption("keystorePath", true, "The full path to the Unison keystore"); options.addOption("chainName", true, "The name of the authentication chain"); options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2"); options.addOption("idpName", true, "The name of the identity provider application"); options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file"); options.addOption("createDefault", false, "If set, add default parameters"); options.addOption("action", true, "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey"); options.addOption("urlBase", true, "Base URL, no URI; https://host:port"); options.addOption("alias", true, "Key alias"); options.addOption("newKeystorePath", true, "Path to the new keystore"); options.addOption("newKeystorePassword", true, "Password for the new keystore"); options.addOption("help", false, "Prints this message"); options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key"); options.addOption("dlqName", true, "The name of the dead letter queue"); options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6"); options.addOption("secretkey", true, "base64 encoded secret key"); options.addOption("envFile", true, "Environment variables for parmaterized configs"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args, true); if (args.length == 0 || cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("OpenUnisonUtils", options); }/*from w ww. j a va 2 s . com*/ logger.info("Loading Unison Configuration"); String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options); TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options); String action = loadOption(cmd, "action", options); TremoloType ttWrite = null; if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) { ttWrite = loadTremoloType(unisonXMLFile); } logger.info("Configuration loaded"); logger.info("Loading the keystore..."); String ksPath = loadOption(cmd, "keystorePath", options); KeyStore ks = loadKeyStore(ksPath, ttRead); logger.info("...loaded"); if (action.equalsIgnoreCase("import-sp-metadata")) { importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks); } else if (action.equalsIgnoreCase("export-sp-metadata")) { exportSPMetaData(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("print-secretkey")) { printSecreyKey(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("import-secretkey")) { importSecreyKey(options, cmd, ttRead, ks, ksPath); } else if (action.equalsIgnoreCase("create-secretkey")) { Security.addProvider(new BouncyCastleProvider()); logger.info("Creating AES-256 secret key"); String alias = loadOption(cmd, "alias", options); logger.info("Alias : '" + alias + "'"); KeyGenerator kg = KeyGenerator.getInstance("AES", "BC"); kg.init(256, new SecureRandom()); SecretKey sk = kg.generateKey(); ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null); logger.info("Saving key"); ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray()); logger.info("Finished"); } else if (action.equalsIgnoreCase("export-secretkey")) { logger.info("Export Secret Key"); logger.info("Loading key"); String alias = loadOption(cmd, "alias", options); SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray()); logger.info("Loading new keystore path"); String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options); logger.info("Loading new keystore password"); String ksPassword = loadOption(cmd, "newKeystorePassword", options); KeyStore newKS = KeyStore.getInstance("PKCS12"); newKS.load(null, ttRead.getKeyStorePassword().toCharArray()); newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null); newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray()); logger.info("Exported"); } else if (action.equalsIgnoreCase("import-idp-metadata")) { importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks); } else if (action.equalsIgnoreCase("export-idp-metadata")) { exportIdPMetadata(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("clear-dlq")) { logger.info("Getting the DLQ Name..."); String dlqName = loadOption(cmd, "dlqName", options); QueUtils.emptyDLQ(ttRead, dlqName); } else if (action.equalsIgnoreCase("upgradeFrom106")) { logger.info("Upgrading OpenUnison's configuration from 1.0.6"); String backupFileName = unisonXMLFile + ".bak"; logger.info("Backing up to '" + backupFileName + "'"); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile))); PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName)); String line = null; while ((line = in.readLine()) != null) { out.println(line); } out.flush(); out.close(); in.close(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout); FileOutputStream fsout = new FileOutputStream(unisonXMLFile); fsout.write(bout.toByteArray()); fsout.flush(); fsout.close(); } }
From source file:Main.java
public static String encryptData(String password, String plaintextData) throws Exception { // Thank you Mr. Nelenkov String maybeThisHelps = "http://nelenkov.blogspot.com/2012/04/using-password-based-encryption-on.html"; Log.v(TAG, maybeThisHelps);/*w w w .j a va2s.c om*/ int iterationCount = 100; //because Polaroid int keyLength = 256; int saltLength = keyLength; SecureRandom random = new SecureRandom(); byte[] salt = new byte[saltLength]; random.nextBytes(salt); KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded(); SecretKey key = new SecretKeySpec(keyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] iv = new byte[cipher.getBlockSize()]; random.nextBytes(iv); IvParameterSpec ivParams = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, key, ivParams); byte[] ciphertext = cipher.doFinal(plaintextData.getBytes("UTF-8")); String ivToString = new String(Base64.encode(iv, 0)); String saltToString = new String(Base64.encode(salt, 0)); String ciphertextToString = new String(Base64.encode(ciphertext, 0)); Log.d(TAG, ivToString + "]" + saltToString + "]" + ciphertextToString); return (ivToString + "]" + saltToString + "]" + ciphertextToString).replace("\n", ""); }
From source file:net.maritimecloud.identityregistry.utils.PasswordUtil.java
public static String generatePassword() { SecureRandom secRandom = new SecureRandom(); return new BigInteger(130, secRandom).toString(32); }