I'm trying to "manually" compute how the premaster_secret is computed using the RSA key exchange in TLS 1.2, but can't manage to make numbers meet. I am using Scapy SSL to generate a TLS session:

  • I retrieve the e and n parameters from the first certificate's pubKey (Certificate message)
  • I retrieve the premaster_secret from Scapy
  • I compute (premaster_secrete mod n)
  • I compare this result to the Encrypted Premaster sent in the Client Key Exchange message, but it is never the same

Am I missing something?

  • 2
    I think the problem is that you are using unpadded "textbook RSA" vs. actual padded RSA. – StackzOfZtuff May 10 '16 at 6:32
  • Yes, pkcs#1 v1.5 – Z.T. May 10 '16 at 10:20
  • That's indeed what I was missing. I'm almost there. It works for a site such as www.wikipedia.org but not www.google.com - even though I am using its certificate to get the RSA public key. – user7094 May 11 '16 at 1:49

Thanks to the responses I was able to get it working. Here is some Python pseudo-code which explains the algorithm actually used by TLS 1.2:

# Come up with a random premaster_secret
# It needs to start with the TLS version (0x0303)
premaster_secret = '\x03\x03' + os.urandom(46)

# Retrieve the RSA parameters from the certificate public key
RSA_n = ...
RSA_e = ...

# Encodes premaster_secret using PKCS#1 v1.5
premaster_secret = '\x00\x02' + '\x12' * (256 - 3 - len(premaster_secret)) + '\x00' + premaster_secret

# Converts the result into a number and encrypts it
premaster_secret_nb = int(binascii.hexlify(premaster_secret), 16)
encrypted_premaster_secret = pow(premaster_secret_nb, RSA_e, RSA_n)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.