summary refs log tree commit diff
path: root/crypto/src/tls/crypto/impl/bc/BcTlsRsaEncryptor.cs
blob: 1582ff638518ea0ee06883b2f483a6be07b041fe (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
43
44
45
46
47
using System;

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

namespace Org.BouncyCastle.Tls.Crypto.Impl.BC
{
    internal sealed class BcTlsRsaEncryptor
        : TlsEncryptor
    {
        private static RsaKeyParameters CheckPublicKey(RsaKeyParameters pubKeyRsa)
        {
            if (null == pubKeyRsa || pubKeyRsa.IsPrivate)
                throw new ArgumentException("No public RSA key provided", "pubKeyRsa");

            return pubKeyRsa;
        }

        private readonly BcTlsCrypto m_crypto;
        private readonly RsaKeyParameters m_pubKeyRsa;

        internal BcTlsRsaEncryptor(BcTlsCrypto crypto, RsaKeyParameters pubKeyRsa)
        {
            this.m_crypto = crypto;
            this.m_pubKeyRsa = CheckPublicKey(pubKeyRsa);
        }

        public byte[] Encrypt(byte[] input, int inOff, int length)
        {
            try
            {
                Pkcs1Encoding encoding = new Pkcs1Encoding(new RsaBlindedEngine());
                encoding.Init(true, new ParametersWithRandom(m_pubKeyRsa, m_crypto.SecureRandom));
                return encoding.ProcessBlock(input, inOff, length);
            }
            catch (InvalidCipherTextException e)
            {
                /*
                 * This should never happen, only during decryption.
                 */
                throw new TlsFatalAlert(AlertDescription.internal_error, e);
            }
        }
    }
}