I'm trying to create an RSA keypair using BouncyCastle and then try to import generated public key and I'm receiving the following error
AsnContentException: The provided data is tagged with 'Universal' class value '16', but it should have been 'Universal' class value '2'.
The code is the following
RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
AsymmetricCipherKeyPair keys = rsaKeyPairGenerator.GenerateKeyPair();
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
RSA publicRsaKey = RSA.Create();
publicRsaKey.ImportRSAPublicKey(serializedPublicBytes, out _);
Anyone know why am I getting this?
ImportRSAPublicKey
expects a certain specific public key format based on PKCS #1. Your public key is formatted as a SubjectPublicKeyInfo (aka SPKI) Asn1 object, so you should useRSA.ImportSubjectPublicKeyInfo()
to import it. – HomerhomerepublicRsaKey.ImportRSAPublicKey
? – Economically