summary refs log tree commit diff
path: root/Crypto/src/crypto/tls/TlsRsaUtilities.cs
blob: 4450ba452e8aac0cd96485b0b6b45d887bb987c6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.IO;

using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Security;

namespace Org.BouncyCastle.Crypto.Tls
{
	public abstract class TlsRsaUtilities
	{
		public static byte[] GenerateEncryptedPreMasterSecret(SecureRandom random,
			RsaKeyParameters rsaServerPublicKey, Stream output)
		{
			/*
			 * Choose a PremasterSecret and send it encrypted to the server
			 */
			byte[] premasterSecret = new byte[48];
			random.NextBytes(premasterSecret);
			TlsUtilities.WriteVersion(premasterSecret, 0);

			Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine());
			encoding.Init(true, new ParametersWithRandom(rsaServerPublicKey, random));

			try
			{
				byte[] keData = encoding.ProcessBlock(premasterSecret, 0, premasterSecret.Length);
                TlsUtilities.WriteOpaque16(keData, output);
			}
			catch (InvalidCipherTextException)
			{
				/*
				* This should never happen, only during decryption.
				*/
				throw new TlsFatalAlert(AlertDescription.internal_error);
			}

			return premasterSecret;
		}
	}
}