Show / Hide Table of Contents

FormatPkcs1Encrypt Method

FormatPkcs1Encrypt(ReadOnlySpan<byte>, int)

Build the input data into a PKCS #1 v1.5 formatted block for encryption (see RFC 8017).

C#
public static byte[] FormatPkcs1Encrypt(ReadOnlySpan<byte> inputData, int keySizeBits)

Parameters

Type Name Description
ReadOnlySpan<byte> inputData

The data to format.

int keySizeBits

The size of the key used, in bits. This value must be one of the RsaFormat.KeySizeBits-x- values.

Returns

byte[]

A new byte array containing the formatted data.

Exceptions

Type Condition
ArgumentException

The data length is too long for the key size, or the keySizeBits is not supported.

Remarks

This method will build a new buffer that is keySizeBits long and contains the following data.

00 || 02 || PS || 00 || input data

where PS consists of non-zero random bytes
that is:

00 || 02 || non-zero random bytes || 00 || input data

This method supports only keySizeBits values that are defined in this class as KeySizeBits-x-, such as RsaFormat.KeySizeBits1024 (x=1024). You can use one of these values or simply the actual key size in bits. For example, if the key size in bits is 1024, then either RsaFormat.KeySizeBits1024 or 1024 are valid input to this method.

The standard specifies that PS must be at least 8 bytes long. Hence, for a 1024-bit key, the maximum input data length is 117 bytes. For a 2048-bit key, the maximum input data length is 245 bytes.

1024-bit key:
128-byte buffer: 00 01 || x1 x2 x3 x4 x5 x6 x7 x8 || 00 || 117 bytes
         128 =     2    +             8            +  1  +  117

2048-bit key: 256-byte buffer: 00 01 || x1 x2 x3 x4 x5 x6 x7 x8 || 00 || 245 bytes 256 = 2 + 8 + 1 + 245

This method will use the random number generator from CryptographyProviders to generate the random bytes.

For example, if the inputData is 32 bytes long, and the keySizeBits is 1024, the result of this method will look like the following.

00 01 83 62 10 11 98 03 08 80 90 77 43 61 63 23
34 86 98 07 36 44 56 56 10 01 33 01 24 07 13 20
72 39 55 89 50 14 46 82 17 43 55 40 36 92 42 06
06 18 44 86 29 38 36 67 22 91 40 51 16 40 17 18
56 14 55 25 26 33 21 24 14 08 45 90 85 93 10 77
49 22 53 88 08 12 10 47 84 20 48 27 29 7A 14 00
01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10
11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20

Because this method creates a new byte array, and it contains sensitive data, it is a good idea to overwrite the buffer when done with it.

CryptographicOperations.ZeroMemory(formattedData);
In this article
Back to top Generated by DocFX