【问题标题】:How to use RSAPrivate Key generated by C# in java/ Android?如何在 java/Android 中使用 C# 生成的 RSAPrivate Key?
【发布时间】:2018-02-02 22:56:08
【问题描述】:

我的服务器端(C# 或 .Net)人员给了我一个 xml 格式的 RSA 密钥对,但问题是我无法在我的 Java/Android 中使用给定的密钥 代码,它总是抛出 InValidKeySpec 异常。

我以某种方式管理 RSAPublic 密钥转换为 Java 可理解的 RSAPublic 密钥格式 -

String Modoutput = "pgFkNu7tN3K8VCxxvKMFwqaRJ6I158/aihg1J1p13P5HvVz8Pn2oC7hfdhujlQxHPsV/b8Rc3Snq5KGmC4VBnw==";
            String Expoutput = "AQAB";

            byte[] exponentBytes = Base64.decode(Expoutput);
            byte[] modulusBytes =  Base64.decode(Modoutput);

            BigInteger e = new BigInteger(1, exponentBytes);
            BigInteger m = new BigInteger(1, modulusBytes);
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
            PublicKey mServerPublicKey = rsaKeyFactory.generatePublic(keySpec);

但无法将给定的 RSAPrivate (C#) 密钥转换为可理解的 Java/Android。 我试过这个link 和this

我正在研究这个,但没有成功,需要专家的帮助。

编码愉快 :-)

【问题讨论】:

    标签: java c# android rsa


    【解决方案1】:

    假设您的 XML 中有私有指数,这是在 Java 中生成私有密钥的等效代码。对于 Android 替换 base64 编码部分

    String privateExponentB64 = "...";
    String modulusB64 = "...";
    
    byte[] privateExponentBytes = Base64.getDecoder().decode(privateExponentB64);
    byte[] modulusBytes = Base64.getDecoder().decode(modulusB64);
    
    BigInteger privateExponent = new BigInteger(1, privateExponentBytes);
    BigInteger modulus = new BigInteger(1, modulusBytes);
    RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, privateExponen);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = factory.generatePrivate(privateKeySpec);
    

    【讨论】:

    • 和 没问题,但是

      、、、、、 等其他部分呢?那些不是生成 Java 可理解的私钥所必需的吗??

    • privateExponent(不是公开的)和模数足以创建密钥。使用 值作为 privateExponent
    • 当我尝试使用这个私钥时,得到 BadPaddingexception
    • 报错可能是多种原因,可能与我提供的代码无关。请更新您的问题或使用您用于使用私钥的代码创建一个新问题,以及错误的完整跟踪
    【解决方案2】:

    你可以参考这个链接

    How do I use a C# generated RSA public key in Android?

    好像对你有帮助

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-22
    • 2020-12-09
    • 2020-09-20
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多