| 35 | |
| 36 | |
| 37 | public class Digest implements Utf8Sink { |
| 38 | public enum DigestAlgorithm { |
| 39 | MD5, |
| 40 | SHA1, |
| 41 | SHA256, |
| 42 | } |
| 43 | |
| 44 | private final MessageDigest digest; |
| 45 | private final byte[] buffer; |
| 46 | |
| 47 | public Digest(@NotNull DigestAlgorithm algorithm) { |
| 48 | String algo = switch (algorithm) { |
| 49 | case MD5 -> "MD5"; |
| 50 | case SHA1 -> "SHA-1"; |
| 51 | default -> "SHA-256"; |
| 52 | }; |
| 53 | try { |
| 54 | this.digest = MessageDigest.getInstance(algo); |
| 55 | } catch (NoSuchAlgorithmException e) { |
| 56 | /* |
| 57 | * Every implementation of the Java platform is required to support the |
| 58 | * following standard MessageDigest algorithms: |
| 59 | * - MD5 |
| 60 | * - SHA-1 |
| 61 | * - SHA-256 |
| 62 | */ |
| 63 | throw new RuntimeException("unreachable"); |
| 64 | } |
| 65 | this.buffer = new byte[digest.getDigestLength()]; |
| 66 | } |
| 67 | |
| 68 | @Override |
| 69 | public Utf8Sink put(@Nullable Utf8Sequence us) { |
| 70 | if (us != null) { |
| 71 | for (int i = 0, n = us.size(); i < n; i++) { |
| 72 | this.digest.update(us.byteAt(i)); |
| 73 | } |
| 74 | } |
| 75 | return this; |
| 76 | } |
| 77 | |
| 78 | @Override |
| 79 | public Utf8Sink put(byte b) { |
| 80 | this.digest.update(b); |
| 81 | return this; |
| 82 | } |
| 83 | |
| 84 | @Override |
| 85 | public Utf8Sink putNonAscii(long lo, long hi) { |
| 86 | for (long p = lo; p < hi; p++) { |
| 87 | this.digest.update(Unsafe.getByte(p)); |
| 88 | } |
| 89 | return this; |
| 90 | } |
| 91 | |
| 92 | public void hash(@NotNull BinarySequence sequence, @NotNull CharSink<?> sink) { |
| 93 | for (int i = 0; i < sequence.length(); i++) { |
| 94 | this.digest.update(sequence.byteAt(i)); |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…