尝试读取 .NET 和 JVM 中生成的 RSA public 密钥,但失败了

Trying to read an RSA public key generated in .NET and JVM and it's failing

,嗨,这是我的 .NET 代码:

    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();
    }

(外面有一些多余的绒毛可以保存到文件中)

这是我的 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)
            }
        }

    }
}

Kotlin 不是 运行 Android,它目前是一个 IntelliJ 应用程序。

当 运行 时出现以下异常:

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

我试过手动删除 BEGIN\END 行,但没用。

在 C# 代码中,ExportRSAPublicKey() 以 DER 编码的 PKCS#1 格式导出密钥。然后对密钥进行 PEM 编码(Base64 编码,带换行符加页眉加页脚)。
据推测,关于页眉和页脚,密钥应该以 X.509/SPKI 格式导出。但是,为此必须使用 ExportSubjectPublicKeyInfo() 方法。

由于 Kotlin 代码需要 DER 编码的密钥,因此在 Kotlin 端必须执行 DER 编码(删除页眉、页脚和换行符,Base64 解码)。
Kotlin 代码还需要 X.509/SPKI 格式的密钥,如果在那里应用 ExportSubjectPublicKeyInfo(),这与 C# 代码一致。