生成 RSA 密钥对并从 Public 中提取模数和指数 输入 Android

Generating an RSA KeyPair and extracting modulus and exponent from Public Key in Android

我在 Android 中生成了一个 Public 私钥对。现在我需要将我的 Public 密钥发送回服务器以与 RSA 加密进行通信。但是,我正在与 .NET 服务器(在 C# 中)通信。因此,我需要按以下格式发送我的 Public 密钥:

<RSAKeyValue><Modulus>Modulus In Base 64</Modulus><Exponent>Exponent in Base 64</Exponent></RSAKeyValue>

我使用以下代码生成密钥对:

public static void generateKey() {

    try 
    {
        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        final KeyPair key = keyGen.generateKeyPair();
        privateKey = key.getPrivate();
        publicKey = key.getPublic();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

如何提取刚刚生成的 Public 密钥的模数和指数?

没有本地 Android 方法来解决我的问题。为了提取生成的 Public 键的模数和指数,我使用了以下代码,它将 Android Public 键作为输入,并在 . NET XML 格式:

   public static String getPublicKeyAsXml(PublicKey publicKey) throws Exception

     {

        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec ks = kf.getKeySpec(publicKey, RSAPublicKeySpec.class);
        BigInteger modulus = ks.getModulus();
        BigInteger exponent = ks.getPublicExponent();
        byte[] modByte = modulus.toByteArray();
        byte[] expByte = exponent.toByteArray();
        modByte = testBytes(modByte);
        expByte = testBytes(expByte);
        String encodedModulus = Base64.encodeToString(modByte, Base64.NO_WRAP);
        String encodedExponent = Base64.encodeToString(expByte, Base64.NO_WRAP);
        String publicKeyAsXML = "<RSAKeyValue>" +
                "<Modulus>" + encodedModulus + "</Modulus>" +
                "<Exponent>" + encodedExponent + "</Exponent>" +
                "</RSAKeyValue>";

        return publicKeyAsXML;
    }