package com.mbridge.msdk.thrid.okio; import com.mbridge.msdk.foundation.tools.SameMD5; import com.unity3d.ads.core.data.datasource.AndroidStaticDeviceInfoDataSource; 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: classes4.dex */ public final class HashingSource extends ForwardingSource { private final Mac mac; private final MessageDigest messageDigest; public static HashingSource md5(Source source) { return new HashingSource(source, SameMD5.TAG); } public static HashingSource sha1(Source source) { return new HashingSource(source, AndroidStaticDeviceInfoDataSource.ALGORITHM_SHA1); } public static HashingSource sha256(Source source) { return new HashingSource(source, "SHA-256"); } 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"); } private HashingSource(Source source, String str) { super(source); try { this.messageDigest = MessageDigest.getInstance(str); this.mac = null; } catch (NoSuchAlgorithmException unused) { throw new AssertionError(); } } private HashingSource(Source source, ByteString byteString, String str) { super(source); try { Mac mac = Mac.getInstance(str); this.mac = mac; mac.init(new SecretKeySpec(byteString.toByteArray(), str)); this.messageDigest = null; } catch (InvalidKeyException e) { throw new IllegalArgumentException(e); } catch (NoSuchAlgorithmException unused) { throw new AssertionError(); } } @Override // com.mbridge.msdk.thrid.okio.ForwardingSource, com.mbridge.msdk.thrid.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; } public final ByteString hash() { MessageDigest messageDigest = this.messageDigest; return ByteString.of(messageDigest != null ? messageDigest.digest() : this.mac.doFinal()); } }