Created
September 27, 2023 16:07
-
-
Save ExpandingShapes/8c538d43022d146d195db0cbb0c466a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.nio.charset.StandardCharsets; | |
import java.security.MessageDigest; | |
import java.security.NoSuchAlgorithmException; | |
import java.util.Random; | |
public class Main { | |
public static void main(String[] args) { | |
String rawPassword = args[0]; | |
String sault = generateSalt(); | |
String encodedPassword = encode(sault + rawPassword); | |
System.out.println("Sault: " + sault); | |
System.out.println("Encoded password: " + encodedPassword); | |
} | |
private static final String DIGEST_ALGORITHM = "SHA-512"; | |
private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); | |
public static String encode(CharSequence rawPassword) { | |
try { | |
MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM); | |
byte[] bytes = md.digest(rawPassword.toString().getBytes(StandardCharsets.UTF_8)); | |
return bytesToHex(bytes); | |
} catch (NoSuchAlgorithmException e) { | |
throw new RuntimeException("Не удалось получить экземпляр MessageDigest", e); | |
} | |
} | |
public boolean matches(CharSequence rawPassword, String encodedPassword) { | |
return encode(rawPassword).equalsIgnoreCase(encodedPassword); | |
} | |
public static String bytesToHex(byte[] bytes) { | |
char[] hexChars = new char[bytes.length * 2]; | |
for (int j = 0; j < bytes.length; j++) { | |
int v = bytes[j] & 0xFF; | |
hexChars[j * 2] = HEX_ARRAY[v >>> 4]; | |
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; | |
} | |
return new String(hexChars); | |
} | |
public static String generateSalt() { | |
int leftLimit = 97; // letter 'a' | |
int rightLimit = 122; // letter 'z' | |
int targetStringLength = 16; | |
Random random = new Random(); | |
StringBuilder buffer = new StringBuilder(targetStringLength); | |
for (int i = 0; i < targetStringLength; i++) { | |
int randomLimitedInt = leftLimit + (int) | |
(random.nextFloat() * (rightLimit - leftLimit + 1)); | |
buffer.append((char) randomLimitedInt); | |
} | |
return buffer.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment