I am creating a set of RSA keys in Python with the Crypto library, then exporting the public key, and sending it to a .NET Core 6 application. But .NET is having trouble reading the public key.
Python Crypto library code - this code is running on a Ubuntu Linux development PC:
key = RSA.generate(2048)
public_key = base64.b64encode(key.publickey().exportKey()).decode('utf8')
C# code - this is running on a Windows 10 development PC:
byte[] publicKeyBytes = Convert.FromBase64String(base64PublicKey);
RSA rsa = RSA.Create();
rsa.ImportRSAPublicKey(publicKeyBytes, out int bytesRead);
The error I received is:
AsnContentException: The provided data is tagged with 'Universal' class value '13', but it should have been 'Universal' class value '16'.
Looking at this SO article, and at this GitHub issue, it looked like I needed a different import method. So I also tried changing the last line to:
rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out int bytesRead);
But I got the exact same error. Only the stacktrace was a little different because it was using a different provider.
If it helps, below is a link to the full help text for the Crypto library's export_key() method. But this is the part I thought was most relevant, and what made me think that ImportSubjectPublicKeyInfo() would work:
This (the pkcs) parameter is ignored for a public key. For DER and PEM, an ASN.1 DER SubjectPublicKeyInfo structure is always used.
Edit: this might be related to encoding, or possibly a little endian vs big endian issue between libraries...
Here is a link to the full description of the exportKey() function.
Edit: the important part turned out to be the format parameter defaults to PEM formatting.