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

package com.google.crypto.tink.hybrid.subtle;

import java.security.NoSuchAlgorithmException;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.util.Random;
import com.google.crypto.tink.internal.BigIntegerEncoding;
import java.security.SecureRandom;
import java.security.PrivateKey;
import java.security.Key;
import javax.crypto.Cipher;
import java.security.PublicKey;
import java.security.GeneralSecurityException;
import java.math.BigInteger;

class RsaKem
{
    static final byte[] EMPTY_AAD;
    static final int MIN_RSA_KEY_LENGTH_BITS = 2048;
    
    private RsaKem() {
    }
    
    static void validateRsaModulus(final BigInteger mod) throws GeneralSecurityException {
        if (mod.bitLength() < 2048) {
            throw new GeneralSecurityException(String.format("RSA key must be of at least size %d bits, but got %d", 2048, mod.bitLength()));
        }
    }
    
    static int bigIntSizeInBytes(final BigInteger mod) {
        return (mod.bitLength() + 7) / 8;
    }
    
    static byte[] rsaEncrypt(final PublicKey publicKey, final byte[] x) throws GeneralSecurityException {
        final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");
        rsaCipher.init(1, publicKey);
        try {
            return rsaCipher.doFinal(x);
        }
        catch (final RuntimeException e) {
            throw new GeneralSecurityException(e);
        }
    }
    
    static byte[] rsaDecrypt(final PrivateKey privateKey, final byte[] x) throws GeneralSecurityException {
        final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");
        rsaCipher.init(2, privateKey);
        try {
            return rsaCipher.doFinal(x);
        }
        catch (final RuntimeException e) {
            throw new GeneralSecurityException(e);
        }
    }
    
    static byte[] generateSecret(final BigInteger max) {
        final int maxSizeInBytes = bigIntSizeInBytes(max);
        final Random rand = new SecureRandom();
        BigInteger r;
        do {
            r = new BigInteger(max.bitLength(), rand);
        } while (r.signum() <= 0 || r.compareTo(max) >= 0);
        try {
            return BigIntegerEncoding.toBigEndianBytesOfFixedLength(r, maxSizeInBytes);
        }
        catch (final GeneralSecurityException e) {
            throw new IllegalStateException("Unable to convert BigInteger to byte array", e);
        }
    }
    
    static KeyPair generateRsaKeyPair(final int keySize) {
        KeyPairGenerator rsaGenerator;
        try {
            rsaGenerator = KeyPairGenerator.getInstance("RSA");
            rsaGenerator.initialize(keySize);
        }
        catch (final NoSuchAlgorithmException e) {
            throw new IllegalStateException("No support for RSA algorithm.", e);
        }
        return rsaGenerator.generateKeyPair();
    }
    
    static {
        EMPTY_AAD = new byte[0];
    }
}
