Skip to content

Commit 439ba7b

Browse files
Merge branch 'master' into BAEL-2214
2 parents f40d235 + fe3bf74 commit 439ba7b

File tree

36 files changed

+502
-116
lines changed

36 files changed

+502
-116
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/bin/
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.java.src;
2+
3+
import java.util.Scanner;
4+
5+
public class RoundUpToHundred {
6+
7+
public static void main(String[] args) {
8+
Scanner scanner = new Scanner(System.in);
9+
double input = scanner.nextDouble();
10+
scanner.close();
11+
12+
RoundUpToHundred.round(input);
13+
}
14+
15+
static long round(double input) {
16+
long i = (long) Math.ceil(input);
17+
return ((i + 99) / 100) * 100;
18+
};
19+
20+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.java.src;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import org.junit.Test;
6+
7+
public class RoundUpToHundredTest {
8+
@Test
9+
public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
10+
assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
11+
assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
12+
assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
13+
}
14+
}

core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.baeldung.file;
22

33
import org.apache.commons.io.FileUtils;
4+
import org.apache.commons.io.IOUtils;
45
import org.hamcrest.CoreMatchers;
56
import org.hamcrest.Matchers;
67
import org.junit.Test;
@@ -120,4 +121,14 @@ private String readFromInputStream(InputStream inputStream) throws IOException {
120121

121122
return resultStringBuilder.toString();
122123
}
124+
125+
@Test
126+
public void givenFileName_whenUsingIOUtils_thenFileData() throws IOException {
127+
String expectedData = "This is a content of the file";
128+
129+
FileInputStream fis = new FileInputStream("src/test/resources/fileToRead.txt");
130+
String data = IOUtils.toString(fis, "UTF-8");
131+
132+
assertEquals(expectedData, data.trim());
133+
}
123134
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.baeldung.heapdump;
2+
3+
import com.sun.management.HotSpotDiagnosticMXBean;
4+
5+
import javax.management.MBeanServer;
6+
7+
import java.io.IOException;
8+
import java.lang.management.ManagementFactory;
9+
import java.nio.file.Paths;
10+
11+
public class HeapDump {
12+
13+
public static void dumpHeap(String filePath, boolean live) throws IOException {
14+
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
15+
HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(
16+
server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
17+
mxBean.dumpHeap(filePath, live);
18+
}
19+
20+
public static void main(String[] args) throws IOException {
21+
String file = Paths.get("dump.hprof").toFile().getPath();
22+
23+
dumpHeap(file, true);
24+
}
25+
}
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
package com.baeldung.passwordhashing;
2+
3+
import java.security.NoSuchAlgorithmException;
4+
import java.security.SecureRandom;
5+
import java.security.spec.InvalidKeySpecException;
6+
import java.security.spec.KeySpec;
7+
import java.util.Arrays;
8+
import java.util.Base64;
9+
import java.util.regex.Matcher;
10+
import java.util.regex.Pattern;
11+
12+
import javax.crypto.SecretKeyFactory;
13+
import javax.crypto.spec.PBEKeySpec;
14+
15+
/**
16+
* Hash passwords for storage, and test passwords against password tokens.
17+
*
18+
* Instances of this class can be used concurrently by multiple threads.
19+
*
20+
* @author erickson
21+
* @see <a href="http://stackoverflow.com/a/2861125/3474">StackOverflow</a>
22+
*/
23+
public final class PBKDF2Hasher
24+
{
25+
26+
/**
27+
* Each token produced by this class uses this identifier as a prefix.
28+
*/
29+
public static final String ID = "$31$";
30+
31+
/**
32+
* The minimum recommended cost, used by default
33+
*/
34+
public static final int DEFAULT_COST = 16;
35+
36+
private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
37+
38+
private static final int SIZE = 128;
39+
40+
private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})");
41+
42+
private final SecureRandom random;
43+
44+
private final int cost;
45+
46+
public PBKDF2Hasher()
47+
{
48+
this(DEFAULT_COST);
49+
}
50+
51+
/**
52+
* Create a password manager with a specified cost
53+
*
54+
* @param cost the exponential computational cost of hashing a password, 0 to 30
55+
*/
56+
public PBKDF2Hasher(int cost)
57+
{
58+
iterations(cost); /* Validate cost */
59+
this.cost = cost;
60+
this.random = new SecureRandom();
61+
}
62+
63+
private static int iterations(int cost)
64+
{
65+
if ((cost < 0) || (cost > 30))
66+
throw new IllegalArgumentException("cost: " + cost);
67+
return 1 << cost;
68+
}
69+
70+
/**
71+
* Hash a password for storage.
72+
*
73+
* @return a secure authentication token to be stored for later authentication
74+
*/
75+
public String hash(char[] password)
76+
{
77+
byte[] salt = new byte[SIZE / 8];
78+
random.nextBytes(salt);
79+
byte[] dk = pbkdf2(password, salt, 1 << cost);
80+
byte[] hash = new byte[salt.length + dk.length];
81+
System.arraycopy(salt, 0, hash, 0, salt.length);
82+
System.arraycopy(dk, 0, hash, salt.length, dk.length);
83+
Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding();
84+
return ID + cost + '$' + enc.encodeToString(hash);
85+
}
86+
87+
/**
88+
* Authenticate with a password and a stored password token.
89+
*
90+
* @return true if the password and token match
91+
*/
92+
public boolean checkPassword(char[] password, String token)
93+
{
94+
Matcher m = layout.matcher(token);
95+
if (!m.matches())
96+
throw new IllegalArgumentException("Invalid token format");
97+
int iterations = iterations(Integer.parseInt(m.group(1)));
98+
byte[] hash = Base64.getUrlDecoder().decode(m.group(2));
99+
byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8);
100+
byte[] check = pbkdf2(password, salt, iterations);
101+
int zero = 0;
102+
for (int idx = 0; idx < check.length; ++idx)
103+
zero |= hash[salt.length + idx] ^ check[idx];
104+
return zero == 0;
105+
}
106+
107+
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations)
108+
{
109+
KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE);
110+
try {
111+
SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);
112+
return f.generateSecret(spec).getEncoded();
113+
}
114+
catch (NoSuchAlgorithmException ex) {
115+
throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex);
116+
}
117+
catch (InvalidKeySpecException ex) {
118+
throw new IllegalStateException("Invalid SecretKeyFactory", ex);
119+
}
120+
}
121+
122+
/**
123+
* Hash a password in an immutable {@code String}.
124+
*
125+
* <p>Passwords should be stored in a {@code char[]} so that it can be filled
126+
* with zeros after use instead of lingering on the heap and elsewhere.
127+
*
128+
* @deprecated Use {@link #hash(char[])} instead
129+
*/
130+
@Deprecated
131+
public String hash(String password)
132+
{
133+
return hash(password.toCharArray());
134+
}
135+
136+
/**
137+
* Authenticate with a password in an immutable {@code String} and a stored
138+
* password token.
139+
*
140+
* @deprecated Use {@link #checkPassword(char[],String)} instead.
141+
* @see #hash(String)
142+
*/
143+
@Deprecated
144+
public boolean checkPassword(String password, String token)
145+
{
146+
return checkPassword(password.toCharArray(), token);
147+
}
148+
149+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.baeldung.passwordhashing;
2+
3+
import java.nio.charset.StandardCharsets;
4+
import java.security.MessageDigest;
5+
import java.security.NoSuchAlgorithmException;
6+
7+
8+
/** A really simple SHA_512 Encryption example.
9+
*
10+
*/
11+
public class SHA512Hasher {
12+
13+
public String hash(String passwordToHash, byte[] salt){
14+
String generatedPassword = null;
15+
try {
16+
MessageDigest md = MessageDigest.getInstance("SHA-512");
17+
md.update(salt);
18+
byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
19+
StringBuilder sb = new StringBuilder();
20+
for(int i=0; i< bytes.length ;i++){
21+
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
22+
}
23+
generatedPassword = sb.toString();
24+
}
25+
catch (NoSuchAlgorithmException e){
26+
e.printStackTrace();
27+
}
28+
return generatedPassword;
29+
}
30+
31+
public boolean checkPassword(String hash, String attempt, byte[] salt){
32+
String generatedHash = hash(attempt, salt);
33+
return hash.equals(generatedHash);
34+
}
35+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baeldung.passwordhashing;
2+
3+
import javax.crypto.SecretKeyFactory;
4+
import javax.crypto.spec.PBEKeySpec;
5+
import java.security.spec.KeySpec;
6+
7+
/** A really simple SimplePBKDF2 Encryption example.
8+
*
9+
*/
10+
public class SimplePBKDF2Hasher {
11+
12+
public static String hashSimple(String password, byte[] salt) throws Exception{
13+
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
14+
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
15+
byte[] hash = f.generateSecret(spec).getEncoded();
16+
return String.valueOf(hash);
17+
}
18+
}

core-java/src/main/java/com/baeldung/zoneddatetime/OffsetDateTimeExample.java

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
11
package com.baeldung.zoneddatetime;
22

3-
import java.time.LocalDateTime;
43
import java.time.OffsetDateTime;
5-
import java.time.ZoneId;
64
import java.time.ZoneOffset;
75

86
public class OffsetDateTimeExample {
97

10-
public OffsetDateTime getCurrentTimeByZoneOffset(String region) {
11-
LocalDateTime now = LocalDateTime.now();
12-
ZoneId zone = ZoneId.of(region);
13-
ZoneOffset zoneOffSet= zone.getRules().getOffset(now);
8+
public OffsetDateTime getCurrentTimeByZoneOffset(String offset) {
9+
ZoneOffset zoneOffSet= ZoneOffset.of(offset);
1410
OffsetDateTime date = OffsetDateTime.now(zoneOffSet);
1511
return date;
1612
}

core-java/src/main/java/com/baeldung/zoneddatetime/OffsetTimeExample.java

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,12 @@
11
package com.baeldung.zoneddatetime;
22

3-
import java.time.LocalDateTime;
43
import java.time.OffsetTime;
5-
import java.time.ZoneId;
64
import java.time.ZoneOffset;
75

86
public class OffsetTimeExample {
97

10-
public OffsetTime getCurrentTimeByZoneOffset(String region) {
11-
LocalDateTime now = LocalDateTime.now();
12-
ZoneId zone = ZoneId.of(region);
13-
ZoneOffset zoneOffSet = zone.getRules()
14-
.getOffset(now);
8+
public OffsetTime getCurrentTimeByZoneOffset(String offset) {
9+
ZoneOffset zoneOffSet = ZoneOffset.of(offset);
1510
OffsetTime time = OffsetTime.now(zoneOffSet);
1611
return time;
1712
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.passwordhashing;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.*;
7+
8+
9+
public class PBKDF2HasherUnitTest {
10+
11+
private PBKDF2Hasher mPBKDF2Hasher;
12+
13+
@Before
14+
public void setUp() throws Exception {
15+
mPBKDF2Hasher = new PBKDF2Hasher();
16+
}
17+
18+
@Test
19+
public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception {
20+
String message1 = "password123";
21+
22+
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
23+
24+
assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1));
25+
26+
}
27+
28+
@Test
29+
public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception {
30+
String message1 = "password123";
31+
32+
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
33+
34+
String wrongPasswordAttempt = "IamWrong";
35+
36+
assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1));
37+
38+
}
39+
40+
41+
}

0 commit comments

Comments
 (0)