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

package com.google.crypto.tink.jwt.internal;

import com.google.crypto.tink.internal.Util;
import com.google.crypto.tink.internal.MutableSerializationRegistry;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.ExtensionRegistryLite;
import com.google.crypto.tink.util.SecretBigInteger;
import com.google.crypto.tink.proto.KeyData;
import javax.annotation.Nullable;
import com.google.crypto.tink.SecretKeyAccess;
import com.google.crypto.tink.proto.KeyTemplate;
import java.security.GeneralSecurityException;
import com.google.crypto.tink.proto.JwtRsaSsaPkcs1KeyFormat;
import com.google.crypto.tink.internal.BigIntegerEncoding;
import com.google.protobuf.ByteString;
import java.math.BigInteger;
import com.google.crypto.tink.proto.OutputPrefixType;
import com.google.crypto.tink.proto.JwtRsaSsaPkcs1Algorithm;
import com.google.crypto.tink.internal.EnumTypeProtoConverter;
import com.google.crypto.tink.jwt.JwtRsaSsaPkcs1PrivateKey;
import com.google.crypto.tink.internal.KeyParser;
import com.google.crypto.tink.internal.ProtoKeySerialization;
import com.google.crypto.tink.jwt.JwtRsaSsaPkcs1PublicKey;
import com.google.crypto.tink.internal.KeySerializer;
import com.google.crypto.tink.internal.ParametersParser;
import com.google.crypto.tink.internal.ProtoParametersSerialization;
import com.google.crypto.tink.jwt.JwtRsaSsaPkcs1Parameters;
import com.google.crypto.tink.internal.ParametersSerializer;
import com.google.crypto.tink.util.Bytes;
import com.google.crypto.tink.AccessesPartialKey;

@AccessesPartialKey
public final class JwtRsaSsaPkcs1ProtoSerialization
{
    private static final String PRIVATE_TYPE_URL = "type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PrivateKey";
    private static final Bytes PRIVATE_TYPE_URL_BYTES;
    private static final String PUBLIC_TYPE_URL = "type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PublicKey";
    private static final Bytes PUBLIC_TYPE_URL_BYTES;
    private static final ParametersSerializer<JwtRsaSsaPkcs1Parameters, ProtoParametersSerialization> PARAMETERS_SERIALIZER;
    private static final ParametersParser<ProtoParametersSerialization> PARAMETERS_PARSER;
    private static final KeySerializer<JwtRsaSsaPkcs1PublicKey, ProtoKeySerialization> PUBLIC_KEY_SERIALIZER;
    private static final KeyParser<ProtoKeySerialization> PUBLIC_KEY_PARSER;
    private static final KeySerializer<JwtRsaSsaPkcs1PrivateKey, ProtoKeySerialization> PRIVATE_KEY_SERIALIZER;
    private static final KeyParser<ProtoKeySerialization> PRIVATE_KEY_PARSER;
    private static final EnumTypeProtoConverter<JwtRsaSsaPkcs1Algorithm, JwtRsaSsaPkcs1Parameters.Algorithm> ALGORITHM_CONVERTER;
    
    private static OutputPrefixType toProtoOutputPrefixType(final JwtRsaSsaPkcs1Parameters parameters) {
        if (parameters.getKidStrategy().equals(JwtRsaSsaPkcs1Parameters.KidStrategy.BASE64_ENCODED_KEY_ID)) {
            return OutputPrefixType.TINK;
        }
        return OutputPrefixType.RAW;
    }
    
    private static ByteString encodeBigInteger(final BigInteger i) {
        final byte[] encoded = BigIntegerEncoding.toBigEndianBytes(i);
        return ByteString.copyFrom(encoded);
    }
    
