Trying to format negative number to String using:
(DecimalFormat) NumberFormat.getNumberInstance(new Locale("no")));
Using jdk-10.0.2. I have found out that Norway and some other countries are using Unicode Character 'MINUS SIGN' (U+2212) for negative prefix, while most other countries are using Unicode Character 'HYPHEN-MINUS' (U+002D). This is a problem as test are failing on equal and on my Mac all negative prefix is HYPHEN-MINUS.
A solution I have found is to call setNegativePrefix("-") after getting the DecimalFormat to override the strange local negative prefixes.
Please also see workaround at Orcale (end of page) https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8214926.
#Test
public void norwegianNegativePrefixDifferentFromEnglish() throws UnsupportedEncodingException {
Assertions.assertThat(((DecimalFormat) NumberFormat.getNumberInstance(new Locale("no"))).getNegativePrefix())
.isEqualTo(((DecimalFormat) NumberFormat.getNumberInstance(new Locale("en"))).getNegativePrefix());
}
Anyone know why? Executing this Java gives the attached results:
public void fintLocals() {
HashMap<String, List<String>> negativeSignAndLocals = new HashMap<String, List<String>>();
for (Locale locale : Locale.getAvailableLocales()) {
DecimalFormat formatForLocal = ((DecimalFormat) NumberFormat.getNumberInstance(locale));
// System.out.println(formatForLocal.getNegativePrefix()+ " minus for "+locale);
List<String> negLoc = negativeSignAndLocals.get(formatForLocal.getNegativePrefix());
if (negLoc == null) {
negativeSignAndLocals.put(formatForLocal.getNegativePrefix(), new ArrayList<>());
}
negativeSignAndLocals.get(formatForLocal.getNegativePrefix()).add(locale.toString());
}
for (Map.Entry<String, List<String>> entry : negativeSignAndLocals.entrySet()) {
System.out.println("Negative sign = " + entry.getKey() + " as Hex value " + charToHex(entry.getKey().charAt(0))
+ " are used by: " + (String) String.join(",", entry.getValue()));
}
}
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
char[] array = {hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f]};
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
Negative sign − as Hex value 2212 are used by: nn,sv_SE,sv,se_NO,nb_SJ,no_NO_NY,sv_FI,no,ksh,gsw_CH,et,gsw,gsw_FR,fi,et_EE,rm,nb_NO,fi_FI,rm_CH,ksh_DE,se_FI,no_NO,lt_LT,nn_NO,se_SE,se,fo_DK,fo_FO,fo,lt,gsw_LI,sv_AX,nb
Negative sign - as Hex value 002d are used by: ,bg,kea,zu,am_ET,fr_DZ,ti_ET,bo_CN,hsb,qu_EC,ta_SG,lv,en_NU,zh_SG_#Hans,en_MS,en_GG,en_JM,vo,kkj,sr_ME,es_BO,dz_BT,mer,sah,en_ZM,fr_ML,br,ha_NG,bs_BA,dsb_DE,sk,os_GE,ml,en_MT,en_LR,en_GH,en_IL,cs,el,tzm_MA,af,sw_UG,ses_ML,smn,tk_TM,sr_ME_#Cyrl,dsb,lkt_US,vai_LR_#Latn,ji_001,yo_NG,khq,sw_CD,vo_001,en_PW,pl_PL,fil_PH,sr_CS,ne_IN,es_PH,es_ES,es_CO,bg_BG,ji,bs_BA_#Latn,en_VC,es_US,agq,hsb_DE,en_US_POSIX,en_150,en_KN,ha_NE,pt_MO,ebu,ro_RO,zh__#Hans,lb_LU,sr_ME_#Latn,es_GT,so_KE,dje_NE,bas_CM,fr_PM,fr_MG,es_CL,mn,agq_CM,kam_KE,teo,tr_TR,eu,en_MO,shi__#Tfng,en_BZ,sq_AL,es_DO,ru,twq_NE,az,nmg_CM,kl_GL,en_NR,nd,kk,az__#Cyrl,en_MP,en_GD,tk,hy,shi__#Latn,en_BW,en_AU,en_CY,kab_DZ,kde_TZ,ta_MY,ti_ER,nus_SS,en_RW,nd_ZW,ksb,luo,lb,ne,en_IE,zh_SG,ln_CD,en_KI,nnh_CM,om_ET,ja_JP,my,ka,mgh,or_IN,fr_MF,shi,kl,yue_HK,en_SZ,rwk_TZ,zh,es_PE,mgh_MZ,saq,az__#Lat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lkt,zh_CN_#Hans,is,es_419,si,pt_AO,en_001,en,guz_KE,es_IC,ca,ru_KG,fr_MR,zh_TW_#Hant,bm_ML,pa_PK,kw_GB,ug_CN,as_IN,es_BR,zh_HK,khq_ML,sw_KE,en_SB,th_TH,rw_RW,chr_US,shi_MA_#Tfng,nyn,yue,jmc,en_MW,naq_NA,mk,en_IO,en_DE,en_CC,bs,ro_MD,en_FI,pt_PT,fy,az_AZ_#Cyrl,th,dav_KE,uz_UZ,shi_MA_#Latn,es_CU,en_SC,en_VI,haw,eu_ES,en_UG,en_NZ,dje,es_UY,bas,mas_KE,ru_UA,sg_CF,el_GR,yav_CM,uz__#Latn,sg,da_GL,en_FJ,de_LI,en_BB,km_KH,smn_FI,hr_BA,de_AT,nl,lu_CD,ca_ES_VALENCIA,so_SO,lv_LV,es_CR,fr_GA,sr,sr_RS_#Cyrl,bem,en_MU,da,wae,gl_ES,en_IM,az_AZ_#Latn,en_LS,ig,en_HK,en_GI,ce_RU,en_CA,gd,ka_GE,fr_SY,sw_TZ,fr_RW,so_ET,nl_BE,mg_MG,cy_GB,en_VG,cu,os_RU,sr_RS_#Latn,en_TC,ky_KG,af_NA,vun,en_IN,lu,ki,yo,es_NI,ff_MR,mas_TZ,ti,kok,ewo,ms_BN,br_FR
Negative sign as Hex value 200e are used by: fa_AF,ar_EH,fa_IR,ar_MR,fa,ur_IN,ps,lrc_IR,lrc_IQ,ps_AF,ar_DZ,iw,lrc,pa_PK_#Arab,ar_MA,iw_IL,ur,uz__#Arab,ar_LB,ks_IN,ur_PK,mzn,mzn_IR,uz_AF_#Arab,ar_TN,ks,pa__#Arab,ar_LY
Negative sign as Hex value 200f are used by: ar_JO,ar_SA,ar_TD,ar_EG,ar_SD,ar_KM,ar_IL,ar_SY,ar_PS,ar_YE,ar_OM,ar_SS,ar_ER,ar_SO,ar_AE,ar_BH,ar_IQ,ar_QA,ckb_IQ,ar,ckb_IR,ar_001,ckb,ar_KW,ar_DJ
How do I create a random password that meets the system's length and character set requirements in Java?
I have to create a random password that is 10-14 characters long and has at least one uppercase, one lowercase, and one special character. Unfortunately, some special characters are too special and cannot be used, so I cannot use just printed ASCII.
Many of the examples on this site generate a random password or session key without enough entropy in the characters or without realistic requirements in a business setting like the ones given above, so I'm asking more pointed question to get a better answer.
My character set, every special character on a standard US keyboard except for a space:
A-Z
a-z
0-9
~`!##$%^&*()-_=+[{]}\|;:'",<.>/?
I suggest using apache commons RandomStringUtils. Use something what is already done.
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!##$%^&*()-_=+[{]}\\|;:\'\",<.>/?";
String pwd = RandomStringUtils.random( 15, characters );
System.out.println( pwd );
If you are using maven
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
otherwise download jar
UPDATE
Version with secure random. So matter of required characters left and can be solved as in comment, generate required parts separately and normal ones. Then join them randomly.
char[] possibleCharacters = (new String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!##$%^&*()-_=+[{]}\\|;:\'\",<.>/?")).toCharArray();
String randomStr = RandomStringUtils.random( randomStrLength, 0, possibleCharacters.length-1, false, false, possibleCharacters, new SecureRandom() );
System.out.println( randomStr );
I recently learned about Passay. It provides the required functionality needed in its PasswordGenerator class. It randomly generates passwords meeting the requirements similar to what is written below using CharacterRules rather than PasswordCharacterSets as I have done below. Instead of holding a list of unused indexes for random character insertion, it simply shuffles the character buffer after inserting characters that meet the requirements.
Below is left over from before, I recommend using Passay if your licensing allows it, this code should work otherwise and provides details of why the generated passwords are crytographically strong
I ended up writing this code twice. Once to get a random character result, but it turned out the distribution of characters depended on the size of the character set(whoops!). I rewrote it and now you should just copy/paste the code and change the Main.java to the character sets you want. Although it could have been done differently, I think this is a relatively straightforward approach to get the correct result and I encourage reuse, comments, criticisms, and well-thought edits.
The controls of the PasswordGenerator code is as follows:
Min/Max Length: Set using a random number
PasswordCharacterSet: It is assumed that all PasswordCharacterSets passed into PasswordGenerator consist of unique character sets, if not, the random characters will have a skew towards the duplicates.
PasswordCharacterSet Min Characters: The min characters to use for this character set.
The main bits for the actual password generation:
Randomness of Random: We're using SecureRandom which is backed by a cryptographically strong PRNG, rather than the Random class which is not.
Random character order for the password: All the indexes of the pw char array are added to the remainingIndexes array. As we call addRandomCharacters, it removes an index randomly and we use the removed index to populate the array.
Random characters: In addRandomCharacters, a random index from the character index we're using is chosen and added to the pw array.
Guaranteeing minimum characters of each type are set: We simply carve out the minimum character amount first. We choose the minimum amount of random values from each character set and then move on.
Random distribution for the remaining characters: After the minimum values have been set, we want to make the rest of the characters random across all character sets. All the characters are added to a single array. The remaining slots are filled using the same strategy for the previous character sets.
Description of password complexity: Password complexity is usually talked about in bits of entropy. Here are the number of possibilities for your keyspace:
There is at least one uppercase alpha character (out of 26), one lowercase alpha character(out of 26), one digit (out of 10), and one special character (out of 32), the way you calculate the number of possibilities is the number of possibilities for each character multiplied by the number of characters since they are randomly placed in the string. So we know the possibilities for four of the characters are:
Required Characters = 26*26*10*32=216,320
All remaining characters have 94 (26+26+10+32) possibilities each
Our calculation is:
Characters Possibilities Bits of Entropy
10 chars 216,320*94^6 = 149,232,631,038,033,920 ~2^57
11 chars 216,320*94^7 = 14,027,867,317,575,188,480 ~2^63
12 chars 216,320*94^8 = 1,318,619,527,852,067,717,120 ~2^70
13 chars 216,320*94^9 = 123,950,235,618,094,365,409,280 ~2^76
14 chars 216,320*94^10 = 11,651,322,148,100,870,348,472,320 ~2^83
With this is mind, if you want the most secure passwords, you should always choose the highest amount of characters possible which is 14 in this case.
Main.java
package org.redtown.pw;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.redtown.pw.PasswordGenerator.PasswordCharacterSet;
public class Main {
public static void main(String[] args) {
Set<PasswordCharacterSet> values = new HashSet<PasswordCharacterSet>(EnumSet.allOf(SummerCharacterSets.class));
PasswordGenerator pwGenerator = new PasswordGenerator(values, 10, 14);
for(int i=0; i < 10; ++i) {
System.out.println(pwGenerator.generatePassword());
}
}
private static final char[] ALPHA_UPPER_CHARACTERS = { 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private static final char[] ALPHA_LOWER_CHARACTERS = { 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
private static final char[] NUMERIC_CHARACTERS = { '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9' };
private static final char[] SPECIAL_CHARACTERS = { '~', '`', '!', '#', '#',
'$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', '{',
']', '}', '\\', '|', ';', ':', '\'', '"', ',', '<', '.', '>', '/',
'?' };
private enum SummerCharacterSets implements PasswordCharacterSet {
ALPHA_UPPER(ALPHA_UPPER_CHARACTERS, 1),
ALPHA_LOWER(ALPHA_LOWER_CHARACTERS, 1),
NUMERIC(NUMERIC_CHARACTERS, 1),
SPECIAL(SPECIAL_CHARACTERS, 1);
private final char[] chars;
private final int minUsage;
private SummerCharacterSets(char[] chars, int minUsage) {
this.chars = chars;
this.minUsage = minUsage;
}
#Override
public char[] getCharacters() {
return chars;
}
#Override
public int getMinCharacters() {
return minUsage;
}
}
}
PasswordGenerator.java
package org.redtown.pw;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class PasswordGenerator {
private final List<PasswordCharacterSet> pwSets;
private final char[] allCharacters;
private final int minLength;
private final int maxLength;
private final int presetCharacterCount;
public PasswordGenerator(Collection<PasswordCharacterSet> origPwSets, int minLength, int maxLength) {
this.minLength = minLength;
this.maxLength = maxLength;
// Make a copy of the character arrays and min-values so they cannot be changed after initialization
int pwCharacters = 0;
int preallocatedCharacters = 0;
List<PasswordCharacterSet> pwSets = new ArrayList<PasswordCharacterSet>(origPwSets.size());
for(PasswordCharacterSet origpwSet : origPwSets) {
PasswordCharacterSet newPwSet = new PwSet(origpwSet);
pwSets.add(newPwSet);
pwCharacters += newPwSet.getCharacters().length;
preallocatedCharacters += newPwSet.getMinCharacters();
}
this.presetCharacterCount = preallocatedCharacters;
this.pwSets = Collections.unmodifiableList(pwSets);
if (minLength < presetCharacterCount) {
throw new IllegalArgumentException("Combined minimum lengths "
+ presetCharacterCount
+ " are greater than the minLength of " + minLength);
}
// Copy all characters into single array so we can evenly access all members when accessing this array
char[] allChars = new char[pwCharacters];
int currentIndex = 0;
for(PasswordCharacterSet pwSet : pwSets) {
char[] chars = pwSet.getCharacters();
System.arraycopy(chars, 0, allChars, currentIndex, chars.length);
currentIndex += chars.length;
}
this.allCharacters = allChars;
}
public char[] generatePassword() {
SecureRandom rand = new SecureRandom();
// Set pw length to minLength <= pwLength <= maxLength
int pwLength = minLength + rand.nextInt(maxLength - minLength + 1);
int randomCharacterCount = pwLength - presetCharacterCount;
// Place each index in an array then remove them randomly to assign positions in the pw array
List<Integer> remainingIndexes = new ArrayList<Integer>(pwLength);
for(int i=0; i < pwLength; ++i) {
remainingIndexes.add(i);
}
// Fill pw array
char[] pw = new char[pwLength];
for(PasswordCharacterSet pwSet : pwSets) {
addRandomCharacters(pw, pwSet.getCharacters(), pwSet.getMinCharacters(), remainingIndexes, rand);
}
addRandomCharacters(pw, allCharacters, randomCharacterCount, remainingIndexes, rand);
return pw;
}
private static void addRandomCharacters(char[] pw, char[] characterSet,
int numCharacters, List<Integer> remainingIndexes, Random rand) {
for(int i=0; i < numCharacters; ++i) {
// Get and remove random index from the remaining indexes
int pwIndex = remainingIndexes.remove(rand.nextInt(remainingIndexes.size()));
// Set random character from character index to pwIndex
int randCharIndex = rand.nextInt(characterSet.length);
pw[pwIndex] = characterSet[randCharIndex];
}
}
public static interface PasswordCharacterSet {
char[] getCharacters();
int getMinCharacters();
}
/**
* Defensive copy of a passed-in PasswordCharacterSet
*/
private static final class PwSet implements PasswordCharacterSet {
private final char[] chars;
private final int minChars;
public PwSet(PasswordCharacterSet pwSet) {
this.minChars = pwSet.getMinCharacters();
char[] pwSetChars = pwSet.getCharacters();
// Defensive copy
this.chars = Arrays.copyOf(pwSetChars, pwSetChars.length);
}
#Override
public char[] getCharacters() {
return chars;
}
#Override
public int getMinCharacters() {
return minChars;
}
}
}
Here is a utility that uses just vanilla Java and implements the requirements. It basically gets one of each of the required character sets. Then populates the rest with random chars from the whole set. Then shuffles it all up.
public class PasswordUtils {
static char[] SYMBOLS = "^$*.[]{}()?-\"!##%&/\\,><':;|_~`".toCharArray();
static char[] LOWERCASE = "abcdefghijklmnopqrstuvwxyz".toCharArray();
static char[] UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
static char[] NUMBERS = "0123456789".toCharArray();
static char[] ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789^$*.[]{}()?-\"!##%&/\\,><':;|_~`".toCharArray();
static Random rand = new SecureRandom();
public static String getPassword(int length) {
assert length >= 4;
char[] password = new char[length];
//get the requirements out of the way
password[0] = LOWERCASE[rand.nextInt(LOWERCASE.length)];
password[1] = UPPERCASE[rand.nextInt(UPPERCASE.length)];
password[2] = NUMBERS[rand.nextInt(NUMBERS.length)];
password[3] = SYMBOLS[rand.nextInt(SYMBOLS.length)];
//populate rest of the password with random chars
for (int i = 4; i < length; i++) {
password[i] = ALL_CHARS[rand.nextInt(ALL_CHARS.length)];
}
//shuffle it up
for (int i = 0; i < password.length; i++) {
int randomPosition = rand.nextInt(password.length);
char temp = password[i];
password[i] = password[randomPosition];
password[randomPosition] = temp;
}
return new String(password);
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(getPassword(8));
}
}
}
Using the random functionality of java.util package of rt.jar, we can create a random password of any length. below is the snippet for the same.
public class GeneratePassword {
public static void main(String[] args)
{
int length = 10;
String symbol = "-/.^&*_!#%=+>)";
String cap_letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String small_letter = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String finalString = cap_letter + small_letter +
numbers + symbol;
Random random = new Random();
char[] password = new char[length];
for (int i = 0; i < length; i++)
{
password[i] =
finalString.charAt(random.nextInt(finalString.length()));
}
System.out.println(password);
}
}
I know it is an old question, but maybe my solution will help someone with the same problem.
I'm using RandomStringUtils for password generator and then I check did password fulfilled conditions (at least one symbol, one capital letter, one small letter and one number and 8 characters long) with regex and if it didn't then I call again password generator with recursion until condition is not fulfilled. I can say that method is not gonna be called more than 3 times for sure!
public String generatePassword() {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789#!#$%&";
String password = RandomStringUtils.random( 8, characters );
String regex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[#!#$%&])(?=\\S+$).{8,}$";
Pattern pattern = Pattern.compile( regex );
Matcher matcher = pattern.matcher( password );
if (matcher.matches()) {
return password;
} else {
return generatePassword(); // recursion
}
}
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
public static final Character[] ALPHA_UPPER_CHARACTERS = {'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
public static final Character[] ALPHA_LOWER_CHARACTERS = {'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
public static final Character[] NUMERIC_CHARACTERS = {'0', '1', '2', '3', '4',
'5', '6', '7', '8', '9'};
public static final Character[] SPECIAL_CHARACTERS = {'#', '#',
'$', '%', '^', '&', '*', '|', ';', ':', '?'};
**Note: I copied char set from #summer**
final List<Character[]> charSets = new ArrayList<>();
charSets.add(Constant.ALPHA_UPPER_CHARACTERS);
charSets.add(Constant.ALPHA_LOWER_CHARACTERS);
charSets.add(Constant.NUMERIC_CHARACTERS);
charSets.add(Constant.SPECIAL_CHARACTERS);
public String getFilterPassword() {
StringBuilder passBuilder = new StringBuilder();
final int charSetLen = charSets.size();
for (int i = 0; i < 10; i++) {
int randomLength = new Random().nextInt(charSetLen - 1);
Character[] newAlpha = charSets.get(randomLength);
int randomSetLen = newAlpha.length;
int randomAlphaLen = new Random().nextInt(randomSetLen - 1);
passBuilder.append(newAlpha[randomAlphaLen]);
}
return passBuilder.toString();
}