package org.bouncycastle.jce.provider;

import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.DerivationFunction;
import org.bouncycastle.crypto.DerivationParameters;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.OutputLengthException;
import org.bouncycastle.crypto.params.KDFParameters;

/* JADX INFO: loaded from: classes2.dex */
public class BrokenKDF2BytesGenerator implements DerivationFunction {
    private Digest digest;
    private byte[] iv;
    private byte[] shared;

    public BrokenKDF2BytesGenerator(Digest digest) {
        this.digest = digest;
    }

    @Override // org.bouncycastle.crypto.DerivationFunction
    public int generateBytes(byte[] bArr, int i, int i2) throws DataLengthException, IllegalArgumentException {
        if (bArr.length - i2 < i) {
            throw new OutputLengthException("output buffer too small");
        }
        long j = ((long) i2) * 8;
        if (j > ((long) this.digest.getDigestSize()) * 8 * 2147483648L) {
            throw new IllegalArgumentException("Output length too large");
        }
        int digestSize = (int) (j / ((long) this.digest.getDigestSize()));
        int digestSize2 = this.digest.getDigestSize();
        byte[] bArr2 = new byte[digestSize2];
        int i3 = 1;
        while (true) {
            Digest digest = this.digest;
            if (i3 > digestSize) {
                digest.reset();
                return i2;
            }
            digest.update(this.shared, 0, this.shared.length);
            this.digest.update((byte) (i3 & 255));
            this.digest.update((byte) ((i3 >> 8) & 255));
            this.digest.update((byte) ((i3 >> 16) & 255));
            this.digest.update((byte) ((i3 >> 24) & 255));
            this.digest.update(this.iv, 0, this.iv.length);
            this.digest.doFinal(bArr2, 0);
            int i4 = i2 - i;
            if (i4 > digestSize2) {
                System.arraycopy(bArr2, 0, bArr, i, digestSize2);
                i += digestSize2;
            } else {
                System.arraycopy(bArr2, 0, bArr, i, i4);
            }
            i3++;
        }
    }

    public Digest getDigest() {
        return this.digest;
    }

    @Override // org.bouncycastle.crypto.DerivationFunction
    public void init(DerivationParameters derivationParameters) {
        if (!(derivationParameters instanceof KDFParameters)) {
            throw new IllegalArgumentException("KDF parameters required for generator");
        }
        KDFParameters kDFParameters = (KDFParameters) derivationParameters;
        this.shared = kDFParameters.getSharedSecret();
        this.iv = kDFParameters.getIV();
    }
}
