package org.bouncycastle.crypto.tls;

import java.io.IOException;
import java.io.OutputStream;

import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSABlindedEngine;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.crypto.params.RSAKeyParameters;

public class TlsRSAUtils
{
    public static byte[] generateEncryptedPreMasterSecret(TlsContext context, RSAKeyParameters rsaServerPublicKey,
        OutputStream output) throws IOException
    {
        /*
         * Choose a PremasterSecret and send it encrypted to the server
         */
        byte[] premasterSecret = new byte[48];
        context.getSecureRandom().nextBytes(premasterSecret);
        TlsUtils.writeVersion(context.getClientVersion(), premasterSecret, 0);

        PKCS1Encoding encoding = new PKCS1Encoding(new RSABlindedEngine());
        encoding.init(true, new ParametersWithRandom(rsaServerPublicKey, context.getSecureRandom()));

        try
        {
            byte[] encryptedPreMasterSecret = encoding.processBlock(premasterSecret, 0, premasterSecret.length);

            if (TlsUtils.isSSL(context))
            {
                // TODO Do any SSLv3 servers actually expect the length?
                output.write(encryptedPreMasterSecret);
            }
            else
            {
                TlsUtils.writeOpaque16(encryptedPreMasterSecret, output);
            }
        }
        catch (InvalidCipherTextException e)
        {
            /*
             * This should never happen, only during decryption.
             */
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }

        return premasterSecret;
    }

    /**
     * @deprecated {@link TlsEncryptionCredentials#decryptPreMasterSecret(byte[])} is expected to decrypt safely
     */
    public static byte[] safeDecryptPreMasterSecret(TlsContext context, TlsEncryptionCredentials encryptionCredentials,
        byte[] encryptedPreMasterSecret) throws IOException
    {
        return encryptionCredentials.decryptPreMasterSecret(encryptedPreMasterSecret);
    }

    public static byte[] safeDecryptPreMasterSecret(TlsContext context, RSAKeyParameters rsaServerPrivateKey,
        byte[] encryptedPreMasterSecret)
    {
        /*
         * RFC 5246 7.4.7.1.
         */
        ProtocolVersion clientVersion = context.getClientVersion();

        // TODO Provide as configuration option?
        boolean versionNumberCheckDisabled = false;

        /*
         * Generate 48 random bytes we can use as a Pre-Master-Secret, if the
         * PKCS1 padding check should fail.
         */
        byte[] M = new byte[48];
        context.getSecureRandom().nextBytes(M);

        try
        {
            PKCS1Encoding encoding = new PKCS1Encoding(new RSABlindedEngine(), M);
            encoding.init(false, new ParametersWithRandom(rsaServerPrivateKey, context.getSecureRandom()));

            M = encoding.processBlock(encryptedPreMasterSecret, 0,
                encryptedPreMasterSecret.length);
        }
        catch (Exception e)
        {
            /*
             * This should never happen since the decryption should never throw an exception
             * and return a random value instead.
             *
             * In any case, a TLS server MUST NOT generate an alert if processing an
             * RSA-encrypted premaster secret message fails, or the version number is not as
             * expected. Instead, it MUST continue the handshake with a randomly generated
             * premaster secret.
             */
        }

        /*
         * If ClientHello.client_version is TLS 1.1 or higher, server implementations MUST
         * check the version number [..].
         */
        if (versionNumberCheckDisabled && clientVersion.isEqualOrEarlierVersionOf(ProtocolVersion.TLSv10))
        {
            /*
             * If the version number is TLS 1.0 or earlier, server
             * implementations SHOULD check the version number, but MAY have a
             * configuration option to disable the check.
             *
             * So there is nothing to do here.
             */
        } else {
            /*
             * Note that explicitly constructing the pre_master_secret with the
             * ClientHello.client_version produces an invalid master_secret if the client
             * has sent the wrong version in the original pre_master_secret.
             */
            TlsUtils.writeVersion(clientVersion, M, 0);
        }
        return M;
    }
}

@@ -376,16 +376,53 @@
 ameters;
+%0Aimport org.bouncycastle.util.Arrays;
 %0A%0Apublic
@@ -2757,17 +2757,24 @@
  byte%5B%5D 
-M
+fallback
  = new b
@@ -2830,13 +2830,63 @@
 tes(
-M
+fallback
 );%0A%0A
+        byte%5B%5D M = Arrays.clone(fallback);%0A
     
@@ -2982,17 +2982,24 @@
 gine(), 
-M
+fallback
 );%0A     
@@ -3025,16 +3025,32 @@
 t(false,
+%0A               
  new Par
@@ -3184,32 +3184,16 @@
 cret, 0,
-%0A               
  encrypt
@@ -4348,21 +4348,37 @@
        %7D
- else
+%0A        else%0A       
  %7B%0A     
@@ -4406,58 +4406,79 @@
   * 
-Note that explicitly construct
+OK, we need to compare the version number 
 in
-g
  the 
-pre_m
+decrypted Pre-M
 aster
-_s
+-S
 ecre
@@ -4507,173 +4507,477 @@
   * 
-ClientHello.
 client
-_v
+V
 ersion 
-produces an invalid m
+received during the handshake. If they don't match, we replace the%0A             * decrypted Pre-M
 aster
-_s
+-S
 ecret 
-if the client%0A             * has sent the wrong version in the original pre_master_secret.%0A     
+with a random one.%0A             */%0A            int correct = (clientVersion.getMajorVersion() %5E (M%5B0%5D & 0xff))%0A                %7C (clientVersion.getMinorVersion() %5E (M%5B1%5D & 0xff));%0A            correct %7C= correct %3E%3E 1;%0A            correct %7C= correct %3E%3E 2;%0A            correct %7C= correct %3E%3E 4;%0A            int mask = ~((correct & 1) - 1);%0A%0A
         
 */%0A 
@@ -4964,34 +4964,38 @@
  - 1);%0A%0A        
+    /
 *
-/
 %0A            Tls
@@ -4995,51 +4995,233 @@
     
-TlsUtils.writeVersion(clientVersion, M, 0);
+ * mask will be all bits set to 0xff if the version number differed.%0A             */%0A            for (int i = 0; i %3C 48; i++)%0A            %7B%0A                M%5Bi%5D = (byte)((M%5Bi%5D & (~mask)) %7C (fallback%5Bi%5D & mask));%0A            %7D
 %0A   

Add the client-version check part of PR https://github.com/bcgit/bc-java/pull/67/, after review.