    private static JwtRsaSsaPkcs1KeyFormat getProtoKeyFormat(final JwtRsaSsaPkcs1Parameters parameters) throws GeneralSecurityException {
        if (!parameters.getKidStrategy().equals(JwtRsaSsaPkcs1Parameters.KidStrategy.IGNORED) && !parameters.getKidStrategy().equals(JwtRsaSsaPkcs1Parameters.KidStrategy.BASE64_ENCODED_KEY_ID)) {
            throw new GeneralSecurityException("Unable to serialize Parameters object with KidStrategy " + parameters.getKidStrategy());
        }
        return JwtRsaSsaPkcs1KeyFormat.newBuilder().setVersion(0).setAlgorithm(JwtRsaSsaPkcs1ProtoSerialization.ALGORITHM_CONVERTER.toProtoEnum(parameters.getAlgorithm())).setModulusSizeInBits(parameters.getModulusSizeBits()).setPublicExponent(encodeBigInteger(parameters.getPublicExponent())).build();
    }
    
    private static ProtoParametersSerialization serializeParameters(final JwtRsaSsaPkcs1Parameters parameters) throws GeneralSecurityException {
        final OutputPrefixType outputPrefixType = toProtoOutputPrefixType(parameters);
        return ProtoParametersSerialization.create(KeyTemplate.newBuilder().setTypeUrl("type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PrivateKey").setValue(getProtoKeyFormat(parameters).toByteString()).setOutputPrefixType(outputPrefixType).build());
    }
    
    private static com.google.crypto.tink.proto.JwtRsaSsaPkcs1PublicKey getProtoPublicKey(final JwtRsaSsaPkcs1PublicKey key) throws GeneralSecurityException {
        final com.google.crypto.tink.proto.JwtRsaSsaPkcs1PublicKey.Builder builder = com.google.crypto.tink.proto.JwtRsaSsaPkcs1PublicKey.newBuilder().setVersion(0).setAlgorithm(JwtRsaSsaPkcs1ProtoSerialization.ALGORITHM_CONVERTER.toProtoEnum(key.getParameters().getAlgorithm())).setN(encodeBigInteger(key.getModulus())).setE(encodeBigInteger(key.getParameters().getPublicExponent()));
        if (key.getParameters().getKidStrategy().equals(JwtRsaSsaPkcs1Parameters.KidStrategy.CUSTOM)) {
            builder.setCustomKid(com.google.crypto.tink.proto.JwtRsaSsaPkcs1PublicKey.CustomKid.newBuilder().setValue(key.getKid().get()).build());
        }
        return builder.build();
    }
    
    private static ProtoKeySerialization serializePublicKey(final JwtRsaSsaPkcs1PublicKey key, @Nullable final SecretKeyAccess access) throws GeneralSecurityException {
        return ProtoKeySerialization.create("type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PublicKey", getProtoPublicKey(key).toByteString(), KeyData.KeyMaterialType.ASYMMETRIC_PUBLIC, toProtoOutputPrefixType(key.getParameters()), key.getIdRequirementOrNull());
    }
    
    private static ByteString encodeSecretBigInteger(final SecretBigInteger i, final SecretKeyAccess access) {
        return encodeBigInteger(i.getBigInteger(access));
    }
    
    private static ProtoKeySerialization serializePrivateKey(final JwtRsaSsaPkcs1PrivateKey key, @Nullable final SecretKeyAccess access) throws GeneralSecurityException {
        final SecretKeyAccess a = SecretKeyAccess.requireAccess(access);
        final com.google.crypto.tink.proto.JwtRsaSsaPkcs1PrivateKey protoPrivateKey = com.google.crypto.tink.proto.JwtRsaSsaPkcs1PrivateKey.newBuilder().setVersion(0).setPublicKey(getProtoPublicKey(key.getPublicKey())).setD(encodeSecretBigInteger(key.getPrivateExponent(), a)).setP(encodeSecretBigInteger(key.getPrimeP(), a)).setQ(encodeSecretBigInteger(key.getPrimeQ(), a)).setDp(encodeSecretBigInteger(key.getPrimeExponentP(), a)).setDq(encodeSecretBigInteger(key.getPrimeExponentQ(), a)).setCrt(encodeSecretBigInteger(key.getCrtCoefficient(), a)).build();
        return ProtoKeySerialization.create("type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PrivateKey", protoPrivateKey.toByteString(), KeyData.KeyMaterialType.ASYMMETRIC_PRIVATE, toProtoOutputPrefixType(key.getParameters()), key.getIdRequirementOrNull());
    }
    
