Files
mtusi2026lab4/src/main/java/ru/mtusi/messenger/util/TokenHasher.java
T
2026-10-22 20:59:59 +03:00

37 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();
}
}