Java Implementation String SHA1 Encryption Method
- 2021-12-12 08:49:38
- OfStack
Directory Java String SHA1 Encryption Import Class Definition Function javaSHA1 Encryption Decryption Encapsulation 1 Method for Encryption Main Function Test
Java String SHA1 Encryption
Import class
import java.security.MessageDigest;
Definition function
private String toUserPwd(final String password) {
try {
if (password == null) {
return null;
}
final MessageDigest messageDigest = MessageDigest.getInstance("SHA");
final byte[] digests = messageDigest.digest(password.getBytes());
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < digests.length; i++) {
int halfbyte = (digests[i] >>> 4) & 0x0F;
for (int j = 0; j <= 1; j++) {
stringBuilder.append(
((0 <= halfbyte) && (halfbyte <= 9))
? (char) ('0' + halfbyte)
: (char) ('a' + (halfbyte - 10)));
halfbyte = digests[i] & 0x0F;
}
}
return stringBuilder.toString();
} catch (final Throwable throwable) {
this.log.error("error converting password", throwable);
return null;
}
}
javaSHA1 Encryption and Decryption
Encapsulate 1 method for encryption
/**
* sha1 Encryption
* @param data
* @return
* @throws NoSuchAlgorithmException
*/
public static String sha1(String data) throws NoSuchAlgorithmException {
// Add salt Safer 1 Some
data += "lyz";
// Information Summarizer Algorithm name
MessageDigest md = MessageDigest.getInstance("SHA1");
// Convert a string into a byte array
byte[] b = data.getBytes();
// Updates our summary with the specified bytes
md.update(b);
// Get the ciphertext (Complete summary calculation)
byte[] b2 = md.digest();
// Gets the calculated length
int len = b2.length;
//16 Binary string
String str = "0123456789abcdef";
// Convert a string to an array of strings
char[] ch = str.toCharArray();
// Create 1 A 40 Bit length byte array
char[] chs = new char[len*2];
// Cycle 20 Times
for(int i=0,k=0;i<len;i++) {
byte b3 = b2[i];// Gets each byte in the byte array after digest calculation
// >>>: Unsigned right shift
// &: Bitwise and
//0xf:0-15 The number of
chs[k++] = ch[b3 >>> 4 & 0xf];
chs[k++] = ch[b3 & 0xf];
}
// Character array to string
return new String(chs);
}
Main function test
public static void main(String[] args) throws NoSuchAlgorithmException {
String data = " Jumping beam adzuki bean tlxd666";
String result = sha1(data);
System.out.println(" After encryption: "+result);
}