    private static BigInteger decodeBigInteger(final ByteString data) {
        return BigIntegerEncoding.fromUnsignedBigEndianBytes(data.toByteArray());
    }
    
    private static void validateVersion(final int version) throws GeneralSecurityException {
        if (version != 0) {
            throw new GeneralSecurityException("Parsing failed: unknown version " + version);
        }
    }
    
    private static JwtRsaSsaPkcs1Parameters parseParameters(final ProtoParametersSerialization serialization) throws GeneralSecurityException {
        if (!serialization.getKeyTemplate().getTypeUrl().equals("type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PrivateKey")) {
            throw new IllegalArgumentException("Wrong type URL in call to JwtRsaSsaPkcs1ProtoSerialization.parseParameters: " + serialization.getKeyTemplate().getTypeUrl());
        }
        JwtRsaSsaPkcs1KeyFormat format;
        try {
            format = JwtRsaSsaPkcs1KeyFormat.parseFrom(serialization.getKeyTemplate().getValue(), ExtensionRegistryLite.getEmptyRegistry());
        }
        catch (final InvalidProtocolBufferException e) {
            throw new GeneralSecurityException("Parsing JwtRsaSsaPkcs1Parameters failed: ", e);
        }
        validateVersion(format.getVersion());
        JwtRsaSsaPkcs1Parameters.KidStrategy kidStrategy = null;
        if (serialization.getKeyTemplate().getOutputPrefixType().equals(OutputPrefixType.TINK)) {
            kidStrategy = JwtRsaSsaPkcs1Parameters.KidStrategy.BASE64_ENCODED_KEY_ID;
        }
        if (serialization.getKeyTemplate().getOutputPrefixType().equals(OutputPrefixType.RAW)) {
            kidStrategy = JwtRsaSsaPkcs1Parameters.KidStrategy.IGNORED;
        }
        if (kidStrategy == null) {
            throw new GeneralSecurityException("Invalid OutputPrefixType for JwtHmacKeyFormat");
        }
        return JwtRsaSsaPkcs1Parameters.builder().setKidStrategy(kidStrategy).setAlgorithm(JwtRsaSsaPkcs1ProtoSerialization.ALGORITHM_CONVERTER.fromProtoEnum(format.getAlgorithm())).setPublicExponent(decodeBigInteger(format.getPublicExponent())).setModulusSizeBits(format.getModulusSizeInBits()).build();
    }
    
