package com.example.puntobip;

import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import java.io.IOException;
/* loaded from: classes.dex */
public class MifareManager {
    private static final byte[][] KEY_B_SECTOR = {new byte[]{31, -62, 53, -84, 19, 9}, new byte[]{36, 63, 22, 9, 24, -47}, new byte[]{-102, -4, 66, 55, 42, -15}, new byte[]{104, 45, 64, 26, -69, 9}, new byte[]{6, 125, -76, 84, 84, -87}, new byte[]{21, -4, 76, 118, 19, -2}, new byte[]{104, -45, 2, -120, -111, 10}, new byte[]{-11, -102, 54, -94, 84, 109}, new byte[]{100, -29, -63, 3, -108, -62}, new byte[]{-73, 54, 65, 38, 20, -81}, new byte[]{50, 79, 93, -10, 83, 16}, new byte[]{100, 63, -74, -34, 34, 23}, new byte[]{-126, -12, 53, -34, -33, 1}, new byte[]{2, 99, -34, 18, 120, -13}, new byte[]{81, 40, 76, 54, -122, -90}, new byte[]{106, 71, 13, 84, 18, 124}};
    private static final int NO_SECTOR = 99;
    private static final int TOTAL_BLOCKS_BY_SECTOR = 4;
    private int currentAuthSector = NO_SECTOR;
    private MifareClassic mfc;

    public MifareManager(Tag tagFromIntent) {
        this.mfc = MifareClassic.get(tagFromIntent);
    }

    public void open() throws IOException {
        this.mfc.connect();
    }

    public void close() {
        try {
            this.mfc.close();
        } catch (IOException e) {
        }
    }

    public Tag getTag() {
        return this.mfc.getTag();
    }

    public void authenticateSector(int sector) throws IOException, AuthenticateException {
        if (!this.mfc.authenticateSectorWithKeyB(sector, KEY_B_SECTOR[sector])) {
            throw new AuthenticateException(sector);
        }
    }

    public void checkAuthSectorByBlock(int block) throws IOException, AuthenticateException {
        int sector = block / 4;
        if (this.currentAuthSector != sector) {
            authenticateSector(sector);
            this.currentAuthSector = sector;
        }
    }

    public byte[] readBlock(int block) throws IOException, AuthenticateException {
        checkAuthSectorByBlock(block);
        byte[] data = this.mfc.readBlock(block);
        return data;
    }

    public void writeBlock(int block, byte[] data) throws IOException, AuthenticateException {
        checkAuthSectorByBlock(block);
        this.mfc.writeBlock(block, data);
    }

    public void writeValue(int block, int value) throws IOException, AuthenticateException {
        byte[] data = readBlock(block);
        data[0] = (byte) (value >>> 0);
        data[1] = (byte) (value >>> 8);
        data[2] = (byte) (value >>> 16);
        data[3] = (byte) (value >>> 24);
        data[4] = (byte) (data[0] ^ (-1));
        data[5] = (byte) (data[1] ^ (-1));
        data[6] = (byte) (data[2] ^ (-1));
        data[7] = (byte) (data[3] ^ (-1));
        data[8] = data[0];
        data[9] = data[1];
        data[10] = data[2];
        data[11] = data[3];
        writeBlock(block, data);
    }
}
