// 
// Decompiled by Procyon v0.6.0
// 

package com.google.crypto.tink.internal;

import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.math.BigInteger;

public final class BigIntegerEncoding
{
    public static byte[] toBigEndianBytes(final BigInteger n) {
        if (n.signum() == -1) {
            throw new IllegalArgumentException("n must not be negative");
        }
        return n.toByteArray();
    }
    
    public static byte[] toUnsignedBigEndianBytes(final BigInteger n) {
        if (n.signum() == -1) {
            throw new IllegalArgumentException("n must not be negative");
        }
        final byte[] twosComplement = n.toByteArray();
        if (twosComplement[0] == 0) {
            return Arrays.copyOfRange(twosComplement, 1, twosComplement.length);
        }
        return twosComplement;
    }
    
    public static byte[] toBigEndianBytesOfFixedLength(final BigInteger n, final int length) throws GeneralSecurityException {
        if (n.signum() == -1) {
            throw new IllegalArgumentException("integer must be nonnegative");
        }
        final byte[] b = n.toByteArray();
        if (b.length == length) {
            return b;
        }
        if (b.length > length + 1) {
            throw new GeneralSecurityException("integer too large");
        }
        if (b.length != length + 1) {
            final byte[] res = new byte[length];
            System.arraycopy(b, 0, res, length - b.length, b.length);
            return res;
        }
        if (b[0] == 0) {
            return Arrays.copyOfRange(b, 1, b.length);
        }
        throw new GeneralSecurityException("integer too large");
    }
    
    public static BigInteger fromUnsignedBigEndianBytes(final byte[] bytes) {
        return new BigInteger(1, bytes);
    }
    
    private BigIntegerEncoding() {
    }
}
