有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java/Android中使用C#生成的私钥?

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

不知怎的,我通过这种方式将RSA公钥转换成Java公钥格式-

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可理解。 我试过这个{a1}和{a2}

我正在研究这个问题,但没有取得任何成功,需要专家的帮助

快乐编码:-)


共 (2) 个答案

  1. # 2 楼答案

    假设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);