Home > database >  x509Certificate to RsaKeyParameters for encrypt data
x509Certificate to RsaKeyParameters for encrypt data

Time:07-27

I'm trying to encrypt data with BouncyCastle in VB so i take for reference this answer example code and have something like this:

        Dim cerReader = New PemReader(File.OpenText("the\route\certificate.cer"))
        Dim rsaPub = CType(cerReader.ReadObject(), Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)
        Dim encrypter = New OaepEncoding(New RsaEngine(), New Sha256Digest(), New Sha256Digest(), Nothing)
        encrypter.Init(True, rsaPub)
        Dim cipher = encrypter.ProcessBlock(data, 0, data.Length)
        Return Convert.ToBase64String(cipher)

but in the line:

Dim rsaPub = CType(cerReader.ReadObject(), Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)

gives me this error:

Cannot cast an object of type 'Org.BouncyCastle.X509.X509Certificate' to type 'Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters'.

and i can't found in the docs some example o make that cast or encrypt using .cer just .pem that i think is the same but doesn't work. Someone have a idea of what can I do?

CodePudding user response:

The extension .cer is ambiguous, sometimes it means a PEM encoded, sometimes a DER encoded certificate. Since you are applying a PemReader I assume you are using a PEM encoded certificate.
On the linked site a PEM encoded public key is imported, while here a certificate is imported. For this the second line has to be replaced by:

Imports Org.BouncyCastle.X509
...
Dim rsaPub = DirectCast(cerReader.ReadObject(), X509Certificate).GetPublicKey()

With this the PemReader imports an X509Certificate whose public key is fetched with GetPublicKey(). The rest of the code does not need to be changed.

  • Related