List of usage examples for org.springframework.security.crypto.keygen KeyGenerators secureRandom
public static BytesKeyGenerator secureRandom(int keyLength)
From source file:com.my.quickstart.util.Digests.java
/** * ?UUIDsalt/*from w ww . j a v a 2s . co m*/ * @return */ public static String generateUUIDSalt() { byte[] b = KeyGenerators.secureRandom(16).generateKey(); String salt = UUID.nameUUIDFromBytes(b).toString(); return salt; }
From source file:org.matrix.security.crypto.encrypt.Encryptors.java
/** * Creates a standard password-based bytes encryptor using 256 bit AES encryption. * Derives the secret key using PKCS #5's PBKDF2 (Password-Based Key Derivation Function #2). * Salts the password to prevent dictionary attacks against the key. * The provided salt is expected to be hex-encoded; it should be random and at least 8 bytes in length. * Also applies a random 16 byte initialization vector to ensure each encrypted message will be unique. * Requires Java 6./*from w ww . ja v a 2 s . c o m*/ * * @param password the password used to generate the encryptor's secret key; should not be shared * @param salt a hex-encoded, random, site-global salt value to use to generate the key */ public static BytesEncryptor standard(CharSequence password, CharSequence salt) { return new AesBytesEncryptor(password.toString(), salt, KeyGenerators.secureRandom(16)); }
From source file:io.stallion.utils.Encrypter.java
public static String encryptString(String password, String value) { String salt = KeyGenerators.string().generateKey(); SecretKeySpec skeySpec = makeKeySpec(password, salt); byte[] iv = KeyGenerators.secureRandom(16).generateKey(); String ivString = Hex.encodeHexString(iv); try {//from w w w.j a v a 2 s. co m Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv)); /* Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv)); */ byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName("UTF-8"))); String s = StringUtils.strip(new Base32().encodeAsString(encrypted), "=").toLowerCase(); // Strip line breaks s = salt + ivString + s.replaceAll("(\\n|\\r)", ""); return s; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:pl.exsio.frameset.vaadin.module.util.usergen.UserGenModule.java
private void generateUsers(Form form) { OptionGroup groups = (OptionGroup) form.getField("groups"); Set<Group> groupsSet = getGroupsSet(groups); Set<Role> rolesSet = getRolesSet(form); String usernamePrefix = (String) form.getField("usernamePrefix").getValue(); String usernameSuffix = (String) form.getField("usernameSuffix").getValue(); Long from = Long.parseLong((String) form.getField("from").getValue()); Long to = Long.parseLong((String) form.getField("to").getValue()); Table csvTable = createCsvTable();/*from www .j a va 2 s . c o m*/ for (int i = from.intValue(); i < to.intValue(); i++) { String username = usernamePrefix + i + "@" + usernameSuffix; byte[] byteArray = KeyGenerators.secureRandom(2).generateKey(); String passwordSuffix = ""; for (byte b : byteArray) { passwordSuffix += new Byte(b).toString(); } String password = usernamePrefix + passwordSuffix; User user = this.securityEntities.newUser(); user.setUsername(username); user.setPassword(this.encoder.encode(password)); user.setEmail(username); user.setEnabled(true); user.setGroups(groupsSet); user.setRoles(rolesSet); Item item = csvTable.addItem(username); item.getItemProperty("username").setValue(username); try { this.securityRepositories.getUserRepository().save(user); item.getItemProperty("password").setValue(password); } catch (DataIntegrityViolationException ex) { item.getItemProperty("password").setValue(t("username_exists")); } } CSVExporter exporter = createCsvExporter(csvTable); this.addComponent(exporter); Notification.show(t("generation_completed")); }
From source file:de.thm.arsnova.services.UserService.java
@Override public DbUser createDbUser(String username, String password) { if (null == keygen) { keygen = KeyGenerators.secureRandom(32); }// ww w .ja va 2s. c om if (null == mailPattern) { parseMailAddressPattern(); } if (null == mailPattern || !mailPattern.matcher(username).matches()) { return null; } if (null != databaseDao.getUser(username)) { return null; } DbUser dbUser = new DbUser(); dbUser.setUsername(username); dbUser.setPassword(encodePassword(password)); dbUser.setActivationKey(RandomStringUtils.randomAlphanumeric(32)); dbUser.setCreation(System.currentTimeMillis()); DbUser result = databaseDao.createOrUpdateUser(dbUser); if (null != result) { sendActivationEmail(result); } return result; }
From source file:de.thm.arsnova.service.UserServiceImpl.java
@Override public UserProfile create(String username, String password) { String lcUsername = username.toLowerCase(); if (null == keygen) { keygen = KeyGenerators.secureRandom(16); }//from ww w . j av a 2 s .com if (null == mailPattern) { parseMailAddressPattern(); } if (null == mailPattern || !mailPattern.matcher(lcUsername).matches()) { logger.info("User registration failed. {} does not match pattern.", lcUsername); return null; } if (null != userRepository.findByAuthProviderAndLoginId(UserProfile.AuthProvider.ARSNOVA, lcUsername)) { logger.info("User registration failed. {} already exists.", lcUsername); return null; } UserProfile userProfile = new UserProfile(); UserProfile.Account account = new UserProfile.Account(); userProfile.setAccount(account); userProfile.setAuthProvider(UserProfile.AuthProvider.ARSNOVA); userProfile.setLoginId(lcUsername); account.setPassword(encodePassword(password)); account.setActivationKey(RandomStringUtils.randomAlphanumeric(32)); userProfile.setCreationTimestamp(new Date()); /* Repository is accessed directly without EntityService to skip permission check */ UserProfile result = userRepository.save(userProfile); if (null != result) { sendActivationEmail(result); } else { logger.error("User registration failed. {} could not be created.", lcUsername); } return result; }
From source file:de.thm.arsnova.service.UserServiceImpl.java
private String generateGuestId() { if (null == keygen) { keygen = KeyGenerators.secureRandom(16); }/*from ww w . j a va 2s. c o m*/ return new String(Hex.encode(keygen.generateKey())); }
From source file:org.dspace.app.rest.security.jwt.JWTTokenHandler.java
/** * Generate a random 32 bytes key// w ww. j a v a2 s .c o m */ private String generateRandomKey() { //24 bytes because BASE64 encoding makes this 32 bytes //Base64 takes 4 characters for every 3 bytes BytesKeyGenerator bytesKeyGenerator = KeyGenerators.secureRandom(24); byte[] secretKey = bytesKeyGenerator.generateKey(); return Base64.encodeBase64String(secretKey); }
From source file:org.springframework.security.crypto.scrypt.SCryptPasswordEncoder.java
/** * Creates a new instance//from w w w.ja va2 s.co m * * @param cpuCost * cpu cost of the algorithm (as defined in scrypt this is N). * must be power of 2 greater than 1. Default is currently 16,348 * or 2^14) * @param memoryCost * memory cost of the algorithm (as defined in scrypt this is r) * Default is currently 8. * @param parallelization * the parallelization of the algorithm (as defined in scrypt * this is p) Default is currently 1. Note that the * implementation does not currently take advantage of * parallelization. * @param keyLength * key length for the algorithm (as defined in scrypt this is * dkLen). The default is currently 32. * @param saltLength * salt length (as defined in scrypt this is the length of S). * The default is currently 64. */ public SCryptPasswordEncoder(int cpuCost, int memoryCost, int parallelization, int keyLength, int saltLength) { if (cpuCost <= 1) { throw new IllegalArgumentException("Cpu cost parameter must be > 1."); } if (memoryCost == 1 && cpuCost > 65536) { throw new IllegalArgumentException("Cpu cost parameter must be > 1 and < 65536."); } if (memoryCost < 1) { throw new IllegalArgumentException("Memory cost must be >= 1."); } int maxParallel = Integer.MAX_VALUE / (128 * memoryCost * 8); if (parallelization < 1 || parallelization > maxParallel) { throw new IllegalArgumentException("Parallelisation parameter p must be >= 1 and <= " + maxParallel + " (based on block size r of " + memoryCost + ")"); } if (keyLength < 1 || keyLength > Integer.MAX_VALUE) { throw new IllegalArgumentException("Key length must be >= 1 and <= " + Integer.MAX_VALUE); } if (saltLength < 1 || saltLength > Integer.MAX_VALUE) { throw new IllegalArgumentException("Salt length must be >= 1 and <= " + Integer.MAX_VALUE); } this.cpuCost = cpuCost; this.memoryCost = memoryCost; this.parallelization = parallelization; this.keyLength = keyLength; this.saltGenerator = KeyGenerators.secureRandom(saltLength); }