    private static JwtRsaSsaPkcs1PublicKey getPublicKeyFromProto(final com.google.crypto.tink.proto.JwtRsaSsaPkcs1PublicKey protoKey, final OutputPrefixType outputPrefixType, @Nullable final Integer idRequirement) throws GeneralSecurityException {
        validateVersion(protoKey.getVersion());
        final JwtRsaSsaPkcs1Parameters.Builder parametersBuilder = JwtRsaSsaPkcs1Parameters.builder();
        final JwtRsaSsaPkcs1PublicKey.Builder keyBuilder = JwtRsaSsaPkcs1PublicKey.builder();
        if (outputPrefixType.equals(OutputPrefixType.TINK)) {
            if (protoKey.hasCustomKid()) {
                throw new GeneralSecurityException("Keys serialized with OutputPrefixType TINK should not have a custom kid");
            }
            if (idRequirement == null) {
                throw new GeneralSecurityException("Keys serialized with OutputPrefixType TINK need an ID Requirement");
            }
            parametersBuilder.setKidStrategy(JwtRsaSsaPkcs1Parameters.KidStrategy.BASE64_ENCODED_KEY_ID);
            keyBuilder.setIdRequirement(idRequirement);
        }
        else if (outputPrefixType.equals(OutputPrefixType.RAW)) {
            if (protoKey.hasCustomKid()) {
                parametersBuilder.setKidStrategy(JwtRsaSsaPkcs1Parameters.KidStrategy.CUSTOM);
                keyBuilder.setCustomKid(protoKey.getCustomKid().getValue());
            }
            else {
                parametersBuilder.setKidStrategy(JwtRsaSsaPkcs1Parameters.KidStrategy.IGNORED);
            }
        }
        final BigInteger modulus = decodeBigInteger(protoKey.getN());
        final int modulusSizeInBits = modulus.bitLength();
        parametersBuilder.setAlgorithm(JwtRsaSsaPkcs1ProtoSerialization.ALGORITHM_CONVERTER.fromProtoEnum(protoKey.getAlgorithm())).setPublicExponent(decodeBigInteger(protoKey.getE())).setModulusSizeBits(modulusSizeInBits);
        keyBuilder.setModulus(modulus).setParameters(parametersBuilder.build());
        return keyBuilder.build();
    }
    
    private static JwtRsaSsaPkcs1PublicKey parsePublicKey(final ProtoKeySerialization serialization, @Nullable final SecretKeyAccess access) throws GeneralSecurityException {
        if (!serialization.getTypeUrl().equals("type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PublicKey")) {
            throw new IllegalArgumentException("Wrong type URL in call to JwtRsaSsaPkcs1ProtoSerialization.parsePublicKey: " + serialization.getTypeUrl());
        }
        try {
            final com.google.crypto.tink.proto.JwtRsaSsaPkcs1PublicKey protoKey = com.google.crypto.tink.proto.JwtRsaSsaPkcs1PublicKey.parseFrom(serialization.getValue(), ExtensionRegistryLite.getEmptyRegistry());
            return getPublicKeyFromProto(protoKey, serialization.getOutputPrefixType(), serialization.getIdRequirementOrNull());
        }
        catch (final InvalidProtocolBufferException e) {
            throw new GeneralSecurityException("Parsing JwtRsaSsaPkcs1PublicKey failed");
        }
    }
    
    private static SecretBigInteger decodeSecretBigInteger(final ByteString data, final SecretKeyAccess access) {
        return SecretBigInteger.fromBigInteger(BigIntegerEncoding.fromUnsignedBigEndianBytes(data.toByteArray()), access);
    }
    
    private static JwtRsaSsaPkcs1PrivateKey parsePrivateKey(final ProtoKeySerialization serialization, @Nullable final SecretKeyAccess access) throws GeneralSecurityException {
        if (!serialization.getTypeUrl().equals("type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PrivateKey")) {
            throw new IllegalArgumentException("Wrong type URL in call to JwtRsaSsaPkcs1ProtoSerialization.parsePrivateKey: " + serialization.getTypeUrl());
        }
        try {
            final com.google.crypto.tink.proto.JwtRsaSsaPkcs1PrivateKey protoKey = com.google.crypto.tink.proto.JwtRsaSsaPkcs1PrivateKey.parseFrom(serialization.getValue(), ExtensionRegistryLite.getEmptyRegistry());
            validateVersion(protoKey.getVersion());
            final JwtRsaSsaPkcs1PublicKey publicKey = getPublicKeyFromProto(protoKey.getPublicKey(), serialization.getOutputPrefixType(), serialization.getIdRequirementOrNull());
            final SecretKeyAccess a = SecretKeyAccess.requireAccess(access);
            return JwtRsaSsaPkcs1PrivateKey.builder().setPublicKey(publicKey).setPrimes(decodeSecretBigInteger(protoKey.getP(), a), decodeSecretBigInteger(protoKey.getQ(), a)).setPrivateExponent(decodeSecretBigInteger(protoKey.getD(), a)).setPrimeExponents(decodeSecretBigInteger(protoKey.getDp(), a), decodeSecretBigInteger(protoKey.getDq(), a)).setCrtCoefficient(decodeSecretBigInteger(protoKey.getCrt(), a)).build();
        }
        catch (final InvalidProtocolBufferException e) {
            throw new GeneralSecurityException("Parsing JwtRsaSsaPkcs1PrivateKey failed");
        }
    }
    
