forked from mtusi2026/mtusi2026lab5
38 lines
1.0 KiB
Java
38 lines
1.0 KiB
Java
package ru.mtusi.messenger.util;
|
|
|
|
import org.springframework.stereotype.Component;
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.security.MessageDigest;
|
|
import java.security.NoSuchAlgorithmException;
|
|
|
|
@Component("tokenHasher")
|
|
public class TokenHasher {
|
|
|
|
public byte[] sha256(String token) {
|
|
try {
|
|
return MessageDigest.getInstance("SHA-256")
|
|
.digest(token.getBytes(StandardCharsets.UTF_8));
|
|
} catch (NoSuchAlgorithmException e) {
|
|
throw new IllegalStateException("SHA-256 not available", e);
|
|
}
|
|
}
|
|
|
|
public String hash(String token) {
|
|
return toHex(sha256(token));
|
|
}
|
|
|
|
public String hash(byte[] bytes) {
|
|
return toHex(bytes);
|
|
}
|
|
|
|
private String toHex(byte[] bytes) {
|
|
StringBuilder sb = new StringBuilder(bytes.length * 2);
|
|
for (byte b : bytes) {
|
|
sb.append(Character.forDigit((b >> 4) & 0xF, 16));
|
|
sb.append(Character.forDigit(b & 0xF, 16));
|
|
}
|
|
return sb.toString();
|
|
}
|
|
}
|