forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSHA1.java
73 lines (60 loc) · 2.66 KB
/
SHA1.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.thealgorithms.hashes;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
/**
* The SHA1 class provides a method to generate the SHA-1 hash for a given string.
* SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function that produces
* a 160-bit (20-byte) hash value. It is commonly used for data integrity verification,
* although it is no longer considered secure for cryptographic purposes.
*
* @see <a href="https://en.wikipedia.org/wiki/SHA-1">SHA-1 on Wikipedia</a>
*/
public class SHA1 {
/**
* Generates the SHA-1 hash of the input string.
*
* @param input the string to be hashed
* @return the SHA-1 hash as a hexadecimal string
*/
public static String getSha1(String input) {
try {
// Create a MessageDigest instance for SHA-1
MessageDigest md = MessageDigest.getInstance("SHA-1");
// Compute the SHA-1 digest of the input string
byte[] messageDigest = md.digest(input.getBytes());
// Convert the byte array into a BigInteger to get the hash in hexadecimal format
BigInteger no = new BigInteger(1, messageDigest);
// Convert the BigInteger to a hexadecimal string
String hashtext = no.toString(16);
// Pad with leading zeros to ensure the hash is 32 characters long
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
// Return the generated SHA-1 hash
return hashtext;
} catch (NoSuchAlgorithmException e) {
// Handle the case where SHA-1 algorithm is not available
throw new RuntimeException(e);
}
}
/**
* The main method that takes user input, computes its SHA-1 hash, and prints the result.
*
* @param args command-line arguments
* @throws NoSuchAlgorithmException if the SHA-1 algorithm is not available
*/
public static void main(String args[]) throws NoSuchAlgorithmException {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a string to hash
System.out.print("Enter the string to hash: ");
// Read the input string from the user
String s = scanner.nextLine();
// Compute the SHA-1 hash of the input string and print it
System.out.println("Your HashCode Generated by SHA-1 is: " + getSha1(s));
// Close the Scanner object
scanner.close();
}
}