    public static void register() throws GeneralSecurityException {
        register(MutableSerializationRegistry.globalInstance());
    }
    
    public static void register(final MutableSerializationRegistry registry) throws GeneralSecurityException {
        registry.registerParametersSerializer(JwtRsaSsaPkcs1ProtoSerialization.PARAMETERS_SERIALIZER);
        registry.registerParametersParser(JwtRsaSsaPkcs1ProtoSerialization.PARAMETERS_PARSER);
        registry.registerKeySerializer(JwtRsaSsaPkcs1ProtoSerialization.PUBLIC_KEY_SERIALIZER);
        registry.registerKeyParser(JwtRsaSsaPkcs1ProtoSerialization.PUBLIC_KEY_PARSER);
        registry.registerKeySerializer(JwtRsaSsaPkcs1ProtoSerialization.PRIVATE_KEY_SERIALIZER);
        registry.registerKeyParser(JwtRsaSsaPkcs1ProtoSerialization.PRIVATE_KEY_PARSER);
    }
    
    private JwtRsaSsaPkcs1ProtoSerialization() {
    }
    
    static {
        PRIVATE_TYPE_URL_BYTES = Util.toBytesFromPrintableAscii("type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PrivateKey");
        PUBLIC_TYPE_URL_BYTES = Util.toBytesFromPrintableAscii("type.googleapis.com/google.crypto.tink.JwtRsaSsaPkcs1PublicKey");
        PARAMETERS_SERIALIZER = ParametersSerializer.create(JwtRsaSsaPkcs1ProtoSerialization::serializeParameters, JwtRsaSsaPkcs1Parameters.class, ProtoParametersSerialization.class);
        PARAMETERS_PARSER = ParametersParser.create(JwtRsaSsaPkcs1ProtoSerialization::parseParameters, JwtRsaSsaPkcs1ProtoSerialization.PRIVATE_TYPE_URL_BYTES, ProtoParametersSerialization.class);
        PUBLIC_KEY_SERIALIZER = KeySerializer.create(JwtRsaSsaPkcs1ProtoSerialization::serializePublicKey, JwtRsaSsaPkcs1PublicKey.class, ProtoKeySerialization.class);
        PUBLIC_KEY_PARSER = KeyParser.create(JwtRsaSsaPkcs1ProtoSerialization::parsePublicKey, JwtRsaSsaPkcs1ProtoSerialization.PUBLIC_TYPE_URL_BYTES, ProtoKeySerialization.class);
        PRIVATE_KEY_SERIALIZER = KeySerializer.create(JwtRsaSsaPkcs1ProtoSerialization::serializePrivateKey, JwtRsaSsaPkcs1PrivateKey.class, ProtoKeySerialization.class);
        PRIVATE_KEY_PARSER = KeyParser.create(JwtRsaSsaPkcs1ProtoSerialization::parsePrivateKey, JwtRsaSsaPkcs1ProtoSerialization.PRIVATE_TYPE_URL_BYTES, ProtoKeySerialization.class);
        ALGORITHM_CONVERTER = EnumTypeProtoConverter.builder().add(JwtRsaSsaPkcs1Algorithm.RS256, JwtRsaSsaPkcs1Parameters.Algorithm.RS256).add(JwtRsaSsaPkcs1Algorithm.RS384, JwtRsaSsaPkcs1Parameters.Algorithm.RS384).add(JwtRsaSsaPkcs1Algorithm.RS512, JwtRsaSsaPkcs1Parameters.Algorithm.RS512).build();
    }
}
