Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

298
Visualizações
Trying to read an RSA public key generated in .NET and JVM and it's failing

, Hi, here is my .NET code:

    public static string ExportPublicKeyFile(this RSA rsa)
    {
        var privateKeyBytes = rsa.ExportRSAPublicKey();
        var builder = new StringBuilder("-----BEGIN PUBLIC KEY-----");

        var base64PrivateKeyString = Convert.ToBase64String(privateKeyBytes);
        var offset = 0;
        const int LINE_LENGTH = 64;

        for (var i = 0; i < base64PrivateKeyString.Length; ++i)
        {
            if (i % (LINE_LENGTH - 1) == 0)
                builder.Append("\n");
            builder.Append(base64PrivateKeyString[i]);
        }
        if (builder[builder.Length-1] != '\n')
            builder.Append("\n");

        builder.AppendLine("-----END PUBLIC KEY-----");
        return builder.ToString();
    }

(There's some extra fluff around the outside to save to a file)

Here's my Kotlin:

class App {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            //App().run()
            //val parts = "/ss/dsa".split('/')
            //println(parts)

            val key = PublicKeyReader.get("C:\\Path\\To\\public.key")

        }

        object PublicKeyReader {
            @kotlin.Throws(Exception::class)
            operator fun get(filename: String): PublicKey {
                val keyBytes: ByteArray = Files.readAllBytes(Paths.get(filename))
                val spec = X509EncodedKeySpec(keyBytes)
                val kf: java.security.KeyFactory = java.security.KeyFactory.getInstance("RSA")
                return kf.generatePublic(spec)
            }
        }

    }
}

The Kotlin isn't running an Android, it's an IntelliJ application currently.

I get the following exception when running:

Caused by: java.security.InvalidKeyException: invalid key format

I have tried removing the BEGIN\END lines manually, and it didn't help.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In the C# code, ExportRSAPublicKey() exports the key in PKCS#1 format, DER encoded. Then the key is PEM encoded (Base64 encoding with line breaks plus header plus footer).
Presumably, with regard to header and footer, the key should be exported in X.509/SPKI format. However, for this purpose the ExportSubjectPublicKeyInfo() method must be used.

Since the Kotlin code expects the key DER encoded, on the Kotlin side a DER encoding has to be performed (removal of header, footer and line breaks, Base64 decoding).
The Kotlin code furthermore expects the key in X.509/SPKI format, which is consistent with the C# code if ExportSubjectPublicKeyInfo() is applied there.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda