C# CNG RSA classes
Not my normal Identity stuff but I’ve been working on a cryptography project using the CNG (Certificate Next Generation) classes with .Net Framework 4.7.2 and there is very little documentation. So I thought I would do a write-up and some sample code.
This is a command line application.
The gist is here.
The code:
The output:
Private key — length = 539
525341320008000003000000000100008000000080000000010001F51B87623115AF27903A7E677B016987F4DDBD8BD3E81C08DBF247CFE1EF752DFAE4D0B144571560743F39D643EA3EE8EABC5C128A17D7E1471135EA1E5E938A6A0B8EBD62F7C987A746C152B6348E5EB7949618ED78C0BA3CD601021288B8DC22257D782EF8B61DCD6A35F85CBC426E11DE0AA2C6524498EAE1D567A6D0588794DD44D58C7AB4E4BEFDB3B271756919B000AB8E5624F50079D366E21DD17E5A2C2946806A962D49C0C6BA9C15A33F5563E6079FDCDD25B01B6B283A49FF3735C1C29F1499297B9E47154062A0FD1A14F5E4057F610EE73C217FACD5C19EDE2373A21357667FFB730E7B1E664FCB61E3E1B19AA8EA2BAE07C110272EA6A44F25F90F536625BDD4F42A8625D1A91AB340914490AE13028C2F0794AA58B7931AD3AA219940897630CD3528DD153DF1788BDAD29B79AC8432767C5A072988B461EDCC7C914EC43711354CB9D00FB0424F2718723A37200F03690B9F25D57AE02C099E4DAD410BB9E258293B084A324D5194DB7538D8F4514370F320A0F66621810BFBF0024EDF0AEA12CD85969220E41863729822EFA9DE534A2D8E12F51E46581436F55925B0E2870ED36A07B07AFFF471918CE35A42BA8A91A77E5EEAAE70EA20CF953C238965868A15543D7674EE82902E696FF090C2D0F1A385715C0448E1B1AE36CF40A44CA0D2440A24D454CAAF49ADD011DDB3A153903FF1B190FEFFEE8F
Public key — length = 283
525341310008000003000000000100000000000000000000010001F51B87623115AF27903A7E677B016987F4DDBD8BD3E81C08DBF247CFE1EF752DFAE4D0B144571560743F39D643EA3EE8EABC5C128A17D7E1471135EA1E5E938A6A0B8EBD62F7C987A746C152B6348E5EB7949618ED78C0BA3CD601021288B8DC22257D782EF8B61DCD6A35F85CBC426E11DE0AA2C6524498EAE1D567A6D0588794DD44D58C7AB4E4BEFDB3B271756919B000AB8E5624F50079D366E21DD17E5A2C2946806A962D49C0C6BA9C15A33F5563E6079FDCDD25B01B6B283A49FF3735C1C29F1499297B9E47154062A0FD1A14F5E4057F610EE73C217FACD5C19EDE2373A21357667FFB730E7B1E664FCB61E3E1B19AA8EA2BAE07C110272EA6A44F25
Encrypt / decrypt works
Signing works
Looking at the public key, we see a length of 283 and we know that for a key length of 2048 bits, the actual key should have a length of 256 bytes i.e. 2018/8.
This gives a header of 27 bytes:
525341310008000003000000000100000000000000000000010001
The first four bytes are the ASCII representation of “RSA1” as per:
`// RsaPublic = 0x31415352 BCRYPT_RSAPUBLIC_MAGIC// RsaPrivate = 0x32415352 BCRYPT_RSAPRIVATE_MAGIC
(Note — little endian).
The private key is 539 i.e. header (27) plus public key (256) plus private key (256).
Note that the first four bytes of the private key are the ASCII representation for the private key i.e. “RSA2”.
Note the structure of RSAParameters:
The public key is simply the exponent and modulus. The rest is used by the private key.
Enjoy!