90 lines
3.0 KiB
Java
90 lines
3.0 KiB
Java
package okio;
|
|
|
|
import java.io.IOException;
|
|
import java.security.InvalidKeyException;
|
|
import java.security.MessageDigest;
|
|
import java.security.NoSuchAlgorithmException;
|
|
import javax.crypto.Mac;
|
|
import javax.crypto.spec.SecretKeySpec;
|
|
|
|
/* loaded from: classes2.dex */
|
|
public final class HashingSource extends ForwardingSource {
|
|
private final Mac mac;
|
|
private final MessageDigest messageDigest;
|
|
|
|
private HashingSource(Source source, String str) {
|
|
super(source);
|
|
try {
|
|
this.messageDigest = MessageDigest.getInstance(str);
|
|
this.mac = null;
|
|
} catch (NoSuchAlgorithmException unused) {
|
|
throw new AssertionError();
|
|
}
|
|
}
|
|
|
|
public static HashingSource hmacSha1(Source source, ByteString byteString) {
|
|
return new HashingSource(source, byteString, "HmacSHA1");
|
|
}
|
|
|
|
public static HashingSource hmacSha256(Source source, ByteString byteString) {
|
|
return new HashingSource(source, byteString, "HmacSHA256");
|
|
}
|
|
|
|
public static HashingSource md5(Source source) {
|
|
return new HashingSource(source, "MD5");
|
|
}
|
|
|
|
public static HashingSource sha1(Source source) {
|
|
return new HashingSource(source, "SHA-1");
|
|
}
|
|
|
|
public static HashingSource sha256(Source source) {
|
|
return new HashingSource(source, "SHA-256");
|
|
}
|
|
|
|
public ByteString hash() {
|
|
MessageDigest messageDigest = this.messageDigest;
|
|
return ByteString.of(messageDigest != null ? messageDigest.digest() : this.mac.doFinal());
|
|
}
|
|
|
|
@Override // okio.ForwardingSource, okio.Source
|
|
public long read(Buffer buffer, long j) throws IOException {
|
|
long read = super.read(buffer, j);
|
|
if (read != -1) {
|
|
long j2 = buffer.size;
|
|
long j3 = j2 - read;
|
|
Segment segment = buffer.head;
|
|
while (j2 > j3) {
|
|
segment = segment.prev;
|
|
j2 -= segment.limit - segment.pos;
|
|
}
|
|
while (j2 < buffer.size) {
|
|
int i = (int) ((segment.pos + j3) - j2);
|
|
MessageDigest messageDigest = this.messageDigest;
|
|
if (messageDigest != null) {
|
|
messageDigest.update(segment.data, i, segment.limit - i);
|
|
} else {
|
|
this.mac.update(segment.data, i, segment.limit - i);
|
|
}
|
|
j3 = (segment.limit - segment.pos) + j2;
|
|
segment = segment.next;
|
|
j2 = j3;
|
|
}
|
|
}
|
|
return read;
|
|
}
|
|
|
|
private HashingSource(Source source, ByteString byteString, String str) {
|
|
super(source);
|
|
try {
|
|
this.mac = Mac.getInstance(str);
|
|
this.mac.init(new SecretKeySpec(byteString.toByteArray(), str));
|
|
this.messageDigest = null;
|
|
} catch (InvalidKeyException e) {
|
|
throw new IllegalArgumentException(e);
|
|
} catch (NoSuchAlgorithmException unused) {
|
|
throw new AssertionError();
|
|
}
|
|
}
|
|
}
|