【问题标题】:Trying to read an RSA public key generated in .NET and JVM and it's failing尝试读取在 .NET 和 JVM 中生成的 RSA 公钥,但失败了
【发布时间】:2021-08-22 18:16:44
【问题描述】:

,嗨,这是我的 .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 行,但没有帮助。

【问题讨论】:

    标签: .net jvm rsa


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,ExportSubjectPublicKeyInfo 是关键(形象地说)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 2011-07-11
    • 2017-08-14
    相关资源
    最近更新 更多