[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.cipher;
|
||||
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class EncryptorUnitTest {
|
||||
private String encKeyString;
|
||||
private String message;
|
||||
private String certificateString;
|
||||
private Encryptor encryptor;
|
||||
|
||||
@Before
|
||||
public void init(){
|
||||
encKeyString = "1234567890123456";
|
||||
message = "This is a secret message";
|
||||
encryptor = new Encryptor();
|
||||
certificateString = "-----BEGIN CERTIFICATE-----\n" +
|
||||
"MIICVjCCAb8CAg37MA0GCSqGSIb3DQEBBQUAMIGbMQswCQYDVQQGEwJKUDEOMAwG\n" +
|
||||
"A1UECBMFVG9reW8xEDAOBgNVBAcTB0NodW8ta3UxETAPBgNVBAoTCEZyYW5rNERE\n" +
|
||||
"MRgwFgYDVQQLEw9XZWJDZXJ0IFN1cHBvcnQxGDAWBgNVBAMTD0ZyYW5rNEREIFdl\n" +
|
||||
"YiBDQTEjMCEGCSqGSIb3DQEJARYUc3VwcG9ydEBmcmFuazRkZC5jb20wHhcNMTIw\n" +
|
||||
"ODIyMDUyNzIzWhcNMTcwODIxMDUyNzIzWjBKMQswCQYDVQQGEwJKUDEOMAwGA1UE\n" +
|
||||
"CAwFVG9reW8xETAPBgNVBAoMCEZyYW5rNEREMRgwFgYDVQQDDA93d3cuZXhhbXBs\n" +
|
||||
"ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMYBBrx5PlP0WNI/ZdzD\n" +
|
||||
"+6Pktmurn+F2kQYbtc7XQh8/LTBvCo+P6iZoLEmUA9e7EXLRxgU1CVqeAi7QcAn9\n" +
|
||||
"MwBlc8ksFJHB0rtf9pmf8Oza9E0Bynlq/4/Kb1x+d+AyhL7oK9tQwB24uHOueHi1\n" +
|
||||
"C/iVv8CSWKiYe6hzN1txYe8rAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAASPdjigJ\n" +
|
||||
"kXCqKWpnZ/Oc75EUcMi6HztaW8abUMlYXPIgkV2F7YanHOB7K4f7OOLjiz8DTPFf\n" +
|
||||
"jC9UeuErhaA/zzWi8ewMTFZW/WshOrm3fNvcMrMLKtH534JKvcdMg6qIdjTFINIr\n" +
|
||||
"evnAhf0cwULaebn+lMs8Pdl7y37+sfluVok=\n" +
|
||||
"-----END CERTIFICATE-----";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEncryptionKey_whenMessageIsPassedToEncryptor_thenMessageIsEncrypted() throws Exception {
|
||||
byte[] encryptedMessage = encryptor.encryptMessage(message.getBytes(),encKeyString.getBytes());
|
||||
|
||||
assertThat(encryptedMessage).isNotNull();
|
||||
assertThat(encryptedMessage.length % 32).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCertificateWithPublicKey_whenMessageIsPassedToEncryptor_thenMessageIsEncrypted() throws Exception {
|
||||
CertificateFactory factory = CertificateFactory.getInstance("X.509");
|
||||
InputStream is = new ByteArrayInputStream(certificateString.getBytes());
|
||||
X509Certificate certificate = (X509Certificate) factory.generateCertificate(is);
|
||||
|
||||
byte[] encryptedMessage = encryptor.encryptMessage(message.getBytes(),certificate);
|
||||
|
||||
assertThat(encryptedMessage).isNotNull();
|
||||
assertThat(encryptedMessage.length % 128).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEncryptionKey_whenMessageIsEncrypted_thenDecryptMessage() throws Exception{
|
||||
byte[] encryptedMessageBytes = encryptor.encryptMessage(message.getBytes(),encKeyString.getBytes());
|
||||
|
||||
byte[] clearMessageBytes = encryptor.decryptMessage(encryptedMessageBytes, encKeyString.getBytes());
|
||||
|
||||
assertThat(message).isEqualTo(new String(clearMessageBytes));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.encrypt;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.SecretKey;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class FileEncrypterDecrypterIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenStringAndFilename_whenEncryptingIntoFile_andDecryptingFileAgain_thenOriginalStringIsReturned() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException {
|
||||
String originalContent = "foobar";
|
||||
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
|
||||
|
||||
FileEncrypterDecrypter fileEncrypterDecrypter = new FileEncrypterDecrypter(secretKey, "AES/CBC/PKCS5Padding");
|
||||
fileEncrypterDecrypter.encrypt(originalContent, "baz.enc");
|
||||
|
||||
String decryptedContent = fileEncrypterDecrypter.decrypt("baz.enc");
|
||||
assertThat(decryptedContent, is(originalContent));
|
||||
|
||||
new File("baz.enc").delete(); // cleanup
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.hashing;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Keccak256HashingUnitTest {
|
||||
|
||||
private static String originalValue = "abc123";
|
||||
private static String hashedValue = "719accc61a9cc126830e5906f9d672d06eab6f8597287095a2c55a8b775e7016";
|
||||
|
||||
@Test public void testHashWithJavaMessageDigest() throws Exception {
|
||||
final String currentHashedValue = Keccak256Hashing.hashWithJavaMessageDigest(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test public void testHashWithBouncyCastle() {
|
||||
final String currentHashedValue = Keccak256Hashing.hashWithBouncyCastle(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.hashing;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SHA256HashingUnitTest {
|
||||
|
||||
private static String originalValue = "abc123";
|
||||
private static String hashedValue = "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090";
|
||||
|
||||
@Test
|
||||
public void testHashWithJavaMessageDigest() throws Exception {
|
||||
final String currentHashedValue = SHA256Hashing.HashWithJavaMessageDigest(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithGuava() throws Exception {
|
||||
final String currentHashedValue = SHA256Hashing.hashWithGuava(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithApacheCommans() throws Exception {
|
||||
final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithBouncyCastle() throws Exception {
|
||||
final String currentHashedValue = SHA256Hashing.HashWithBouncyCastle(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.hashing;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SHA3HashingUnitTest {
|
||||
|
||||
private static String originalValue = "abc123";
|
||||
private static String hashedValue = "f58fa3df820114f56e1544354379820cff464c9c41cb3ca0ad0b0843c9bb67ee";
|
||||
|
||||
/* works with JDK9+ only */
|
||||
//@Test
|
||||
public void testHashWithJavaMessageDigestJDK9() throws Exception {
|
||||
final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigestJDK9(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithJavaMessageDigest() throws Exception {
|
||||
final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigest(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
/* works with JDK9+ only */
|
||||
//@Test
|
||||
public void testHashWithApacheCommonsJDK9() {
|
||||
final String currentHashedValue = SHA3Hashing.hashWithApacheCommonsJDK9(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashWithBouncyCastle() {
|
||||
final String currentHashedValue = SHA3Hashing.hashWithBouncyCastle(originalValue);
|
||||
assertEquals(hashedValue, currentHashedValue);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package com.baeldung.keystore;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import sun.security.x509.AlgorithmId;
|
||||
import sun.security.x509.CertificateAlgorithmId;
|
||||
import sun.security.x509.CertificateSerialNumber;
|
||||
import sun.security.x509.CertificateValidity;
|
||||
import sun.security.x509.CertificateVersion;
|
||||
import sun.security.x509.CertificateX509Key;
|
||||
import sun.security.x509.SubjectAlternativeNameExtension;
|
||||
import sun.security.x509.X500Name;
|
||||
import sun.security.x509.X509CertImpl;
|
||||
import sun.security.x509.X509CertInfo;
|
||||
import sun.security.x509.CertificateExtensions;
|
||||
import sun.security.x509.GeneralNames;
|
||||
import sun.security.x509.GeneralName;
|
||||
import sun.security.x509.GeneralNameInterface;
|
||||
import sun.security.x509.DNSName;
|
||||
import sun.security.x509.IPAddressName;
|
||||
import sun.security.util.DerOutputStream;
|
||||
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.KeyStore;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.SignatureException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Created by adi on 4/14/18.
|
||||
*/
|
||||
public class JavaKeyStoreUnitTest {
|
||||
|
||||
private JavaKeyStore keyStore;
|
||||
|
||||
private static final String KEYSTORE_PWD = "abc123";
|
||||
private static final String KEYSTORE_NAME = "myKeyStore";
|
||||
private static final String KEY_STORE_TYPE = "JCEKS";
|
||||
|
||||
private static final String MY_SECRET_ENTRY = "mySecretEntry";
|
||||
private static final String DN_NAME = "CN=test, OU=test, O=test, L=test, ST=test, C=CY";
|
||||
private static final String SHA1WITHRSA = "SHA1withRSA";
|
||||
private static final String MY_PRIVATE_KEY = "myPrivateKey";
|
||||
private static final String MY_CERTIFICATE = "myCertificate";
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
//using java cryptography extension keyStore instead of Keystore.getDefaultType
|
||||
keyStore = new JavaKeyStore(KEY_STORE_TYPE, KEYSTORE_PWD, KEYSTORE_NAME);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
if (keyStore.getKeyStore() != null) {
|
||||
keyStore.deleteKeyStore();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNoKeyStore_whenCreateEmptyKeyStore_thenGetKeyStoreNotNull() throws Exception {
|
||||
keyStore.createEmptyKeyStore();
|
||||
KeyStore result = keyStore.getKeyStore();
|
||||
Assert.assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyKeystore_whenLoadKeyStore_thenKeyStoreLoadedAndSizeZero() throws Exception {
|
||||
keyStore.createEmptyKeyStore();
|
||||
keyStore.loadKeyStore();
|
||||
KeyStore result = keyStore.getKeyStore();
|
||||
Assert.assertNotNull(result);
|
||||
Assert.assertTrue(result.size() == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadedKeyStore_whenSetEntry_thenSizeIsOneAndGetKeyNotNull() throws Exception {
|
||||
keyStore.createEmptyKeyStore();
|
||||
keyStore.loadKeyStore();
|
||||
|
||||
KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256");
|
||||
SecretKey secretKey = keygen.generateKey();
|
||||
//ideally, password should be different for every key
|
||||
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray());
|
||||
KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
|
||||
keyStore.setEntry(MY_SECRET_ENTRY, secretKeyEntry, protParam);
|
||||
|
||||
KeyStore result = keyStore.getKeyStore();
|
||||
Assert.assertTrue(result.size() == 1);
|
||||
KeyStore.Entry entry = keyStore.getEntry(MY_SECRET_ENTRY);
|
||||
Assert.assertTrue(entry != null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadedKeyStore_whenSetKeyEntry_thenSizeIsOneAndGetEntryNotNull() throws Exception {
|
||||
keyStore.createEmptyKeyStore();
|
||||
keyStore.loadKeyStore();
|
||||
|
||||
// Generate the key pair
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyPairGenerator.initialize(1024);
|
||||
KeyPair keyPair = keyPairGenerator.generateKeyPair();
|
||||
|
||||
// Generate a self signed certificate
|
||||
X509Certificate certificate = generateSelfSignedCertificate(keyPair);
|
||||
|
||||
X509Certificate[] certificateChain = new X509Certificate[1];
|
||||
certificateChain[0] = certificate;
|
||||
keyStore.setKeyEntry(MY_PRIVATE_KEY, keyPair.getPrivate(), KEYSTORE_PWD, certificateChain);
|
||||
|
||||
KeyStore result = keyStore.getKeyStore();
|
||||
Assert.assertTrue(result.size() == 1);
|
||||
KeyStore.Entry entry = keyStore.getEntry(MY_PRIVATE_KEY);
|
||||
Assert.assertTrue(entry != null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadedKeyStore_whenSetCertificateEntry_thenSizeIsOneAndGetCertificateEntryNotNull() throws Exception {
|
||||
keyStore.createEmptyKeyStore();
|
||||
keyStore.loadKeyStore();
|
||||
|
||||
// Generate the key pair
|
||||
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
|
||||
keyPairGenerator.initialize(1024);
|
||||
KeyPair keyPair = keyPairGenerator.generateKeyPair();
|
||||
|
||||
// Generate a self signed certificate
|
||||
X509Certificate certificate = generateSelfSignedCertificate(keyPair);
|
||||
|
||||
keyStore.setCertificateEntry(MY_CERTIFICATE, certificate);
|
||||
|
||||
KeyStore result = this.keyStore.getKeyStore();
|
||||
Assert.assertTrue(result.size() == 1);
|
||||
java.security.cert.Certificate resultCertificate = keyStore.getCertificate(MY_CERTIFICATE);
|
||||
Assert.assertNotNull(resultCertificate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadedKeyStoreWithOneEntry_whenDeleteEntry_thenKeyStoreSizeIsZero() throws Exception {
|
||||
keyStore.createEmptyKeyStore();
|
||||
keyStore.loadKeyStore();
|
||||
|
||||
KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256");
|
||||
SecretKey secretKey = keygen.generateKey();
|
||||
//ideally, password should be different for every key
|
||||
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray());
|
||||
KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
|
||||
keyStore.setEntry(MY_SECRET_ENTRY, secretKeyEntry, protParam);
|
||||
|
||||
keyStore.deleteEntry(MY_SECRET_ENTRY);
|
||||
|
||||
KeyStore result = this.keyStore.getKeyStore();
|
||||
Assert.assertTrue(result.size() == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoadedKeystore_whenDeleteKeyStore_thenKeyStoreIsNull() throws Exception {
|
||||
keyStore.createEmptyKeyStore();
|
||||
keyStore.loadKeyStore();
|
||||
|
||||
keyStore.deleteKeyStore();
|
||||
|
||||
KeyStore result = this.keyStore.getKeyStore();
|
||||
Assert.assertTrue(result == null);
|
||||
}
|
||||
|
||||
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws CertificateException, IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
|
||||
X509CertInfo certInfo = new X509CertInfo();
|
||||
// Serial number and version
|
||||
certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, new SecureRandom())));
|
||||
certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
|
||||
|
||||
// Subject & Issuer
|
||||
X500Name owner = new X500Name(DN_NAME);
|
||||
certInfo.set(X509CertInfo.SUBJECT, owner);
|
||||
certInfo.set(X509CertInfo.ISSUER, owner);
|
||||
|
||||
// Key and algorithm
|
||||
certInfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
|
||||
AlgorithmId algorithm = new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid);
|
||||
certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algorithm));
|
||||
|
||||
// Validity
|
||||
Date validFrom = new Date();
|
||||
Date validTo = new Date(validFrom.getTime() + 50L * 365L * 24L * 60L * 60L * 1000L); //50 years
|
||||
CertificateValidity validity = new CertificateValidity(validFrom, validTo);
|
||||
certInfo.set(X509CertInfo.VALIDITY, validity);
|
||||
|
||||
GeneralNameInterface dnsName = new DNSName("baeldung.com");
|
||||
DerOutputStream dnsNameOutputStream = new DerOutputStream();
|
||||
dnsName.encode(dnsNameOutputStream);
|
||||
|
||||
GeneralNameInterface ipAddress = new IPAddressName("127.0.0.1");
|
||||
DerOutputStream ipAddressOutputStream = new DerOutputStream();
|
||||
ipAddress.encode(ipAddressOutputStream);
|
||||
|
||||
GeneralNames generalNames = new GeneralNames();
|
||||
generalNames.add(new GeneralName(dnsName));
|
||||
generalNames.add(new GeneralName(ipAddress));
|
||||
|
||||
CertificateExtensions ext = new CertificateExtensions();
|
||||
ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(generalNames));
|
||||
|
||||
certInfo.set(X509CertInfo.EXTENSIONS, ext);
|
||||
|
||||
// Create certificate and sign it
|
||||
X509CertImpl cert = new X509CertImpl(certInfo);
|
||||
cert.sign(keyPair.getPrivate(), SHA1WITHRSA);
|
||||
|
||||
// Since the SHA1withRSA provider may have a different algorithm ID to what we think it should be,
|
||||
// we need to reset the algorithm ID, and resign the certificate
|
||||
AlgorithmId actualAlgorithm = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
|
||||
certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, actualAlgorithm);
|
||||
X509CertImpl newCert = new X509CertImpl(certInfo);
|
||||
newCert.sign(keyPair.getPrivate(), SHA1WITHRSA);
|
||||
|
||||
return newCert;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.passwordhashing;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
|
||||
public class PBKDF2HasherUnitTest {
|
||||
|
||||
private PBKDF2Hasher mPBKDF2Hasher;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
mPBKDF2Hasher = new PBKDF2Hasher();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception {
|
||||
String message1 = "password123";
|
||||
|
||||
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
|
||||
|
||||
assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception {
|
||||
String message1 = "password123";
|
||||
|
||||
String hash1 = mPBKDF2Hasher.hash(message1.toCharArray());
|
||||
|
||||
String wrongPasswordAttempt = "IamWrong";
|
||||
|
||||
assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.passwordhashing;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* Created by PhysicsSam on 06-Sep-18.
|
||||
*/
|
||||
public class SHA512HasherUnitTest {
|
||||
|
||||
private SHA512Hasher hasher;
|
||||
private SecureRandom secureRandom;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
hasher = new SHA512Hasher();
|
||||
secureRandom = new SecureRandom();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception {
|
||||
|
||||
byte[] salt = new byte[16];
|
||||
secureRandom.nextBytes(salt);
|
||||
|
||||
String hash1 = hasher.hash("password", salt);
|
||||
String hash2 = hasher.hash("password", salt);
|
||||
|
||||
assertEquals(hash1, hash2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception {
|
||||
|
||||
byte[] salt = new byte[16];
|
||||
secureRandom.nextBytes(salt);
|
||||
String hash1 = hasher.hash("password", salt);
|
||||
//generate a second salt
|
||||
byte[] secondSalt = new byte[16];
|
||||
String hash2 = hasher.hash("password", secondSalt);
|
||||
|
||||
assertNotEquals(hash1, hash2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception {
|
||||
byte[] salt = new byte[16];
|
||||
secureRandom.nextBytes(salt);
|
||||
|
||||
String originalHash = hasher.hash("password123", salt);
|
||||
|
||||
assertTrue(hasher.checkPassword(originalHash, "password123", salt));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception {
|
||||
byte[] salt = new byte[16];
|
||||
secureRandom.nextBytes(salt);
|
||||
|
||||
String originalHash = hasher.hash("password123", salt);
|
||||
|
||||
assertFalse(hasher.checkPassword(originalHash, "password124", salt));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package org.baeldung.java.md5;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.hash.HashCode;
|
||||
import com.google.common.hash.Hashing;
|
||||
|
||||
public class JavaMD5UnitTest {
|
||||
|
||||
String filename = "src/test/resources/test_md5.txt";
|
||||
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
||||
|
||||
String hash = "35454B055CC325EA1AF2126E27707052";
|
||||
String password = "ILoveJava";
|
||||
|
||||
@Test
|
||||
public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException {
|
||||
String hash = "35454B055CC325EA1AF2126E27707052";
|
||||
String password = "ILoveJava";
|
||||
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
md.update(password.getBytes());
|
||||
byte[] digest = md.digest();
|
||||
String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase();
|
||||
|
||||
assertThat(myHash.equals(hash)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException {
|
||||
String filename = "src/test/resources/test_md5.txt";
|
||||
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
||||
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
md.update(Files.readAllBytes(Paths.get(filename)));
|
||||
byte[] digest = md.digest();
|
||||
String myChecksum = DatatypeConverter.printHexBinary(digest).toUpperCase();
|
||||
|
||||
assertThat(myChecksum.equals(checksum)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPassword_whenHashingUsingCommons_thenVerifying() {
|
||||
String hash = "35454B055CC325EA1AF2126E27707052";
|
||||
String password = "ILoveJava";
|
||||
|
||||
String md5Hex = DigestUtils.md5Hex(password).toUpperCase();
|
||||
|
||||
assertThat(md5Hex.equals(hash)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException {
|
||||
String filename = "src/test/resources/test_md5.txt";
|
||||
String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3";
|
||||
|
||||
HashCode hash = com.google.common.io.Files.hash(new File(filename), Hashing.md5());
|
||||
String myChecksum = hash.toString().toUpperCase();
|
||||
|
||||
assertThat(myChecksum.equals(checksum)).isTrue();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
hello world
|
||||
Reference in New Issue
Block a user